#!/usr/bin/env node
"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 __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);

// ../node_modules/.pnpm/chalk@5.3.0/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.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
    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.3.0/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" in env || "GITEA_ACTIONS" in env) {
      return 3;
    }
    if (["TRAVIS", "CIRCLECI", "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 version3 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version3 >= 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.3.0/node_modules/chalk/source/vendor/supports-color/index.js"() {
    import_node_process = __toESM(require("node:process"), 1);
    import_node_os = __toESM(require("node:os"), 1);
    import_node_tty = __toESM(require("node: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.3.0/node_modules/chalk/source/utilities.js
function stringReplaceAll(string2, substring, replacer) {
  let index5 = string2.indexOf(substring);
  if (index5 === -1) {
    return string2;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string2.slice(endIndex, index5) + substring + replacer;
    endIndex = index5 + substringLength;
    index5 = string2.indexOf(substring, endIndex);
  } while (index5 !== -1);
  returnValue += string2.slice(endIndex);
  return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string2, prefix2, postfix, index5) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string2[index5 - 1] === "\r";
    returnValue += string2.slice(endIndex, gotCR ? index5 - 1 : index5) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index5 + 1;
    index5 = string2.indexOf("\n", endIndex);
  } while (index5 !== -1);
  returnValue += string2.slice(endIndex);
  return returnValue;
}
var init_utilities = __esm({
  "../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js"() {
  }
});

// ../node_modules/.pnpm/chalk@5.3.0/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.3.0/node_modules/chalk/source/index.js"() {
    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, string2) => {
      if (self2.level <= 0 || !string2) {
        return self2[IS_EMPTY] ? "" : string2;
      }
      let styler = self2[STYLER];
      if (styler === void 0) {
        return string2;
      }
      const { openAll, closeAll } = styler;
      if (string2.includes("\x1B")) {
        while (styler !== void 0) {
          string2 = stringReplaceAll(string2, styler.close, styler.open);
          styler = styler.parent;
        }
      }
      const lfIndex = string2.indexOf("\n");
      if (lfIndex !== -1) {
        string2 = stringEncaseCRLFWithFirstIndex(string2, closeAll, openAll, lfIndex);
      }
      return openAll + string2 + closeAll;
    };
    Object.defineProperties(createChalk.prototype, styles2);
    chalk = createChalk();
    chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
    source_default = chalk;
  }
});

// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json
var require_package = __commonJS({
  "../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json"(exports2, module2) {
    module2.exports = {
      name: "dotenv",
      version: "16.4.5",
      description: "Loads environment variables from .env file",
      main: "lib/main.js",
      types: "lib/main.d.ts",
      exports: {
        ".": {
          types: "./lib/main.d.ts",
          require: "./lib/main.js",
          default: "./lib/main.js"
        },
        "./config": "./config.js",
        "./config.js": "./config.js",
        "./lib/env-options": "./lib/env-options.js",
        "./lib/env-options.js": "./lib/env-options.js",
        "./lib/cli-options": "./lib/cli-options.js",
        "./lib/cli-options.js": "./lib/cli-options.js",
        "./package.json": "./package.json"
      },
      scripts: {
        "dts-check": "tsc --project tests/types/tsconfig.json",
        lint: "standard",
        "lint-readme": "standard-markdown",
        pretest: "npm run lint && npm run dts-check",
        test: "tap tests/*.js --100 -Rspec",
        "test:coverage": "tap --coverage-report=lcov",
        prerelease: "npm test",
        release: "standard-version"
      },
      repository: {
        type: "git",
        url: "git://github.com/motdotla/dotenv.git"
      },
      funding: "https://dotenvx.com",
      keywords: [
        "dotenv",
        "env",
        ".env",
        "environment",
        "variables",
        "config",
        "settings"
      ],
      readmeFilename: "README.md",
      license: "BSD-2-Clause",
      devDependencies: {
        "@definitelytyped/dtslint": "^0.0.133",
        "@types/node": "^18.11.3",
        decache: "^4.6.1",
        sinon: "^14.0.1",
        standard: "^17.0.0",
        "standard-markdown": "^7.1.0",
        "standard-version": "^9.5.0",
        tap: "^16.3.0",
        tar: "^6.1.11",
        typescript: "^4.8.4"
      },
      engines: {
        node: ">=12"
      },
      browser: {
        fs: false
      }
    };
  }
});

// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js
var require_main = __commonJS({
  "../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js"(exports2, module2) {
    var fs7 = require("fs");
    var path4 = require("path");
    var os3 = require("os");
    var crypto7 = require("crypto");
    var packageJson = require_package();
    var version3 = packageJson.version;
    var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
    function parse5(src) {
      const obj = {};
      let lines = src.toString();
      lines = lines.replace(/\r\n?/mg, "\n");
      let match2;
      while ((match2 = LINE.exec(lines)) != null) {
        const key = match2[1];
        let value = match2[2] || "";
        value = value.trim();
        const maybeQuote = value[0];
        value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
        if (maybeQuote === '"') {
          value = value.replace(/\\n/g, "\n");
          value = value.replace(/\\r/g, "\r");
        }
        obj[key] = value;
      }
      return obj;
    }
    function _parseVault(options) {
      const vaultPath = _vaultPath(options);
      const result = DotenvModule.configDotenv({ path: vaultPath });
      if (!result.parsed) {
        const err2 = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
        err2.code = "MISSING_DATA";
        throw err2;
      }
      const keys = _dotenvKey(options).split(",");
      const length = keys.length;
      let decrypted;
      for (let i2 = 0; i2 < length; i2++) {
        try {
          const key = keys[i2].trim();
          const attrs = _instructions(result, key);
          decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
          break;
        } catch (error2) {
          if (i2 + 1 >= length) {
            throw error2;
          }
        }
      }
      return DotenvModule.parse(decrypted);
    }
    function _log(message) {
      console.log(`[dotenv@${version3}][INFO] ${message}`);
    }
    function _warn(message) {
      console.log(`[dotenv@${version3}][WARN] ${message}`);
    }
    function _debug(message) {
      console.log(`[dotenv@${version3}][DEBUG] ${message}`);
    }
    function _dotenvKey(options) {
      if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
        return options.DOTENV_KEY;
      }
      if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
        return process.env.DOTENV_KEY;
      }
      return "";
    }
    function _instructions(result, dotenvKey) {
      let uri;
      try {
        uri = new URL(dotenvKey);
      } catch (error2) {
        if (error2.code === "ERR_INVALID_URL") {
          const err2 = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
          err2.code = "INVALID_DOTENV_KEY";
          throw err2;
        }
        throw error2;
      }
      const key = uri.password;
      if (!key) {
        const err2 = new Error("INVALID_DOTENV_KEY: Missing key part");
        err2.code = "INVALID_DOTENV_KEY";
        throw err2;
      }
      const environment = uri.searchParams.get("environment");
      if (!environment) {
        const err2 = new Error("INVALID_DOTENV_KEY: Missing environment part");
        err2.code = "INVALID_DOTENV_KEY";
        throw err2;
      }
      const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
      const ciphertext = result.parsed[environmentKey];
      if (!ciphertext) {
        const err2 = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
        err2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
        throw err2;
      }
      return { ciphertext, key };
    }
    function _vaultPath(options) {
      let possibleVaultPath = null;
      if (options && options.path && options.path.length > 0) {
        if (Array.isArray(options.path)) {
          for (const filepath of options.path) {
            if (fs7.existsSync(filepath)) {
              possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
            }
          }
        } else {
          possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
        }
      } else {
        possibleVaultPath = path4.resolve(process.cwd(), ".env.vault");
      }
      if (fs7.existsSync(possibleVaultPath)) {
        return possibleVaultPath;
      }
      return null;
    }
    function _resolveHome(envPath) {
      return envPath[0] === "~" ? path4.join(os3.homedir(), envPath.slice(1)) : envPath;
    }
    function _configVault(options) {
      _log("Loading env from encrypted .env.vault");
      const parsed = DotenvModule._parseVault(options);
      let processEnv = process.env;
      if (options && options.processEnv != null) {
        processEnv = options.processEnv;
      }
      DotenvModule.populate(processEnv, parsed, options);
      return { parsed };
    }
    function configDotenv(options) {
      const dotenvPath = path4.resolve(process.cwd(), ".env");
      let encoding = "utf8";
      const debug = Boolean(options && options.debug);
      if (options && options.encoding) {
        encoding = options.encoding;
      } else {
        if (debug) {
          _debug("No encoding is specified. UTF-8 is used by default");
        }
      }
      let optionPaths = [dotenvPath];
      if (options && options.path) {
        if (!Array.isArray(options.path)) {
          optionPaths = [_resolveHome(options.path)];
        } else {
          optionPaths = [];
          for (const filepath of options.path) {
            optionPaths.push(_resolveHome(filepath));
          }
        }
      }
      let lastError;
      const parsedAll = {};
      for (const path5 of optionPaths) {
        try {
          const parsed = DotenvModule.parse(fs7.readFileSync(path5, { encoding }));
          DotenvModule.populate(parsedAll, parsed, options);
        } catch (e2) {
          if (debug) {
            _debug(`Failed to load ${path5} ${e2.message}`);
          }
          lastError = e2;
        }
      }
      let processEnv = process.env;
      if (options && options.processEnv != null) {
        processEnv = options.processEnv;
      }
      DotenvModule.populate(processEnv, parsedAll, options);
      if (lastError) {
        return { parsed: parsedAll, error: lastError };
      } else {
        return { parsed: parsedAll };
      }
    }
    function config(options) {
      if (_dotenvKey(options).length === 0) {
        return DotenvModule.configDotenv(options);
      }
      const vaultPath = _vaultPath(options);
      if (!vaultPath) {
        _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
        return DotenvModule.configDotenv(options);
      }
      return DotenvModule._configVault(options);
    }
    function decrypt(encrypted, keyStr) {
      const key = Buffer.from(keyStr.slice(-64), "hex");
      let ciphertext = Buffer.from(encrypted, "base64");
      const nonce = ciphertext.subarray(0, 12);
      const authTag = ciphertext.subarray(-16);
      ciphertext = ciphertext.subarray(12, -16);
      try {
        const aesgcm = crypto7.createDecipheriv("aes-256-gcm", key, nonce);
        aesgcm.setAuthTag(authTag);
        return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
      } catch (error2) {
        const isRange = error2 instanceof RangeError;
        const invalidKeyLength = error2.message === "Invalid key length";
        const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
        if (isRange || invalidKeyLength) {
          const err2 = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
          err2.code = "INVALID_DOTENV_KEY";
          throw err2;
        } else if (decryptionFailed) {
          const err2 = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
          err2.code = "DECRYPTION_FAILED";
          throw err2;
        } else {
          throw error2;
        }
      }
    }
    function populate(processEnv, parsed, options = {}) {
      const debug = Boolean(options && options.debug);
      const override = Boolean(options && options.override);
      if (typeof parsed !== "object") {
        const err2 = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
        err2.code = "OBJECT_REQUIRED";
        throw err2;
      }
      for (const key of Object.keys(parsed)) {
        if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
          if (override === true) {
            processEnv[key] = parsed[key];
          }
          if (debug) {
            if (override === true) {
              _debug(`"${key}" is already defined and WAS overwritten`);
            } else {
              _debug(`"${key}" is already defined and was NOT overwritten`);
            }
          }
        } else {
          processEnv[key] = parsed[key];
        }
      }
    }
    var DotenvModule = {
      configDotenv,
      _configVault,
      _parseVault,
      config,
      decrypt,
      parse: parse5,
      populate
    };
    module2.exports.configDotenv = DotenvModule.configDotenv;
    module2.exports._configVault = DotenvModule._configVault;
    module2.exports._parseVault = DotenvModule._parseVault;
    module2.exports.config = DotenvModule.config;
    module2.exports.decrypt = DotenvModule.decrypt;
    module2.exports.parse = DotenvModule.parse;
    module2.exports.populate = DotenvModule.populate;
    module2.exports = DotenvModule;
  }
});

// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/env-options.js
var require_env_options = __commonJS({
  "../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/env-options.js"(exports2, module2) {
    var options = {};
    if (process.env.DOTENV_CONFIG_ENCODING != null) {
      options.encoding = process.env.DOTENV_CONFIG_ENCODING;
    }
    if (process.env.DOTENV_CONFIG_PATH != null) {
      options.path = process.env.DOTENV_CONFIG_PATH;
    }
    if (process.env.DOTENV_CONFIG_DEBUG != null) {
      options.debug = process.env.DOTENV_CONFIG_DEBUG;
    }
    if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
      options.override = process.env.DOTENV_CONFIG_OVERRIDE;
    }
    if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
      options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
    }
    module2.exports = options;
  }
});

// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/cli-options.js
var require_cli_options = __commonJS({
  "../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/cli-options.js"(exports2, module2) {
    var re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/;
    module2.exports = function optionMatcher(args) {
      return args.reduce(function(acc, cur) {
        const matches = cur.match(re);
        if (matches) {
          acc[matches[1]] = matches[2];
        }
        return acc;
      }, {});
    };
  }
});

// ../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(x2, y) {
        if (!y)
          return `${CSI}${x2 + 1}G`;
        return `${CSI}${y + 1};${x2 + 1}H`;
      },
      move(x2, y) {
        let ret = "";
        if (x2 < 0)
          ret += `${CSI}${-x2}D`;
        else if (x2 > 0)
          ret += `${CSI}${x2}C`;
        if (y < 0)
          ret += `${CSI}${-y}A`;
        else if (y > 0)
          ret += `${CSI}${y}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 i2 = 0; i2 < count; i2++)
          clear += this.line + (i2 < 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) {
    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 flush() {
        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 = flush;
      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 isSymbol2(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol2(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 __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve2) {
          resolve2(value);
        });
      }
      return new (P || (P = Promise))(function(resolve2, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e2) {
            reject(e2);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e2) {
            reject(e2);
          }
        }
        function step(result) {
          result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault3 = 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 = __importDefault3(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 resolve2;
      let reject;
      const promise = new Promise((res, rej) => {
        resolve2 = res;
        reject = rej;
      });
      return {
        resolve: resolve2,
        reject,
        promise
      };
    };
    exports2.deferred = deferred;
    var Terminal = class {
      constructor(view4, stdin, stdout, closable) {
        this.view = view4;
        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;
          }
          view4.input(str, key);
        };
        this.stdin.on("keypress", keypress);
        this.view.attach(this);
        const { resolve: resolve2, promise } = (0, exports2.deferred)();
        this.resolve = resolve2;
        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(state) {
        if (state === "hide") {
          this.stdout.write(sisteransi_1.cursor.hide);
        } else {
          this.stdout.write(sisteransi_1.cursor.show);
        }
      }
      requestLayout() {
        const string2 = this.view.render(this.status);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string2;
        this.renderFunc(`${clearPrefix}${string2}`);
      }
    };
    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(view4, stdout) {
        this.view = view4;
        this.stdout = stdout;
        this.text = "";
        this.view.attach(this);
      }
      requestLayout() {
        const string2 = this.view.render("pending");
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string2;
        this.stdout.write(`${clearPrefix}${string2}`);
      }
      clear() {
        const string2 = 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}${string2}`);
      }
    };
    exports2.TaskTerminal = TaskTerminal;
    function render10(view4) {
      const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
      if (view4 instanceof Prompt3) {
        const terminal = new Terminal(view4, stdin, stdout, closable);
        terminal.requestLayout();
        return terminal.result();
      }
      stdout.write(`${view4}
`);
      closable.close();
      return;
    }
    exports2.render = render10;
    function renderWithTask7(view4, task) {
      return __awaiter3(this, void 0, void 0, function* () {
        const terminal = new TaskTerminal(view4, process.stdout);
        terminal.requestLayout();
        const result = yield task;
        terminal.clear();
        return result;
      });
    }
    exports2.renderWithTask = renderWithTask7;
    var terminateHandler;
    function onTerminate(callback) {
      terminateHandler = callback;
    }
    exports2.onTerminate = onTerminate;
  }
});

// ../node_modules/.pnpm/zod@3.23.7/node_modules/zod/lib/index.mjs
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      ctx.schemaErrorMap,
      overrideMap,
      overrideMap === errorMap ? void 0 : errorMap
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
function __classPrivateFieldGet(receiver, state, kind, f3) {
  if (kind === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f3) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
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) => {
    var _a, _b;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
  if (args.precision) {
    regex = `${regex}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    regex = `${regex}(\\.\\d+)?`;
  }
  return regex;
}
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, version3) {
  if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version3 === "v6" || !version3) && ipv6Regex.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 = parseInt(val2.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(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(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index5 = 0; index5 < a.length; index5++) {
      const itemA = a[index5];
      const itemB = b[index5];
      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 && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function custom(check2, params = {}, fatal) {
  if (check2)
    return ZodAny.create().superRefine((data, ctx) => {
      var _a, _b;
      if (!check2(data)) {
        const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
        const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
        const p2 = typeof p === "string" ? { message: p } : p;
        ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
      }
    });
  return ZodAny.create();
}
var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, quotelessJson, ZodError, errorMap, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv6Regex, base64Regex, 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, z;
var init_lib = __esm({
  "../node_modules/.pnpm/zod@3.23.7/node_modules/zod/lib/index.mjs"() {
    (function(util2) {
      util2.assertEqual = (val2) => val2;
      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((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
          filtered[k] = obj[k];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e2) {
          return obj[e2];
        });
      };
      util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (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" && 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 = (_2, 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 t2 = typeof data;
      switch (t2) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return 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;
      }
    };
    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 {
      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;
      }
      get errors() {
        return this.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 i2 = 0;
              while (i2 < issue.path.length) {
                const el = issue.path[i2];
                const terminal = i2 === 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];
                i2++;
              }
            }
          }
        };
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof _ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (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;
    };
    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 };
    };
    overrideErrorMap = errorMap;
    makeIssue = (params) => {
      const { data, path: path4, errorMaps, issueData } = params;
      const fullPath = [...path4, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
      for (const map of maps) {
        errorMessage = map(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 s2 of results) {
          if (s2.status === "aborted")
            return INVALID;
          if (s2.status === "dirty")
            status.dirty();
          arrayValue.push(s2.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x2) => x2.status === "aborted";
    isDirty = (x2) => x2.status === "dirty";
    isValid = (x2) => x2.status === "valid";
    isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
    })(errorUtil || (errorUtil = {}));
    ParseInputLazyPath = class {
      constructor(parent, value, path4, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path4;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (this._key instanceof Array) {
            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 {
      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);
      }
      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) {
        var _a;
        const ctx = {
          common: {
            issues: [],
            async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
            contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
          },
          path: (params === null || params === void 0 ? void 0 : 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);
      }
      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 === null || params === void 0 ? void 0 : params.errorMap,
            async: true
          },
          path: (params === null || params === void 0 ? void 0 : 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(check2, 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 = check2(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(check2, refinementData) {
        return this._refinement((val2, ctx) => {
          if (!check2(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);
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this, this._def);
      }
      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}$/;
    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;
    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])$/;
    ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
    base64Regex = /^([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 check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.length < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.length > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "length") {
            const tooBig = input.data.length > check2.value;
            const tooSmall = input.data.length < check2.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check2.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check2.message
                });
              }
              status.dirty();
            }
          } else if (check2.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "url") {
            try {
              new URL(input.data);
            } catch (_a) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "regex") {
            check2.regex.lastIndex = 0;
            const testResult = check2.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "trim") {
            input.data = input.data.trim();
          } else if (check2.kind === "includes") {
            if (!input.data.includes(check2.value, check2.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check2.value, position: check2.position },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check2.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check2.kind === "startsWith") {
            if (!input.data.startsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "endsWith") {
            if (!input.data.endsWith(check2.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check2.value },
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "datetime") {
            const regex = datetimeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "time") {
            const regex = timeRegex(check2);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "ip") {
            if (!isValidIP(input.data, check2.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        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(check2) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        var _a, _b;
        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 === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
          local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : 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 === null || options === void 0 ? void 0 : options.position,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : 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)
        });
      }
      /**
       * @deprecated Use z.string().min(1) instead.
       * @see {@link ZodString.min}
       */
      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 isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      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) => {
      var _a;
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : 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 check2 of this._def.checks) {
          if (check2.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check2.value,
                type: "number",
                inclusive: check2.inclusive,
                exact: false,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check2.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max = null, 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 === null || params === void 0 ? void 0 : 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) {
          input.data = BigInt(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.bigint,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check2.value,
                inclusive: check2.inclusive,
                message: check2.message
              });
              status.dirty();
            }
          } else if (check2.kind === "multipleOf") {
            if (input.data % check2.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check2.value,
                message: check2.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check2) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodBigInt.create = (params) => {
      var _a;
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : 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 === null || params === void 0 ? void 0 : 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 (isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check2 of this._def.checks) {
          if (check2.kind === "min") {
            if (input.data.getTime() < check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check2.message,
                inclusive: true,
                exact: false,
                minimum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check2.kind === "max") {
            if (input.data.getTime() > check2.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check2.message,
                inclusive: true,
                exact: false,
                maximum: check2.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check2);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check2) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check2]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min != null ? new Date(min) : null;
      }
      get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max != null ? new Date(max) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: (params === null || params === void 0 ? void 0 : 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, i2) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i2) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    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);
        return this._cached = { shape, keys };
      }
      _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) => {
              var _a, _b, _c, _d;
              const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : 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(index5) {
        return new _ZodObject({
          ...this._def,
          catchall: index5
        });
      }
      pick(mask) {
        const shape = {};
        util.objectKeys(mask).forEach((key) => {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        util.objectKeys(this.shape).forEach((key) => {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
          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 = {};
        util.objectKeys(this.shape).forEach((key) => {
          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((x2) => !!x2);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    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], index5) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index5, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index5, "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, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    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(),
              errorMap
            ].filter((x2) => !!x2),
            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(),
              errorMap
            ].filter((x2) => !!x2),
            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((e2) => {
              error2.addIssue(makeArgsIssue(args, e2));
              throw error2;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
              error2.addIssue(makeReturnsIssue(result, e2));
              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 {
      constructor() {
        super(...arguments);
        _ZodEnum_cache.set(this, void 0);
      }
      _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 (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").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_cache = /* @__PURE__ */ new WeakMap();
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      constructor() {
        super(...arguments);
        _ZodNativeEnum_cache.set(this, void 0);
      }
      _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 (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").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_cache = /* @__PURE__ */ new WeakMap();
    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 base;
            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 base;
              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(a, b) {
        return new _ZodPipeline({
          in: a,
          out: b,
          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;
    z = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      defaultErrorMap: errorMap,
      setErrorMap,
      getErrorMap,
      makeIssue,
      EMPTY_PATH,
      addIssueToContext,
      ParseStatus,
      INVALID,
      DIRTY,
      OK,
      isAborted,
      isDirty,
      isValid,
      isAsync,
      get util() {
        return util;
      },
      get objectUtil() {
        return objectUtil;
      },
      ZodParsedType,
      getParsedType,
      ZodType,
      datetimeRegex,
      ZodString,
      ZodNumber,
      ZodBigInt,
      ZodBoolean,
      ZodDate,
      ZodSymbol,
      ZodUndefined,
      ZodNull,
      ZodAny,
      ZodUnknown,
      ZodNever,
      ZodVoid,
      ZodArray,
      ZodObject,
      ZodUnion,
      ZodDiscriminatedUnion,
      ZodIntersection,
      ZodTuple,
      ZodRecord,
      ZodMap,
      ZodSet,
      ZodFunction,
      ZodLazy,
      ZodLiteral,
      ZodEnum,
      ZodNativeEnum,
      ZodPromise,
      ZodEffects,
      ZodTransformer: ZodEffects,
      ZodOptional,
      ZodNullable,
      ZodDefault,
      ZodCatch,
      ZodNaN,
      BRAND,
      ZodBranded,
      ZodPipeline,
      ZodReadonly,
      custom,
      Schema: ZodType,
      ZodSchema: ZodType,
      late,
      get ZodFirstPartyTypeKind() {
        return ZodFirstPartyTypeKind;
      },
      coerce,
      any: anyType,
      array: arrayType,
      bigint: bigIntType,
      boolean: booleanType,
      date: dateType,
      discriminatedUnion: discriminatedUnionType,
      effect: effectsType,
      "enum": enumType,
      "function": functionType,
      "instanceof": instanceOfType,
      intersection: intersectionType,
      lazy: lazyType,
      literal: literalType,
      map: mapType,
      nan: nanType,
      nativeEnum: nativeEnumType,
      never: neverType,
      "null": nullType,
      nullable: nullableType,
      number: numberType,
      object: objectType,
      oboolean,
      onumber,
      optional: optionalType,
      ostring,
      pipeline: pipelineType,
      preprocess: preprocessType,
      promise: promiseType,
      record: recordType,
      set: setType,
      strictObject: strictObjectType,
      string: stringType,
      symbol: symbolType,
      transformer: effectsType,
      tuple: tupleType,
      "undefined": undefinedType,
      union: unionType,
      unknown: unknownType,
      "void": voidType,
      NEVER,
      ZodIssueCode,
      quotelessJson,
      ZodError
    });
  }
});

// src/global.ts
function assertUnreachable(x2) {
  throw new Error("Didn't expect to get here");
}
function softAssertUnreachable(x2) {
  return null;
}
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, map) => {
      const result = Object.keys(obj).reduce(function(result2, key) {
        result2[key] = map(obj[key]);
        return result2;
      }, {});
      return result;
    };
    mapKeys = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const newKey = map(key, val2);
          return [newKey, val2];
        })
      );
      return result;
    };
    mapEntries = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const [newKey, newVal] = map(key, val2);
          return [newKey, newVal];
        })
      );
      return result;
    };
    customMapEntries = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val2]) => {
          const [newKey, newVal] = map(key, val2);
          return [newKey, newVal];
        })
      );
      return result;
    };
  }
});

// src/serializer/mysqlSchema.ts
var index, fk, column, tableV3, compositePK, uniqueConstraint, checkConstraint, tableV4, table, viewMeta, view, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
var init_mysqlSchema = __esm({
  "src/serializer/mysqlSchema.ts"() {
    "use strict";
    init_lib();
    init_global();
    index = 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();
    fk = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    column = 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(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk)
    }).strict();
    compositePK = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    tableV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk)
    }).strict();
    table = objectType({
      name: stringType(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk),
      compositePrimaryKeys: recordType(stringType(), compositePK),
      uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
      checkConstraint: recordType(stringType(), checkConstraint).default({})
    }).strict();
    viewMeta = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    view = objectType({
      name: stringType(),
      columns: recordType(stringType(), column),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict().merge(viewMeta);
    kitInternals = 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");
    schemaHash = 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(), table),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals
    }).strict();
    schemaInternal = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), table),
      views: recordType(stringType(), view).default({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals
    }).strict();
    schemaV3 = schemaInternalV3.merge(schemaHash);
    schemaV4 = schemaInternalV4.merge(schemaHash);
    schemaV5 = schemaInternalV5.merge(schemaHash);
    schema = schemaInternal.merge(schemaHash);
    tableSquashedV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    tableSquashed = objectType({
      name: stringType(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    viewSquashed = view.omit({
      algorithm: true,
      sqlSecurity: true,
      withCheckOption: true
    }).extend({ meta: stringType() });
    schemaSquashed = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), tableSquashed),
      views: recordType(stringType(), viewSquashed)
    }).strict();
    schemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect,
      tables: recordType(stringType(), tableSquashedV4),
      schemas: recordType(stringType(), stringType())
    }).strict();
    MySqlSquasher = {
      squashIdx: (idx) => {
        index.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 index.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: (fk4) => {
        return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk.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: (view4) => {
        return `${view4.algorithm};${view4.sqlSecurity};${view4.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, (index5) => {
            return MySqlSquasher.squashIdx(index5);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
            return MySqlSquasher.squashFK(fk4);
          });
          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, (check2) => {
            return MySqlSquasher.squashCheck(check2);
          });
          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, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, roleSchema, sequenceSquashed, columnV7, column2, checkConstraint2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, 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_lib();
    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();
    enumSchemaV1 = objectType({
      name: stringType(),
      values: recordType(stringType(), stringType())
    }).strict();
    enumSchema = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType().array()
    }).strict();
    pgSchemaV2 = objectType({
      version: literalType("2"),
      tables: recordType(stringType(), tableV2),
      enums: recordType(stringType(), enumSchemaV1)
    }).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(), enumSchemaV1)
    }).strict();
    indexColumn = objectType({
      expression: stringType(),
      isExpression: booleanType(),
      asc: booleanType(),
      nulls: stringType().optional(),
      opclass: stringType().optional()
    });
    index2 = 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();
    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();
    fk2 = 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();
    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();
    column2 = 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();
    checkConstraint2 = 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();
    tableV32 = 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(),
      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();
    view2 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      definition: stringType().optional(),
      materialized: booleanType(),
      with: mergedViewWithOption.optional(),
      isExisting: booleanType(),
      withNoData: booleanType().optional(),
      using: stringType().optional(),
      tablespace: stringType().optional()
    }).strict();
    tableV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), indexV4),
      foreignKeys: recordType(stringType(), fk2)
    }).strict();
    tableV5 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), indexV5),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
    }).strict();
    tableV6 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), indexV6),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
    }).strict();
    tableV7 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnV7),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
    }).strict();
    table2 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
      policies: recordType(stringType(), policy).default({}),
      checkConstraints: recordType(stringType(), checkConstraint2).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    schemaHash2 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    kitInternals2 = 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(), enumSchemaV1)
    }).strict();
    pgSchemaInternalV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV42),
      enums: recordType(stringType(), enumSchemaV1),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaInternalV5 = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV5),
      enums: recordType(stringType(), enumSchemaV1),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    pgSchemaInternalV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableV6),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    pgSchemaExternal = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: arrayType(table2),
      enums: arrayType(enumSchemaV1),
      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(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      sequences: recordType(stringType(), sequenceSchema),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    pgSchemaInternal = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), table2),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view2).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: kitInternals2
    }).strict();
    tableSquashed2 = 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();
    tableSquashedV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableSquashedV42),
      enums: recordType(stringType(), enumSchemaV1),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed2),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashed = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed2),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view2),
      sequences: recordType(stringType(), sequenceSquashed),
      roles: recordType(stringType(), roleSchema).default({}),
      policies: recordType(stringType(), policySquashed).default({})
    }).strict();
    pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
    pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash2);
    pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash2);
    pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash2);
    pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash2);
    pgSchema = pgSchemaInternal.merge(schemaHash2);
    backwardCompatiblePgSchema = unionType([
      pgSchemaV5,
      pgSchemaV6,
      pgSchema
    ]);
    PgSquasher = {
      squashIdx: (idx) => {
        index2.parse(idx);
        return `${idx.name};${idx.columns.map(
          (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass ? c.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 column9 of columnString) {
          const [expression, isExpression, asc, nulls, opclass] = column9.split("--");
          columns.push({
            nulls,
            isExpression: isExpression === "true",
            asc: asc === "true",
            expression,
            opclass: opclass === "undefined" ? void 0 : opclass
          });
        }
        const result = index2.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) => {
        index2.parse(idx);
        return `${idx.name};${idx.columns.map((c) => `${c.isExpression ? "" : c.expression}--${c.asc}--${c.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 column9 of columnString) {
          const [expression, asc, nulls, opclass] = column9.split(",");
          columns.push({
            nulls,
            isExpression: expression === "",
            asc: asc === "true",
            expression
          });
        }
        const result = index2.parse({
          name,
          columns,
          isUnique: isUnique === "true",
          concurrently: false,
          method,
          with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashFK: (fk4) => {
        return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""};${fk4.schemaTo || "public"}`;
      },
      squashPolicy: (policy4) => {
        var _a;
        return `${policy4.name}--${policy4.as}--${policy4.for}--${(_a = policy4.to) == null ? void 0 : _a.join(",")}--${policy4.using}--${policy4.withCheck}--${policy4.on}`;
      },
      unsquashPolicy: (policy4) => {
        const splitted = policy4.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: (policy4) => {
        var _a;
        return `${policy4.name}--${policy4.as}--${policy4.for}--${(_a = policy4.to) == null ? void 0 : _a.join(",")}--${policy4.on}`;
      },
      unsquashPolicyPush: (policy4) => {
        const splitted = policy4.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 = fk2.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: (check2) => {
        return `${check2.name};${check2.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, (index5) => {
            return action === "push" ? PgSquasher.squashIdxPush(index5) : PgSquasher.squashIdx(index5);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
            return PgSquasher.squashFK(fk4);
          });
          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, (policy4) => {
            return action === "push" ? PgSquasher.squashPolicyPush(policy4) : PgSquasher.squashPolicy(policy4);
          });
          const squashedChecksContraints = mapValues(
            it[1].checkConstraints,
            (check2) => {
              return PgSquasher.squashCheck(check2);
            }
          );
          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 index3, column3, compositePK3, uniqueConstraint3, table3, viewMeta2, kitInternals3, dialect2, schemaHash3, schemaInternal2, schema2, tableSquashed3, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore;
var init_singlestoreSchema = __esm({
  "src/serializer/singlestoreSchema.ts"() {
    "use strict";
    init_lib();
    init_global();
    index3 = 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();
    column3 = 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();
    compositePK3 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint3 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    table3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), index3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    viewMeta2 = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    kitInternals3 = 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");
    schemaHash3 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    schemaInternal2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), table3),
      /* views: record(string(), view).default({}), */
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    schema2 = schemaInternal2.merge(schemaHash3);
    tableSquashed3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), tableSquashed3)
      /* views: record(string(), viewSquashed), */
    }).strict();
    SingleStoreSquasher = {
      squashIdx: (idx) => {
        index3.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 index3.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, (index5) => {
            return SingleStoreSquasher.squashIdx(index5);
          });
          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 index4, fk3, compositePK4, column4, tableV33, uniqueConstraint4, checkConstraint3, table4, view3, dialect3, schemaHash4, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals4, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed4, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
var init_sqliteSchema = __esm({
  "src/serializer/sqliteSchema.ts"() {
    "use strict";
    init_lib();
    init_global();
    index4 = objectType({
      name: stringType(),
      columns: stringType().array(),
      where: stringType().optional(),
      isUnique: booleanType()
    }).strict();
    fk3 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    compositePK4 = objectType({
      columns: stringType().array(),
      name: stringType().optional()
    }).strict();
    column4 = 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(), column4),
      indexes: recordType(stringType(), index4),
      foreignKeys: recordType(stringType(), fk3)
    }).strict();
    uniqueConstraint4 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint3 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    table4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), index4),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK4),
      uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({}),
      checkConstraints: recordType(stringType(), checkConstraint3).default({})
    }).strict();
    view3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict();
    dialect3 = enumType(["sqlite"]);
    schemaHash4 = 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(), table4),
      views: recordType(stringType(), view3).default({}),
      enums: objectType({})
    }).strict();
    schemaInternalV52 = objectType({
      version: literalType("5"),
      dialect: dialect3,
      tables: recordType(stringType(), table4),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    kitInternals4 = 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(), table4),
      views: recordType(stringType(), view3).default({}),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals4
    }).strict();
    schemaV32 = schemaInternalV32.merge(schemaHash4).strict();
    schemaV42 = schemaInternalV42.merge(schemaHash4).strict();
    schemaV52 = schemaInternalV52.merge(schemaHash4).strict();
    schema3 = schemaInternal3.merge(schemaHash4).strict();
    tableSquashed4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      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(), tableSquashed4),
      views: recordType(stringType(), view3),
      enums: anyType()
    }).strict();
    SQLiteSquasher = {
      squashIdx: (idx) => {
        index4.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name, columnsString, isUnique, where] = input.split(";");
        const result = index4.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: (fk4) => {
        return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk3.parse({
          name,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPushFK: (fk4) => {
        return `${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
      },
      unsquashPushFK: (input) => {
        const [
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk3.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: (check2) => {
        return `${check2.name};${check2.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, (index5) => {
            return SQLiteSquasher.squashIdx(index5);
          });
          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,
            (check2) => {
              return SQLiteSquasher.squashCheck(check2);
            }
          );
          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/schemaValidator.ts
var dialects, dialect4, commonSquashedSchema, commonSchema;
var init_schemaValidator = __esm({
  "src/schemaValidator.ts"() {
    "use strict";
    init_lib();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore"];
    dialect4 = enumType(dialects);
    commonSquashedSchema = unionType([
      pgSchemaSquashed,
      mysqlSchemaSquashed,
      SQLiteSchemaSquashed,
      singlestoreSchemaSquashed
    ]);
    commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]);
  }
});

// ../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
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((x2) => x2.trim()).filter((x2) => x2.length).join("-");
  } else {
    input = input.trim();
  }
  if (input.length === 0) {
    return "";
  }
  const toLowerCase = options.locale === false ? (string2) => string2.toLowerCase() : (string2) => string2.toLocaleLowerCase(options.locale);
  const toUpperCase = options.locale === false ? (string2) => string2.toUpperCase() : (string2) => string2.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);
}
var UPPERCASE, LOWERCASE, LEADING_CAPITAL, IDENTIFIER, SEPARATORS, LEADING_SEPARATORS, SEPARATORS_AND_IDENTIFIER, NUMBERS_AND_IDENTIFIER, preserveCamelCase, preserveConsecutiveUppercase, postProcess;
var init_camelcase = __esm({
  "../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js"() {
    UPPERCASE = /[\p{Lu}]/u;
    LOWERCASE = /[\p{Ll}]/u;
    LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
    IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
    SEPARATORS = /[_.\- ]+/;
    LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
    SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
    NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
    preserveCamelCase = (string2, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
      let isLastCharLower = false;
      let isLastCharUpper = false;
      let isLastLastCharUpper = false;
      let isLastLastCharPreserved = false;
      for (let index5 = 0; index5 < string2.length; index5++) {
        const character = string2[index5];
        isLastLastCharPreserved = index5 > 2 ? string2[index5 - 3] === "-" : true;
        if (isLastCharLower && UPPERCASE.test(character)) {
          string2 = string2.slice(0, index5) + "-" + string2.slice(index5);
          isLastCharLower = false;
          isLastLastCharUpper = isLastCharUpper;
          isLastCharUpper = true;
          index5++;
        } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
          string2 = string2.slice(0, index5 - 1) + "-" + string2.slice(index5 - 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 string2;
    };
    preserveConsecutiveUppercase = (input, toLowerCase) => {
      LEADING_CAPITAL.lastIndex = 0;
      return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
    };
    postProcess = (input, toUpperCase) => {
      SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
      NUMBERS_AND_IDENTIFIER.lastIndex = 0;
      return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m2) => toUpperCase(m2));
    };
  }
});

// src/@types/utils.ts
var init_utils = __esm({
  "src/@types/utils.ts"() {
    "use strict";
    init_camelcase();
    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/cli/views.ts
var import_hanji, warning, err, info, grey, error, schema4, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, IntrospectProgress, MigrateProgress, ProgressView, DropMigrationView, trimmedRange;
var init_views = __esm({
  "src/cli/views.ts"() {
    "use strict";
    init_source();
    import_hanji = __toESM(require_hanji());
    init_utils2();
    warning = (msg) => {
      (0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
    };
    err = (msg) => {
      (0, import_hanji.render)(`${source_default.bold.red("Error")} ${msg}`);
    };
    info = (msg, greyMsg = "") => {
      return `${source_default.blue.bold("Info:")} ${msg} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
    };
    grey = (msg) => {
      return source_default.grey(msg);
    };
    error = (error2, greyMsg = "") => {
      return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
    };
    schema4 = (schema6) => {
      const tables = Object.values(schema6.tables);
      let msg = source_default.bold(`${tables.length} tables
`);
      msg += tables.map((t2) => {
        const columnsCount = Object.values(t2.columns).length;
        const indexesCount = Object.values(t2.indexes).length;
        let foreignKeys = 0;
        if (schema6.dialect !== "singlestore") {
          foreignKeys = Object.values(t2.foreignKeys).length;
        }
        return `${source_default.bold.blue(t2.name)} ${source_default.gray(
          `${columnsCount} columns ${indexesCount} indexes ${foreignKeys} fks`
        )}`;
      }).join("\n");
      msg += "\n";
      const enums = objectValues(
        "enums" in schema6 ? "values" in schema6["enums"] ? schema6["enums"] : {} : {}
      );
      if (enums.length > 0) {
        msg += "\n";
        msg += source_default.bold(`${enums.length} enums
`);
        msg += enums.map((it) => {
          return `${source_default.bold.blue(it.name)} ${source_default.gray(
            `[${Object.values(it.values).join(", ")}]`
          )}`;
        }).join("\n");
        msg += "\n";
      }
      return msg;
    };
    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((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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((_2) => {
          const it = _2;
          const keyFrom = it.from.name;
          return key.length + 3 + keyFrom.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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((_2) => {
          const it = _2;
          const keyFrom = tableKey(it.from);
          return key.length + 3 + keyFrom.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 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;
        };
      }
    };
    IntrospectProgress = class extends import_hanji.TaskView {
      constructor(hasEnums = false) {
        super();
        this.hasEnums = hasEnums;
        this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
        this.state = {
          tables: {
            count: 0,
            name: "tables",
            status: "fetching"
          },
          columns: {
            count: 0,
            name: "columns",
            status: "fetching"
          },
          enums: {
            count: 0,
            name: "enums",
            status: "fetching"
          },
          indexes: {
            count: 0,
            name: "indexes",
            status: "fetching"
          },
          fks: {
            count: 0,
            name: "foreign keys",
            status: "fetching"
          },
          policies: {
            count: 0,
            name: "policies",
            status: "fetching"
          },
          checks: {
            count: 0,
            name: "check constraints",
            status: "fetching"
          },
          views: {
            count: 0,
            name: "views",
            status: "fetching"
          }
        };
        this.formatCount = (count) => {
          const width = Math.max.apply(
            null,
            Object.values(this.state).map((it) => it.count.toFixed(0).length)
          );
          return count.toFixed(0).padEnd(width, " ");
        };
        this.statusText = (spinner, stage) => {
          const { name, count } = stage;
          const isDone = stage.status === "done";
          const prefix2 = isDone ? `[${source_default.green("\u2713")}]` : `[${spinner}]`;
          const formattedCount = this.formatCount(count);
          const suffix = isDone ? `${formattedCount} ${name} fetched` : `${formattedCount} ${name} fetching`;
          return `${prefix2} ${suffix}
`;
        };
        this.timeout = setInterval(() => {
          this.spinner.tick();
          this.requestLayout();
        }, 128);
        this.on("detach", () => clearInterval(this.timeout));
      }
      update(stage, count, status) {
        this.state[stage].count = count;
        this.state[stage].status = status;
        this.requestLayout();
      }
      render() {
        let info2 = "";
        const spin = this.spinner.value();
        info2 += this.statusText(spin, this.state.tables);
        info2 += this.statusText(spin, this.state.columns);
        info2 += this.hasEnums ? this.statusText(spin, this.state.enums) : "";
        info2 += this.statusText(spin, this.state.indexes);
        info2 += this.statusText(spin, this.state.fks);
        info2 += this.statusText(spin, this.state.policies);
        info2 += this.statusText(spin, this.state.checks);
        info2 += this.statusText(spin, this.state.views);
        return info2;
      }
    };
    MigrateProgress = class extends import_hanji.TaskView {
      constructor() {
        super();
        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}] applying migrations...`;
        }
        return `[${source_default.green("\u2713")}] migrations applied successfully!`;
      }
    };
    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}
`;
      }
    };
    DropMigrationView = class extends import_hanji.Prompt {
      constructor(data) {
        super();
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.data = new import_hanji.SelectState(data);
        this.data.selectedIdx = data.length - 1;
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "\n";
        }
        let text = source_default.bold("Please select migration to drop:\n");
        const selectedPrefix = source_default.yellow("\u276F ");
        const data = trimmedRange(this.data.items, this.data.selectedIdx, 9);
        const labelLength = data.trimmed.map((it) => it.tag.length).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 0);
        text += data.startTrimmed ? "  ...\n" : "";
        data.trimmed.forEach((it, idx) => {
          const isSelected = idx === this.data.selectedIdx - data.offset;
          let title = it.tag.padEnd(labelLength, " ");
          title = isSelected ? source_default.yellow(title) : title;
          text += isSelected ? `${selectedPrefix}${title}` : `  ${title}`;
          text += idx != this.data.items.length - 1 ? "\n" : "";
        });
        text += data.endTrimmed ? "  ...\n" : "";
        return text;
      }
      result() {
        return this.data.items[this.data.selectedIdx];
      }
    };
    trimmedRange = (arr, index5, limitLines) => {
      const limit = limitLines - 2;
      const sideLimit = Math.round(limit / 2);
      const endTrimmed = arr.length - sideLimit > index5;
      const startTrimmed = index5 > sideLimit - 1;
      const paddingStart = Math.max(index5 + sideLimit - arr.length, 0);
      const paddingEnd = Math.min(index5 - sideLimit + 1, 0);
      const d1 = endTrimmed ? 1 : 0;
      const d2 = startTrimmed ? 0 : 1;
      const start = Math.max(0, index5 - sideLimit + d1 - paddingStart);
      const end = Math.min(arr.length, index5 + sideLimit + d2 - paddingEnd);
      return {
        trimmed: arr.slice(start, end),
        offset: start,
        startTrimmed,
        endTrimmed
      };
    };
  }
});

// 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, "''");
}
function unescapeSingleQuotes(str, ignoreFirstAndLastChar) {
  const regex = ignoreFirstAndLastChar ? /(?<!^)'(?!$)/g : /'/g;
  return str.replace(/''/g, "'").replace(regex, "\\'");
}
var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl;
var init_utils2 = __esm({
  "src/utils.ts"() {
    "use strict";
    init_source();
    import_fs = require("fs");
    import_path = require("path");
    import_url = require("url");
    init_views();
    init_global();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    copy = (it) => {
      return JSON.parse(JSON.stringify(it));
    };
    objectValues = (obj) => {
      return Object.values(obj);
    };
    assertV1OutFolder = (out) => {
      if (!(0, import_fs.existsSync)(out))
        return;
      const oldMigrationFolders = (0, import_fs.readdirSync)(out).filter(
        (it) => it.length === 14 && /^\d+$/.test(it)
      );
      if (oldMigrationFolders.length > 0) {
        console.log(
          `Your migrations folder format is outdated, please run ${source_default.green.bold(
            `drizzle-kit up`
          )}`
        );
        process.exit(1);
      }
    };
    dryJournal = (dialect6) => {
      return {
        version: snapshotVersion,
        dialect: dialect6,
        entries: []
      };
    };
    prepareOutFolder = (out, dialect6) => {
      const meta = (0, import_path.join)(out, "meta");
      const journalPath = (0, import_path.join)(meta, "_journal.json");
      if (!(0, import_fs.existsSync)((0, import_path.join)(out, "meta"))) {
        (0, import_fs.mkdirSync)(meta, { recursive: true });
        (0, import_fs.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect6)));
      }
      const journal = JSON.parse((0, import_fs.readFileSync)(journalPath).toString());
      const snapshots = (0, import_fs.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path.join)(meta, it));
      snapshots.sort();
      return { meta, snapshots, journal };
    };
    validatorForDialect = (dialect6) => {
      switch (dialect6) {
        case "postgresql":
          return { validator: backwardCompatiblePgSchema, version: 7 };
        case "sqlite":
          return { validator: backwardCompatibleSqliteSchema, version: 6 };
        case "turso":
          return { validator: backwardCompatibleSqliteSchema, version: 6 };
        case "mysql":
          return { validator: backwardCompatibleMysqlSchema, version: 5 };
        case "singlestore":
          return { validator: backwardCompatibleSingleStoreSchema, version: 1 };
      }
    };
    validateWithReport = (snapshots, dialect6) => {
      const { validator: validator2, version: version3 } = validatorForDialect(dialect6);
      const result = snapshots.reduce(
        (accum, it) => {
          const raw2 = JSON.parse((0, import_fs.readFileSync)(`./${it}`).toString());
          accum.rawMap[it] = raw2;
          if (raw2["version"] && Number(raw2["version"]) > version3) {
            console.log(
              info(
                `${it} snapshot is of unsupported version, please update drizzle-kit`
              )
            );
            process.exit(0);
          }
          const result2 = validator2.safeParse(raw2);
          if (!result2.success) {
            accum.malformed.push(it);
            return accum;
          }
          const snapshot = result2.data;
          if (snapshot.version !== String(version3)) {
            accum.nonLatest.push(it);
            return accum;
          }
          const idEntry = accum.idsMap[snapshot["prevId"]] ?? {
            parent: it,
            snapshots: []
          };
          idEntry.snapshots.push(it);
          accum.idsMap[snapshot["prevId"]] = idEntry;
          return accum;
        },
        {
          malformed: [],
          nonLatest: [],
          idToNameMap: {},
          idsMap: {},
          rawMap: {}
        }
      );
      return result;
    };
    prepareMigrationFolder = (outFolder = "drizzle", dialect6) => {
      const { snapshots, journal } = prepareOutFolder(outFolder, dialect6);
      const report = validateWithReport(snapshots, dialect6);
      if (report.nonLatest.length > 0) {
        console.log(
          report.nonLatest.map((it) => {
            return `${it}/snapshot.json is not of the latest version`;
          }).concat(`Run ${source_default.green.bold(`drizzle-kit up`)}`).join("\n")
        );
        process.exit(0);
      }
      if (report.malformed.length) {
        const message2 = report.malformed.map((it) => {
          return `${it} data is malformed`;
        }).join("\n");
        console.log(message2);
      }
      const collisionEntries = Object.entries(report.idsMap).filter(
        (it) => it[1].snapshots.length > 1
      );
      const message = collisionEntries.map((it) => {
        const data = it[1];
        return `[${data.snapshots.join(
          ", "
        )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
      }).join("\n").trim();
      if (message) {
        console.log(source_default.red.bold("Error:"), message);
      }
      const abort = report.malformed.length || collisionEntries.length > 0;
      if (abort) {
        process.exit(0);
      }
      return { snapshots, journal };
    };
    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 = (table5, schema6, column9) => {
      const out = schema6 ? `"${schema6}"."${table5}"."${column9}"` : `"${table5}"."${column9}"`;
      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 (e2) {
          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;
    };
  }
});

// ../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) {
    var pathModule = require("path");
    var isWindows = process.platform === "win32";
    var fs7 = 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(p, cache) {
      p = pathModule.resolve(p);
      if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
        return cache[p];
      }
      var original = p, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m2 = splitRootRe.exec(p);
        pos = m2[0].length;
        current = m2[0];
        base = m2[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs7.lstatSync(base);
          knownHard[base] = true;
        }
      }
      while (pos < p.length) {
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache && cache[base] === base) {
          continue;
        }
        var resolvedLink;
        if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
          resolvedLink = cache[base];
        } else {
          var stat2 = fs7.lstatSync(base);
          if (!stat2.isSymbolicLink()) {
            knownHard[base] = true;
            if (cache)
              cache[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) {
            fs7.statSync(base);
            linkTarget = fs7.readlinkSync(base);
          }
          resolvedLink = pathModule.resolve(previous, linkTarget);
          if (cache)
            cache[base] = resolvedLink;
          if (!isWindows)
            seenLinks[id] = linkTarget;
        }
        p = pathModule.resolve(resolvedLink, p.slice(pos));
        start();
      }
      if (cache)
        cache[original] = p;
      return p;
    };
    exports2.realpath = function realpath(p, cache, cb) {
      if (typeof cb !== "function") {
        cb = maybeCallback(cache);
        cache = null;
      }
      p = pathModule.resolve(p);
      if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
        return process.nextTick(cb.bind(null, null, cache[p]));
      }
      var original = p, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m2 = splitRootRe.exec(p);
        pos = m2[0].length;
        current = m2[0];
        base = m2[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs7.lstat(base, function(err2) {
            if (err2)
              return cb(err2);
            knownHard[base] = true;
            LOOP();
          });
        } else {
          process.nextTick(LOOP);
        }
      }
      function LOOP() {
        if (pos >= p.length) {
          if (cache)
            cache[original] = p;
          return cb(null, p);
        }
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache && cache[base] === base) {
          return process.nextTick(LOOP);
        }
        if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
          return gotResolvedLink(cache[base]);
        }
        return fs7.lstat(base, gotStat);
      }
      function gotStat(err2, stat2) {
        if (err2)
          return cb(err2);
        if (!stat2.isSymbolicLink()) {
          knownHard[base] = true;
          if (cache)
            cache[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);
          }
        }
        fs7.stat(base, function(err3) {
          if (err3)
            return cb(err3);
          fs7.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 (cache)
          cache[base2] = resolvedLink;
        gotResolvedLink(resolvedLink);
      }
      function gotResolvedLink(resolvedLink) {
        p = pathModule.resolve(resolvedLink, p.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) {
    module2.exports = realpath;
    realpath.realpath = realpath;
    realpath.sync = realpathSync;
    realpath.realpathSync = realpathSync;
    realpath.monkeypatch = monkeypatch;
    realpath.unmonkeypatch = unmonkeypatch;
    var fs7 = require("fs");
    var origRealpath = fs7.realpath;
    var origRealpathSync = fs7.realpathSync;
    var version3 = process.version;
    var ok = /^v[0-5]\./.test(version3);
    var old = require_old();
    function newError(er) {
      return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
    }
    function realpath(p, cache, cb) {
      if (ok) {
        return origRealpath(p, cache, cb);
      }
      if (typeof cache === "function") {
        cb = cache;
        cache = null;
      }
      origRealpath(p, cache, function(er, result) {
        if (newError(er)) {
          old.realpath(p, cache, cb);
        } else {
          cb(er, result);
        }
      });
    }
    function realpathSync(p, cache) {
      if (ok) {
        return origRealpathSync(p, cache);
      }
      try {
        return origRealpathSync(p, cache);
      } catch (er) {
        if (newError(er)) {
          return old.realpathSync(p, cache);
        } else {
          throw er;
        }
      }
    }
    function monkeypatch() {
      fs7.realpath = realpath;
      fs7.realpathSync = realpathSync;
    }
    function unmonkeypatch() {
      fs7.realpath = origRealpath;
      fs7.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) {
    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(a, b, str) {
      if (a instanceof RegExp)
        a = maybeMatch(a, str);
      if (b instanceof RegExp)
        b = maybeMatch(b, str);
      var r2 = range(a, b, str);
      return r2 && {
        start: r2[0],
        end: r2[1],
        pre: str.slice(0, r2[0]),
        body: str.slice(r2[0] + a.length, r2[1]),
        post: str.slice(r2[1] + b.length)
      };
    }
    function maybeMatch(reg, str) {
      var m2 = str.match(reg);
      return m2 ? m2[0] : null;
    }
    balanced.range = range;
    function range(a, b, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a);
      var bi = str.indexOf(b, ai + 1);
      var i2 = ai;
      if (ai >= 0 && bi > 0) {
        if (a === b) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i2 >= 0 && !result) {
          if (i2 == ai) {
            begs.push(i2);
            ai = str.indexOf(a, i2 + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b, i2 + 1);
          }
          i2 = 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) {
    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 m2 = balanced("{", "}", str);
      if (!m2)
        return str.split(",");
      var pre = m2.pre;
      var body = m2.body;
      var post = m2.post;
      var p = pre.split(",");
      p[p.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p[p.length - 1] += postParts.shift();
        p.push.apply(p, postParts);
      }
      parts.push.apply(parts, p);
      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(i2, y) {
      return i2 <= y;
    }
    function gte(i2, y) {
      return i2 >= y;
    }
    function expand2(str, isTop) {
      var expansions = [];
      var m2 = balanced("{", "}", str);
      if (!m2)
        return [str];
      var pre = m2.pre;
      var post = m2.post.length ? expand2(m2.post, false) : [""];
      if (/\$$/.test(m2.pre)) {
        for (var k = 0; k < post.length; k++) {
          var expansion = pre + "{" + m2.body + "}" + post[k];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m2.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m2.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m2.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m2.post.match(/,.*\}/)) {
            str = m2.pre + "{" + m2.body + escClose + m2.post;
            return expand2(str);
          }
          return [str];
        }
        var n;
        if (isSequence) {
          n = m2.body.split(/\.\./);
        } else {
          n = parseCommaParts(m2.body);
          if (n.length === 1) {
            n = expand2(n[0], false).map(embrace);
            if (n.length === 1) {
              return post.map(function(p) {
                return m2.pre + n[0] + p;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x2 = numeric(n[0]);
          var y = numeric(n[1]);
          var width = Math.max(n[0].length, n[1].length);
          var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
          var test = lte;
          var reverse = y < x2;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad = n.some(isPadded);
          N = [];
          for (var i2 = x2; test(i2, y); i2 += incr) {
            var c;
            if (isAlphaSequence) {
              c = String.fromCharCode(i2);
              if (c === "\\")
                c = "";
            } else {
              c = String(i2);
              if (pad) {
                var need = width - c.length;
                if (need > 0) {
                  var z2 = new Array(need + 1).join("0");
                  if (i2 < 0)
                    c = "-" + z2 + c.slice(1);
                  else
                    c = z2 + c;
                }
              }
            }
            N.push(c);
          }
        } else {
          N = [];
          for (var j = 0; j < n.length; j++) {
            N.push.apply(N, expand2(n[j], false));
          }
        }
        for (var j = 0; j < N.length; j++) {
          for (var k = 0; k < post.length; k++) {
            var expansion = pre + N[j] + post[k];
            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) {
    var minimatch2 = module2.exports = (p, pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch2(pattern, options).match(p);
    };
    module2.exports = minimatch2;
    var path4 = require_path();
    minimatch2.sep = path4.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 = (s2) => s2.split("").reduce((set, c) => {
      set[c] = true;
      return set;
    }, {});
    var reSpecials2 = charSet2("().*{}+?[]^$\\!");
    var addPatternStartSet2 = charSet2("[.(");
    var slashSplit = /\/+/;
    minimatch2.filter = (pattern, options = {}) => (p, i2, list) => minimatch2(p, pattern, options);
    var ext2 = (a, b = {}) => {
      const t2 = {};
      Object.keys(a).forEach((k) => t2[k] = a[k]);
      Object.keys(b).forEach((k) => t2[k] = b[k]);
      return t2;
    };
    minimatch2.defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch2;
      }
      const orig = minimatch2;
      const m2 = (p, pattern, options) => orig(p, pattern, ext2(def, options));
      m2.Minimatch = class Minimatch extends orig.Minimatch {
        constructor(pattern, options) {
          super(pattern, ext2(def, options));
        }
      };
      m2.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
      m2.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
      m2.defaults = (options) => orig.defaults(ext2(def, options));
      m2.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
      m2.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
      m2.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
      return m2;
    };
    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((f3) => mm.match(f3));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    var globUnescape2 = (s2) => s2.replace(/\\(.)/g, "$1");
    var charUnescape = (s2) => s2.replace(/\\([^-\]])/g, "$1");
    var regExpEscape2 = (s2) => s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    var braExpEscape = (s2) => s2.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((s2) => s2.split(slashSplit));
        this.debug(this.pattern, set);
        set = set.map((s2, si, set2) => s2.map(this.parse, this));
        this.debug(this.pattern, set);
        set = set.filter((s2) => s2.indexOf(false) === -1);
        this.debug(this.pattern, set);
        this.set = set;
      }
      parseNegate() {
        if (this.options.nonegate)
          return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i2 = 0; i2 < pattern.length && pattern.charAt(i2) === "!"; i2++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset)
          this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, 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 p = pattern[pi];
          var f3 = file[fi];
          this.debug(pattern, p, f3);
          if (p === false)
            return false;
          if (p === GLOBSTAR2) {
            this.debug("GLOBSTAR", [pattern, p, f3]);
            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 p === "string") {
            hit = f3 === p;
            this.debug("string match", p, f3, hit);
          } else {
            hit = f3.match(p);
            this.debug("pattern match", p, f3, 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 = (p) => p.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 i2 = 0, c; i2 < pattern.length && (c = pattern.charAt(i2)); i2++) {
          this.debug("%s	%s %s %j", pattern, i2, re, c);
          if (escaping) {
            if (c === "/") {
              return false;
            }
            if (reSpecials2[c]) {
              re += "\\";
            }
            re += c;
            escaping = false;
            continue;
          }
          switch (c) {
            case "/": {
              return false;
            }
            case "\\":
              if (inClass && pattern.charAt(i2 + 1) === "-") {
                re += c;
                continue;
              }
              clearStateChar();
              escaping = true;
              continue;
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i2, re, c);
              if (inClass) {
                this.debug("  in class");
                if (c === "!" && i2 === classStart + 1)
                  c = "^";
                re += c;
                continue;
              }
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c;
              if (options.noext)
                clearStateChar();
              continue;
            case "(": {
              if (inClass) {
                re += "(";
                continue;
              }
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i2 - 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(i2 + 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(i2 + 1));
              }
              continue;
            }
            case "[":
              clearStateChar();
              if (inClass) {
                re += "\\" + c;
                continue;
              }
              inClass = true;
              classStart = i2;
              reClassStart = re.length;
              re += c;
              continue;
            case "]":
              if (i2 === classStart + 1 || !inClass) {
                re += "\\" + c;
                continue;
              }
              cs = pattern.substring(classStart + 1, i2);
              try {
                RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
                re += c;
              } catch (er) {
                re = re.substring(0, reClassStart) + "(?:$.)";
              }
              hasMagic = true;
              inClass = false;
              continue;
            default:
              clearStateChar();
              if (reSpecials2[c] && !(c === "^" && inClass)) {
                re += "\\";
              }
              re += c;
              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, (_2, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t2 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t2 + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet2[re.charAt(0)];
        for (let n = negativeLists.length - 1; n > -1; n--) {
          const nl = negativeLists[n];
          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 i2 = 0; i2 < openParensBefore; i2++) {
            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(
            (p) => typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR2 ? GLOBSTAR2 : p._src
          ).reduce((set2, p) => {
            if (!(set2[set2.length - 1] === GLOBSTAR2 && p === GLOBSTAR2)) {
              set2.push(p);
            }
            return set2;
          }, []);
          pattern.forEach((p, i2) => {
            if (p !== GLOBSTAR2 || pattern[i2 - 1] === GLOBSTAR2) {
              return;
            }
            if (i2 === 0) {
              if (pattern.length > 1) {
                pattern[i2 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i2 + 1];
              } else {
                pattern[i2] = twoStar;
              }
            } else if (i2 === pattern.length - 1) {
              pattern[i2 - 1] += "(?:\\/|" + twoStar + ")?";
            } else {
              pattern[i2 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i2 + 1];
              pattern[i2 + 1] = GLOBSTAR2;
            }
          });
          return pattern.filter((p) => p !== 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(f3, partial = this.partial) {
        this.debug("match", f3, this.pattern);
        if (this.comment)
          return false;
        if (this.empty)
          return f3 === "";
        if (f3 === "/" && partial)
          return true;
        const options = this.options;
        if (path4.sep !== "/") {
          f3 = f3.split(path4.sep).join("/");
        }
        f3 = f3.split(slashSplit);
        this.debug(this.pattern, "split", f3);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename;
        for (let i2 = f3.length - 1; i2 >= 0; i2--) {
          filename = f3[i2];
          if (filename)
            break;
        }
        for (let i2 = 0; i2 < set.length; i2++) {
          const pattern = set[i2];
          let file = f3;
          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) {
    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) {
    try {
      util2 = require("util");
      if (typeof util2.inherits !== "function")
        throw "";
      module2.exports = util2.inherits;
    } catch (e2) {
      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) {
    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 fs7 = require("fs");
    var path4 = require("path");
    var minimatch2 = require_minimatch();
    var isAbsolute = require("path").isAbsolute;
    var Minimatch2 = minimatch2.Minimatch;
    function alphasort(a, b) {
      return a.localeCompare(b, "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 || fs7;
      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 = path4.resolve(cwd);
      else {
        self2.cwd = path4.resolve(options.cwd);
        self2.changedCwd = self2.cwd !== cwd;
      }
      self2.root = options.root || path4.resolve(self2.cwd, "/");
      self2.root = path4.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 i2 = 0, l = self2.matches.length; i2 < l; i2++) {
        var matches = self2.matches[i2];
        if (!matches || Object.keys(matches).length === 0) {
          if (self2.nonull) {
            var literal = self2.minimatch.globSet[i2];
            if (nou)
              all.push(literal);
            else
              all[literal] = true;
          }
        } else {
          var m2 = Object.keys(matches);
          if (nou)
            all.push.apply(all, m2);
          else
            m2.forEach(function(m3) {
              all[m3] = true;
            });
        }
      }
      if (!nou)
        all = Object.keys(all);
      if (!self2.nosort)
        all = all.sort(alphasort);
      if (self2.mark) {
        for (var i2 = 0; i2 < all.length; i2++) {
          all[i2] = self2._mark(all[i2]);
        }
        if (self2.nodir) {
          all = all.filter(function(e2) {
            var notDir = !/\/$/.test(e2);
            var c = self2.cache[e2] || self2.cache[makeAbs(self2, e2)];
            if (notDir && c)
              notDir = c !== "DIR" && !Array.isArray(c);
            return notDir;
          });
        }
      }
      if (self2.ignore.length)
        all = all.filter(function(m3) {
          return !isIgnored(self2, m3);
        });
      self2.found = all;
    }
    function mark(self2, p) {
      var abs = makeAbs(self2, p);
      var c = self2.cache[abs];
      var m2 = p;
      if (c) {
        var isDir = c === "DIR" || Array.isArray(c);
        var slash = p.slice(-1) === "/";
        if (isDir && !slash)
          m2 += "/";
        else if (!isDir && slash)
          m2 = m2.slice(0, -1);
        if (m2 !== p) {
          var mabs = makeAbs(self2, m2);
          self2.statCache[mabs] = self2.statCache[abs];
          self2.cache[mabs] = self2.cache[abs];
        }
      }
      return m2;
    }
    function makeAbs(self2, f3) {
      var abs = f3;
      if (f3.charAt(0) === "/") {
        abs = path4.join(self2.root, f3);
      } else if (isAbsolute(f3) || f3 === "") {
        abs = f3;
      } else if (self2.changedCwd) {
        abs = path4.resolve(self2.cwd, f3);
      } else {
        abs = path4.resolve(f3);
      }
      if (process.platform === "win32")
        abs = abs.replace(/\\/g, "/");
      return abs;
    }
    function isIgnored(self2, path5) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return item.matcher.match(path5) || !!(item.gmatcher && item.gmatcher.match(path5));
      });
    }
    function childrenIgnored(self2, path5) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return !!(item.gmatcher && item.gmatcher.match(path5));
      });
    }
  }
});

// ../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) {
    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 path4 = 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 n = this.minimatch.set.length;
      this.matches = new Array(n);
      for (var i2 = 0; i2 < n; i2++) {
        this._process(this.minimatch.set[i2], i2, false);
      }
      this._finish();
    }
    GlobSync.prototype._finish = function() {
      assert.ok(this instanceof GlobSync);
      if (this.realpath) {
        var self2 = this;
        this.matches.forEach(function(matchset, index5) {
          var set = self2.matches[index5] = /* @__PURE__ */ Object.create(null);
          for (var p in matchset) {
            try {
              p = self2._makeAbs(p);
              var real = rp.realpathSync(p, self2.realpathCache);
              set[real] = true;
            } catch (er) {
              if (er.syscall === "stat")
                set[self2._makeAbs(p)] = true;
              else
                throw er;
            }
          }
        });
      }
      common.finish(this);
    };
    GlobSync.prototype._process = function(pattern, index5, inGlobStar) {
      assert.ok(this instanceof GlobSync);
      var n = 0;
      while (typeof pattern[n] === "string") {
        n++;
      }
      var prefix2;
      switch (n) {
        case pattern.length:
          this._processSimple(pattern.join("/"), index5);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n).join("/");
          break;
      }
      var remain = pattern.slice(n);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
        return typeof p === "string" ? p : "[*]";
      }).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, index5, inGlobStar);
      else
        this._processReaddir(prefix2, read, abs, remain, index5, inGlobStar);
    };
    GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index5, inGlobStar) {
      var entries = this._readdir(abs, inGlobStar);
      if (!entries)
        return;
      var pn = remain[0];
      var negate = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i2 = 0; i2 < entries.length; i2++) {
        var e2 = entries[i2];
        if (e2.charAt(0) !== "." || dotOk) {
          var m2;
          if (negate && !prefix2) {
            m2 = !e2.match(pn);
          } else {
            m2 = e2.match(pn);
          }
          if (m2)
            matchedEntries.push(e2);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return;
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index5])
          this.matches[index5] = /* @__PURE__ */ Object.create(null);
        for (var i2 = 0; i2 < len; i2++) {
          var e2 = matchedEntries[i2];
          if (prefix2) {
            if (prefix2.slice(-1) !== "/")
              e2 = prefix2 + "/" + e2;
            else
              e2 = prefix2 + e2;
          }
          if (e2.charAt(0) === "/" && !this.nomount) {
            e2 = path4.join(this.root, e2);
          }
          this._emitMatch(index5, e2);
        }
        return;
      }
      remain.shift();
      for (var i2 = 0; i2 < len; i2++) {
        var e2 = matchedEntries[i2];
        var newPattern;
        if (prefix2)
          newPattern = [prefix2, e2];
        else
          newPattern = [e2];
        this._process(newPattern.concat(remain), index5, inGlobStar);
      }
    };
    GlobSync.prototype._emitMatch = function(index5, e2) {
      if (isIgnored(this, e2))
        return;
      var abs = this._makeAbs(e2);
      if (this.mark)
        e2 = this._mark(e2);
      if (this.absolute) {
        e2 = abs;
      }
      if (this.matches[index5][e2])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index5][e2] = true;
      if (this.stat)
        this._stat(e2);
    };
    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 c = this.cache[abs];
        if (!c || c === "FILE")
          return null;
        if (Array.isArray(c))
          return c;
      }
      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 i2 = 0; i2 < entries.length; i2++) {
          var e2 = entries[i2];
          if (abs === "/")
            e2 = abs + e2;
          else
            e2 = abs + "/" + e2;
          this.cache[e2] = true;
        }
      }
      this.cache[abs] = entries;
      return entries;
    };
    GlobSync.prototype._readdirError = function(f3, er) {
      switch (er.code) {
        case "ENOTSUP":
        case "ENOTDIR":
          var abs = this._makeAbs(f3);
          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":
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f3)] = false;
          break;
        default:
          this.cache[this._makeAbs(f3)] = false;
          if (this.strict)
            throw er;
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
    };
    GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index5, 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, index5, false);
      var len = entries.length;
      var isSym = this.symlinks[abs];
      if (isSym && inGlobStar)
        return;
      for (var i2 = 0; i2 < len; i2++) {
        var e2 = entries[i2];
        if (e2.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i2], remainWithoutGlobStar);
        this._process(instead, index5, true);
        var below = gspref.concat(entries[i2], remain);
        this._process(below, index5, true);
      }
    };
    GlobSync.prototype._processSimple = function(prefix2, index5) {
      var exists = this._stat(prefix2);
      if (!this.matches[index5])
        this.matches[index5] = /* @__PURE__ */ Object.create(null);
      if (!exists)
        return;
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path4.join(this.root, prefix2);
        } else {
          prefix2 = path4.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index5, prefix2);
    };
    GlobSync.prototype._stat = function(f3) {
      var abs = this._makeAbs(f3);
      var needDir = f3.slice(-1) === "/";
      if (f3.length > this.maxLength)
        return false;
      if (!this.stat && ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (Array.isArray(c))
          c = "DIR";
        if (!needDir || c === "DIR")
          return c;
        if (needDir && c === "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 c = true;
      if (stat2)
        c = stat2.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c;
      if (needDir && c === "FILE")
        return false;
      return c;
    };
    GlobSync.prototype._mark = function(p) {
      return common.mark(this, p);
    };
    GlobSync.prototype._makeAbs = function(f3) {
      return common.makeAbs(this, f3);
    };
  }
});

// ../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) {
    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(k) {
        wrapper[k] = fn[k];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i2 = 0; i2 < args.length; i2++) {
          args[i2] = arguments[i2];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        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) {
    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 f3 = function() {
        if (f3.called)
          return f3.value;
        f3.called = true;
        return f3.value = fn.apply(this, arguments);
      };
      f3.called = false;
      return f3;
    }
    function onceStrict(fn) {
      var f3 = function() {
        if (f3.called)
          throw new Error(f3.onceError);
        f3.called = true;
        return f3.value = fn.apply(this, arguments);
      };
      var name = fn.name || "Function wrapped with `once`";
      f3.onceError = name + " shouldn't be called more than once";
      f3.called = false;
      return f3;
    }
  }
});

// ../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) {
    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 i2 = 0; i2 < len; i2++) {
            cbs[i2].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 i2 = 0; i2 < length; i2++)
        array2[i2] = args[i2];
      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) {
    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 path4 = 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 i2 = keys.length;
      while (i2--) {
        origin[keys[i2]] = add[keys[i2]];
      }
      return origin;
    }
    glob2.hasMagic = function(pattern, options_) {
      var options = extend({}, options_);
      options.noprocess = true;
      var g = new Glob(pattern, options);
      var set = g.minimatch.set;
      if (!pattern)
        return false;
      if (set.length > 1)
        return true;
      for (var j = 0; j < set[0].length; j++) {
        if (typeof set[0][j] !== "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 n = this.minimatch.set.length;
      this.matches = new Array(n);
      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 (n === 0)
        return done();
      var sync2 = true;
      for (var i2 = 0; i2 < n; i2++) {
        this._process(this.minimatch.set[i2], i2, 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 n = this.matches.length;
      if (n === 0)
        return this._finish();
      var self2 = this;
      for (var i2 = 0; i2 < this.matches.length; i2++)
        this._realpathSet(i2, next);
      function next() {
        if (--n === 0)
          self2._finish();
      }
    };
    Glob.prototype._realpathSet = function(index5, cb) {
      var matchset = this.matches[index5];
      if (!matchset)
        return cb();
      var found = Object.keys(matchset);
      var self2 = this;
      var n = found.length;
      if (n === 0)
        return cb();
      var set = this.matches[index5] = /* @__PURE__ */ Object.create(null);
      found.forEach(function(p, i2) {
        p = self2._makeAbs(p);
        rp.realpath(p, self2.realpathCache, function(er, real) {
          if (!er)
            set[real] = true;
          else if (er.syscall === "stat")
            set[p] = true;
          else
            self2.emit("error", er);
          if (--n === 0) {
            self2.matches[index5] = set;
            cb();
          }
        });
      });
    };
    Glob.prototype._mark = function(p) {
      return common.mark(this, p);
    };
    Glob.prototype._makeAbs = function(f3) {
      return common.makeAbs(this, f3);
    };
    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 i2 = 0; i2 < eq.length; i2++) {
            var e2 = eq[i2];
            this._emitMatch(e2[0], e2[1]);
          }
        }
        if (this._processQueue.length) {
          var pq = this._processQueue.slice(0);
          this._processQueue.length = 0;
          for (var i2 = 0; i2 < pq.length; i2++) {
            var p = pq[i2];
            this._processing--;
            this._process(p[0], p[1], p[2], p[3]);
          }
        }
      }
    };
    Glob.prototype._process = function(pattern, index5, inGlobStar, cb) {
      assert(this instanceof Glob);
      assert(typeof cb === "function");
      if (this.aborted)
        return;
      this._processing++;
      if (this.paused) {
        this._processQueue.push([pattern, index5, inGlobStar, cb]);
        return;
      }
      var n = 0;
      while (typeof pattern[n] === "string") {
        n++;
      }
      var prefix2;
      switch (n) {
        case pattern.length:
          this._processSimple(pattern.join("/"), index5, cb);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n).join("/");
          break;
      }
      var remain = pattern.slice(n);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
        return typeof p === "string" ? p : "[*]";
      }).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, index5, inGlobStar, cb);
      else
        this._processReaddir(prefix2, read, abs, remain, index5, inGlobStar, cb);
    };
    Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index5, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        return self2._processReaddir2(prefix2, read, abs, remain, index5, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index5, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var pn = remain[0];
      var negate = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i2 = 0; i2 < entries.length; i2++) {
        var e2 = entries[i2];
        if (e2.charAt(0) !== "." || dotOk) {
          var m2;
          if (negate && !prefix2) {
            m2 = !e2.match(pn);
          } else {
            m2 = e2.match(pn);
          }
          if (m2)
            matchedEntries.push(e2);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return cb();
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index5])
          this.matches[index5] = /* @__PURE__ */ Object.create(null);
        for (var i2 = 0; i2 < len; i2++) {
          var e2 = matchedEntries[i2];
          if (prefix2) {
            if (prefix2 !== "/")
              e2 = prefix2 + "/" + e2;
            else
              e2 = prefix2 + e2;
          }
          if (e2.charAt(0) === "/" && !this.nomount) {
            e2 = path4.join(this.root, e2);
          }
          this._emitMatch(index5, e2);
        }
        return cb();
      }
      remain.shift();
      for (var i2 = 0; i2 < len; i2++) {
        var e2 = matchedEntries[i2];
        var newPattern;
        if (prefix2) {
          if (prefix2 !== "/")
            e2 = prefix2 + "/" + e2;
          else
            e2 = prefix2 + e2;
        }
        this._process([e2].concat(remain), index5, inGlobStar, cb);
      }
      cb();
    };
    Glob.prototype._emitMatch = function(index5, e2) {
      if (this.aborted)
        return;
      if (isIgnored(this, e2))
        return;
      if (this.paused) {
        this._emitQueue.push([index5, e2]);
        return;
      }
      var abs = isAbsolute(e2) ? e2 : this._makeAbs(e2);
      if (this.mark)
        e2 = this._mark(e2);
      if (this.absolute)
        e2 = abs;
      if (this.matches[index5][e2])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index5][e2] = true;
      var st = this.statCache[abs];
      if (st)
        this.emit("stat", e2, st);
      this.emit("match", e2);
    };
    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 c = this.cache[abs];
        if (!c || c === "FILE")
          return cb();
        if (Array.isArray(c))
          return cb(null, c);
      }
      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 i2 = 0; i2 < entries.length; i2++) {
          var e2 = entries[i2];
          if (abs === "/")
            e2 = abs + e2;
          else
            e2 = abs + "/" + e2;
          this.cache[e2] = true;
        }
      }
      this.cache[abs] = entries;
      return cb(null, entries);
    };
    Glob.prototype._readdirError = function(f3, er, cb) {
      if (this.aborted)
        return;
      switch (er.code) {
        case "ENOTSUP":
        case "ENOTDIR":
          var abs = this._makeAbs(f3);
          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":
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f3)] = false;
          break;
        default:
          this.cache[this._makeAbs(f3)] = 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, index5, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        self2._processGlobStar2(prefix2, read, abs, remain, index5, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index5, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index5, false, cb);
      var isSym = this.symlinks[abs];
      var len = entries.length;
      if (isSym && inGlobStar)
        return cb();
      for (var i2 = 0; i2 < len; i2++) {
        var e2 = entries[i2];
        if (e2.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i2], remainWithoutGlobStar);
        this._process(instead, index5, true, cb);
        var below = gspref.concat(entries[i2], remain);
        this._process(below, index5, true, cb);
      }
      cb();
    };
    Glob.prototype._processSimple = function(prefix2, index5, cb) {
      var self2 = this;
      this._stat(prefix2, function(er, exists) {
        self2._processSimple2(prefix2, index5, er, exists, cb);
      });
    };
    Glob.prototype._processSimple2 = function(prefix2, index5, er, exists, cb) {
      if (!this.matches[index5])
        this.matches[index5] = /* @__PURE__ */ Object.create(null);
      if (!exists)
        return cb();
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path4.join(this.root, prefix2);
        } else {
          prefix2 = path4.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index5, prefix2);
      cb();
    };
    Glob.prototype._stat = function(f3, cb) {
      var abs = this._makeAbs(f3);
      var needDir = f3.slice(-1) === "/";
      if (f3.length > this.maxLength)
        return cb();
      if (!this.stat && ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (Array.isArray(c))
          c = "DIR";
        if (!needDir || c === "DIR")
          return cb(null, c);
        if (needDir && c === "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(f3, abs, null, lstat, cb);
            else
              self2._stat2(f3, abs, er2, stat3, cb);
          });
        } else {
          self2._stat2(f3, abs, er, lstat, cb);
        }
      }
    };
    Glob.prototype._stat2 = function(f3, abs, er, stat2, cb) {
      if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
        this.statCache[abs] = false;
        return cb();
      }
      var needDir = f3.slice(-1) === "/";
      this.statCache[abs] = stat2;
      if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory())
        return cb(null, false, stat2);
      var c = true;
      if (stat2)
        c = stat2.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c;
      if (needDir && c === "FILE")
        return cb();
      return cb(null, c, stat2);
    };
  }
});

// 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/cli/validations/outputs.ts
var withStyle, outputs;
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)}`
    };
    outputs = {
      studio: {
        drivers: (param) => withStyle.error(
          `"${param}" is not a valid driver. Available drivers: "pg", "mysql2", "better-sqlite", "libsql", "turso". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
        ),
        noCredentials: () => withStyle.error(
          `Please specify a 'dbCredentials' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
        ),
        noDriver: () => withStyle.error(
          `Please specify a 'driver' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
        ),
        noDialect: () => withStyle.error(
          `Please specify 'dialect' param in config, either of 'postgresql', 'mysql', 'sqlite', turso or singlestore`
        )
      },
      common: {
        ambiguousParams: (command) => withStyle.error(
          `You can't use both --config and other cli options for ${command} command`
        ),
        schema: (command) => withStyle.error(`"--schema" is a required field for ${command} command`)
      },
      postgres: {
        connection: {
          required: () => withStyle.error(
            `Either "url" or "host", "database" are required for database connection`
          ),
          awsDataApi: () => withStyle.error(
            "You need to provide 'database', 'secretArn' and 'resourceArn' for Drizzle Kit to connect to AWS Data API"
          )
        }
      },
      mysql: {
        connection: {
          driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
          required: () => withStyle.error(
            `Either "url" or "host", "database" are required for database connection`
          )
        }
      },
      sqlite: {
        connection: {
          driver: () => {
            const listOfDrivers = sqliteDriversLiterals.map((it) => `'${it.value}'`).join(", ");
            return withStyle.error(
              `Either ${listOfDrivers} are available options for 'driver' param`
            );
          },
          url: (driver2) => withStyle.error(
            `"url" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
          ),
          authToken: (driver2) => withStyle.error(
            `"authToken" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
          )
        },
        introspect: {},
        push: {}
      },
      singlestore: {
        connection: {
          driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
          required: () => withStyle.error(
            `Either "url" or "host", "database" are required for database connection`
          )
        }
      }
    };
  }
});

// src/cli/validations/common.ts
var assertCollisions, sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema, drivers, wrapParam;
var init_common = __esm({
  "src/cli/validations/common.ts"() {
    "use strict";
    init_source();
    init_lib();
    init_schemaValidator();
    init_outputs();
    assertCollisions = (command, options, whitelist, remainingKeys) => {
      const { config, ...rest } = options;
      let atLeastOneParam = false;
      for (const key of Object.keys(rest)) {
        if (whitelist.includes(key))
          continue;
        atLeastOneParam = atLeastOneParam || rest[key] !== void 0;
      }
      if (!config && atLeastOneParam) {
        return "cli";
      }
      if (!atLeastOneParam) {
        return "config";
      }
      console.log(outputs.common.ambiguousParams(command));
      process.exit(1);
    };
    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 _2 = "";
    }
    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()
    });
    drivers = ["d1-http", "expo", "aws-data-api", "pglite", "durable-sqlite"];
    wrapParam = (name, param, optional = false, type) => {
      const check2 = `[${source_default.green("\u2713")}]`;
      const cross = `[${source_default.red("x")}]`;
      if (typeof param === "string") {
        if (param.length === 0) {
          return `    ${cross} ${name}: ''`;
        }
        if (type === "secret") {
          return `    ${check2} ${name}: '*****'`;
        } else if (type === "url") {
          return `    ${check2} ${name}: '${param.replace(/(?<=:\/\/[^:\n]*:)([^@]*)/, "****")}'`;
        }
        return `    ${check2} ${name}: '${param}'`;
      }
      if (optional) {
        return source_default.gray(`        ${name}?: `);
      }
      return `    ${cross} ${name}: ${source_default.gray("undefined")}`;
    };
  }
});

// src/cli/validations/cli.ts
var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck;
var init_cli = __esm({
  "src/cli/validations/cli.ts"() {
    "use strict";
    init_lib();
    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/libsql.ts
var libSQLCredentials, printConfigConnectionIssues;
var init_libsql = __esm({
  "src/cli/validations/libsql.ts"() {
    "use strict";
    init_lib();
    init_views();
    init_common();
    libSQLCredentials = objectType({
      url: stringType().min(1),
      authToken: stringType().min(1).optional()
    });
    printConfigConnectionIssues = (options, command) => {
      let text = `Please provide required params for 'turso' dialect:
`;
      console.log(error(text));
      console.log(wrapParam("url", options.url));
      console.log(wrapParam("authToken", options.authToken, true, "secret"));
      process.exit(1);
    };
  }
});

// src/cli/validations/mysql.ts
var mysqlCredentials, printConfigConnectionIssues2;
var init_mysql = __esm({
  "src/cli/validations/mysql.ts"() {
    "use strict";
    init_lib();
    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)
      })
    ]);
    printConfigConnectionIssues2 = (options) => {
      if ("url" in options) {
        let text2 = `Please provide required params for MySQL driver:
`;
        console.log(error(text2));
        console.log(wrapParam("url", options.url, false, "url"));
        process.exit(1);
      }
      let text = `Please provide required params for MySQL driver:
`;
      console.log(error(text));
      console.log(wrapParam("host", options.host));
      console.log(wrapParam("port", options.port, true));
      console.log(wrapParam("user", options.user, true));
      console.log(wrapParam("password", options.password, true, "secret"));
      console.log(wrapParam("database", options.database));
      console.log(wrapParam("ssl", options.ssl, true));
      process.exit(1);
    };
  }
});

// src/cli/validations/postgres.ts
var postgresCredentials, printConfigConnectionIssues3;
var init_postgres = __esm({
  "src/cli/validations/postgres.ts"() {
    "use strict";
    init_lib();
    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((o) => {
        delete o.driver;
        return o;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o) => {
        delete o.driver;
        return o;
      }),
      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)
      })
    ]);
    printConfigConnectionIssues3 = (options) => {
      if (options.driver === "aws-data-api") {
        let text = `Please provide required params for AWS Data API driver:
`;
        console.log(error(text));
        console.log(wrapParam("database", options.database));
        console.log(wrapParam("secretArn", options.secretArn, false, "secret"));
        console.log(wrapParam("resourceArn", options.resourceArn, false, "secret"));
        process.exit(1);
      }
      if ("url" in options) {
        let text = `Please provide required params for Postgres driver:
`;
        console.log(error(text));
        console.log(wrapParam("url", options.url, false, "url"));
        process.exit(1);
      }
      if ("host" in options || "database" in options) {
        let text = `Please provide required params for Postgres driver:
`;
        console.log(error(text));
        console.log(wrapParam("host", options.host));
        console.log(wrapParam("port", options.port, true));
        console.log(wrapParam("user", options.user, true));
        console.log(wrapParam("password", options.password, true, "secret"));
        console.log(wrapParam("database", options.database));
        console.log(wrapParam("ssl", options.ssl, true));
        process.exit(1);
      }
      console.log(
        error(
          `Either connection "url" or "host", "database" are required for PostgreSQL database connection`
        )
      );
      process.exit(1);
    };
  }
});

// src/cli/validations/singlestore.ts
var singlestoreCredentials, printConfigConnectionIssues4;
var init_singlestore = __esm({
  "src/cli/validations/singlestore.ts"() {
    "use strict";
    init_lib();
    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)
      })
    ]);
    printConfigConnectionIssues4 = (options) => {
      if ("url" in options) {
        let text2 = `Please provide required params for SingleStore driver:
`;
        console.log(error(text2));
        console.log(wrapParam("url", options.url, false, "url"));
        process.exit(1);
      }
      let text = `Please provide required params for SingleStore driver:
`;
      console.log(error(text));
      console.log(wrapParam("host", options.host));
      console.log(wrapParam("port", options.port, true));
      console.log(wrapParam("user", options.user, true));
      console.log(wrapParam("password", options.password, true, "secret"));
      console.log(wrapParam("database", options.database));
      console.log(wrapParam("ssl", options.ssl, true));
      process.exit(1);
    };
  }
});

// src/cli/validations/sqlite.ts
var sqliteCredentials, printConfigConnectionIssues5;
var init_sqlite = __esm({
  "src/cli/validations/sqlite.ts"() {
    "use strict";
    init_global();
    init_lib();
    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((o) => {
        delete o.driver;
        return o;
      })
    ]);
    printConfigConnectionIssues5 = (options, command) => {
      const parsedDriver = sqliteDriver.safeParse(options.driver);
      const driver2 = parsedDriver.success ? parsedDriver.data : "";
      if (driver2 === "expo") {
        if (command === "migrate") {
          console.log(
            error(
              `You can't use 'migrate' command with Expo SQLite, please follow migration instructions in our docs - https://orm.drizzle.team/docs/get-started-sqlite#expo-sqlite`
            )
          );
        } else if (command === "studio") {
          console.log(
            error(
              `You can't use 'studio' command with Expo SQLite, please use Expo Plugin https://www.npmjs.com/package/expo-drizzle-studio-plugin`
            )
          );
        } else if (command === "pull") {
          console.log(error("You can't use 'pull' command with Expo SQLite"));
        } else if (command === "push") {
          console.log(error("You can't use 'push' command with Expo SQLite"));
        } else {
          console.log(error("Unexpected error with expo driver \u{1F914}"));
        }
        process.exit(1);
      } else if (driver2 === "d1-http") {
        let text2 = `Please provide required params for D1 HTTP driver:
`;
        console.log(error(text2));
        console.log(wrapParam("accountId", options.accountId));
        console.log(wrapParam("databaseId", options.databaseId));
        console.log(wrapParam("token", options.token, false, "secret"));
        process.exit(1);
      } else if (driver2 === "durable-sqlite") {
        if (command === "migrate") {
          console.log(
            error(
              `You can't use 'migrate' command with SQLite Durable Objects`
            )
          );
        } else if (command === "studio") {
          console.log(
            error(
              `You can't use 'migrate' command with SQLite Durable Objects`
            )
          );
        } else if (command === "pull") {
          console.log(error("You can't use 'pull' command with SQLite Durable Objects"));
        } else if (command === "push") {
          console.log(error("You can't use 'push' command with SQLite Durable Objects"));
        } else {
          console.log(error("Unexpected error with SQLite Durable Object driver \u{1F914}"));
        }
        process.exit(1);
      } else {
        softAssertUnreachable(driver2);
      }
      let text = `Please provide required params:
`;
      console.log(error(text));
      console.log(wrapParam("url", options.url));
      process.exit(1);
    };
  }
});

// src/cli/validations/studio.ts
var credentials, studioCliParams, studioConfig;
var init_studio = __esm({
  "src/cli/validations/studio.ts"() {
    "use strict";
    init_lib();
    init_schemaValidator();
    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()
    });
  }
});

// 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 = _;
  }
});

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

// ../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/common.js
var require_common2 = __commonJS({
  "../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/common.js"(exports2, module2) {
    function setup(env3) {
      createDebug.debug = createDebug;
      createDebug.default = createDebug;
      createDebug.coerce = coerce2;
      createDebug.disable = disable;
      createDebug.enable = enable;
      createDebug.enabled = enabled;
      createDebug.humanize = require_ms();
      createDebug.destroy = destroy;
      Object.keys(env3).forEach((key) => {
        createDebug[key] = env3[key];
      });
      createDebug.names = [];
      createDebug.skips = [];
      createDebug.formatters = {};
      function selectColor(namespace) {
        let hash = 0;
        for (let i2 = 0; i2 < namespace.length; i2++) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i2);
          hash |= 0;
        }
        return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
      }
      createDebug.selectColor = selectColor;
      function createDebug(namespace) {
        let prevTime;
        let enableOverride = null;
        let namespacesCache;
        let enabledCache;
        function debug(...args) {
          if (!debug.enabled) {
            return;
          }
          const self2 = debug;
          const curr = Number(/* @__PURE__ */ new Date());
          const ms = curr - (prevTime || curr);
          self2.diff = ms;
          self2.prev = prevTime;
          self2.curr = curr;
          prevTime = curr;
          args[0] = createDebug.coerce(args[0]);
          if (typeof args[0] !== "string") {
            args.unshift("%O");
          }
          let index5 = 0;
          args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format) => {
            if (match2 === "%%") {
              return "%";
            }
            index5++;
            const formatter = createDebug.formatters[format];
            if (typeof formatter === "function") {
              const val2 = args[index5];
              match2 = formatter.call(self2, val2);
              args.splice(index5, 1);
              index5--;
            }
            return match2;
          });
          createDebug.formatArgs.call(self2, args);
          const logFn = self2.log || createDebug.log;
          logFn.apply(self2, args);
        }
        debug.namespace = namespace;
        debug.useColors = createDebug.useColors();
        debug.color = createDebug.selectColor(namespace);
        debug.extend = extend;
        debug.destroy = createDebug.destroy;
        Object.defineProperty(debug, "enabled", {
          enumerable: true,
          configurable: false,
          get: () => {
            if (enableOverride !== null) {
              return enableOverride;
            }
            if (namespacesCache !== createDebug.namespaces) {
              namespacesCache = createDebug.namespaces;
              enabledCache = createDebug.enabled(namespace);
            }
            return enabledCache;
          },
          set: (v) => {
            enableOverride = v;
          }
        });
        if (typeof createDebug.init === "function") {
          createDebug.init(debug);
        }
        return debug;
      }
      function extend(namespace, delimiter) {
        const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
        newDebug.log = this.log;
        return newDebug;
      }
      function enable(namespaces) {
        createDebug.save(namespaces);
        createDebug.namespaces = namespaces;
        createDebug.names = [];
        createDebug.skips = [];
        let i2;
        const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
        const len = split.length;
        for (i2 = 0; i2 < len; i2++) {
          if (!split[i2]) {
            continue;
          }
          namespaces = split[i2].replace(/\*/g, ".*?");
          if (namespaces[0] === "-") {
            createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
          } else {
            createDebug.names.push(new RegExp("^" + namespaces + "$"));
          }
        }
      }
      function disable() {
        const namespaces = [
          ...createDebug.names.map(toNamespace),
          ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
        ].join(",");
        createDebug.enable("");
        return namespaces;
      }
      function enabled(name) {
        if (name[name.length - 1] === "*") {
          return true;
        }
        let i2;
        let len;
        for (i2 = 0, len = createDebug.skips.length; i2 < len; i2++) {
          if (createDebug.skips[i2].test(name)) {
            return false;
          }
        }
        for (i2 = 0, len = createDebug.names.length; i2 < len; i2++) {
          if (createDebug.names[i2].test(name)) {
            return true;
          }
        }
        return false;
      }
      function toNamespace(regexp) {
        return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
      }
      function coerce2(val2) {
        if (val2 instanceof Error) {
          return val2.stack || val2.message;
        }
        return val2;
      }
      function destroy() {
        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
      }
      createDebug.enable(createDebug.load());
      return createDebug;
    }
    module2.exports = setup;
  }
});

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

// ../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js
var require_has_flag = __commonJS({
  "../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(exports2, module2) {
    "use strict";
    module2.exports = (flag, argv = process.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);
    };
  }
});

// ../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js
var require_supports_color = __commonJS({
  "../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js"(exports2, module2) {
    "use strict";
    var os3 = require("os");
    var tty2 = require("tty");
    var hasFlag2 = require_has_flag();
    var { env: env3 } = process;
    var flagForceColor2;
    if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
      flagForceColor2 = 0;
    } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
      flagForceColor2 = 1;
    }
    function envForceColor2() {
      if ("FORCE_COLOR" in env3) {
        if (env3.FORCE_COLOR === "true") {
          return 1;
        }
        if (env3.FORCE_COLOR === "false") {
          return 0;
        }
        return env3.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env3.FORCE_COLOR, 10), 3);
      }
    }
    function translateLevel2(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor2(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
      const noFlagForceColor = envForceColor2();
      if (noFlagForceColor !== void 0) {
        flagForceColor2 = noFlagForceColor;
      }
      const forceColor = sniffFlags ? flagForceColor2 : noFlagForceColor;
      if (forceColor === 0) {
        return 0;
      }
      if (sniffFlags) {
        if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
          return 3;
        }
        if (hasFlag2("color=256")) {
          return 2;
        }
      }
      if (haveStream && !streamIsTTY && forceColor === void 0) {
        return 0;
      }
      const min = forceColor || 0;
      if (env3.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os3.release().split(".");
        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env3) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env3) || env3.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env3) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env3.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env3) {
        const version3 = Number.parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env3.TERM_PROGRAM) {
          case "iTerm.app":
            return version3 >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env3.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env3) {
        return 1;
      }
      return min;
    }
    function getSupportLevel(stream, options = {}) {
      const level = supportsColor2(stream, {
        streamIsTTY: stream && stream.isTTY,
        ...options
      });
      return translateLevel2(level);
    }
    module2.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel({ isTTY: tty2.isatty(1) }),
      stderr: getSupportLevel({ isTTY: tty2.isatty(2) })
    };
  }
});

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

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

// ../node_modules/.pnpm/esbuild-register@3.5.0_esbuild@0.19.12/node_modules/esbuild-register/dist/node.js
var require_node2 = __commonJS({
  "../node_modules/.pnpm/esbuild-register@3.5.0_esbuild@0.19.12/node_modules/esbuild-register/dist/node.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function _interopRequireDefault2(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __markAsModule = (target) => __defProp3(target, "__esModule", { value: true });
    var __commonJS3 = (callback, module22) => () => {
      if (!module22) {
        module22 = { exports: {} };
        callback(module22.exports, module22);
      }
      return module22.exports;
    };
    var __exportStar3 = (target, module22, desc) => {
      if (module22 && typeof module22 === "object" || typeof module22 === "function") {
        for (let key of __getOwnPropNames3(module22))
          if (!__hasOwnProp3.call(target, key) && key !== "default")
            __defProp3(target, key, { get: () => module22[key], enumerable: !(desc = __getOwnPropDesc3(module22, key)) || desc.enumerable });
      }
      return target;
    };
    var __toModule = (module22) => {
      return __exportStar3(__markAsModule(__defProp3(module22 != null ? __create3(__getProtoOf3(module22)) : {}, "default", module22 && module22.__esModule && "default" in module22 ? { get: () => module22.default, enumerable: true } : { value: module22, enumerable: true })), module22);
    };
    var require_base64 = __commonJS3((exports3) => {
      var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
      exports3.encode = function(number2) {
        if (0 <= number2 && number2 < intToCharMap.length) {
          return intToCharMap[number2];
        }
        throw new TypeError("Must be between 0 and 63: " + number2);
      };
      exports3.decode = function(charCode) {
        var bigA = 65;
        var bigZ = 90;
        var littleA = 97;
        var littleZ = 122;
        var zero = 48;
        var nine = 57;
        var plus = 43;
        var slash = 47;
        var littleOffset = 26;
        var numberOffset = 52;
        if (bigA <= charCode && charCode <= bigZ) {
          return charCode - bigA;
        }
        if (littleA <= charCode && charCode <= littleZ) {
          return charCode - littleA + littleOffset;
        }
        if (zero <= charCode && charCode <= nine) {
          return charCode - zero + numberOffset;
        }
        if (charCode == plus) {
          return 62;
        }
        if (charCode == slash) {
          return 63;
        }
        return -1;
      };
    });
    var require_base64_vlq = __commonJS3((exports3) => {
      var base64 = require_base64();
      var VLQ_BASE_SHIFT = 5;
      var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
      var VLQ_BASE_MASK = VLQ_BASE - 1;
      var VLQ_CONTINUATION_BIT = VLQ_BASE;
      function toVLQSigned(aValue) {
        return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
      }
      function fromVLQSigned(aValue) {
        var isNegative = (aValue & 1) === 1;
        var shifted = aValue >> 1;
        return isNegative ? -shifted : shifted;
      }
      exports3.encode = function base64VLQ_encode(aValue) {
        var encoded = "";
        var digit;
        var vlq = toVLQSigned(aValue);
        do {
          digit = vlq & VLQ_BASE_MASK;
          vlq >>>= VLQ_BASE_SHIFT;
          if (vlq > 0) {
            digit |= VLQ_CONTINUATION_BIT;
          }
          encoded += base64.encode(digit);
        } while (vlq > 0);
        return encoded;
      };
      exports3.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
        var strLen = aStr.length;
        var result = 0;
        var shift = 0;
        var continuation, digit;
        do {
          if (aIndex >= strLen) {
            throw new Error("Expected more digits in base 64 VLQ value.");
          }
          digit = base64.decode(aStr.charCodeAt(aIndex++));
          if (digit === -1) {
            throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
          }
          continuation = !!(digit & VLQ_CONTINUATION_BIT);
          digit &= VLQ_BASE_MASK;
          result = result + (digit << shift);
          shift += VLQ_BASE_SHIFT;
        } while (continuation);
        aOutParam.value = fromVLQSigned(result);
        aOutParam.rest = aIndex;
      };
    });
    var require_util3 = __commonJS3((exports3) => {
      function getArg(aArgs, aName, aDefaultValue) {
        if (aName in aArgs) {
          return aArgs[aName];
        } else if (arguments.length === 3) {
          return aDefaultValue;
        } else {
          throw new Error('"' + aName + '" is a required argument.');
        }
      }
      exports3.getArg = getArg;
      var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
      var dataUrlRegexp = /^data:.+\,.+$/;
      function urlParse(aUrl) {
        var match2 = aUrl.match(urlRegexp);
        if (!match2) {
          return null;
        }
        return {
          scheme: match2[1],
          auth: match2[2],
          host: match2[3],
          port: match2[4],
          path: match2[5]
        };
      }
      exports3.urlParse = urlParse;
      function urlGenerate(aParsedUrl) {
        var url = "";
        if (aParsedUrl.scheme) {
          url += aParsedUrl.scheme + ":";
        }
        url += "//";
        if (aParsedUrl.auth) {
          url += aParsedUrl.auth + "@";
        }
        if (aParsedUrl.host) {
          url += aParsedUrl.host;
        }
        if (aParsedUrl.port) {
          url += ":" + aParsedUrl.port;
        }
        if (aParsedUrl.path) {
          url += aParsedUrl.path;
        }
        return url;
      }
      exports3.urlGenerate = urlGenerate;
      function normalize(aPath) {
        var path4 = aPath;
        var url = urlParse(aPath);
        if (url) {
          if (!url.path) {
            return aPath;
          }
          path4 = url.path;
        }
        var isAbsolute = exports3.isAbsolute(path4);
        var parts = path4.split(/\/+/);
        for (var part, up2 = 0, i2 = parts.length - 1; i2 >= 0; i2--) {
          part = parts[i2];
          if (part === ".") {
            parts.splice(i2, 1);
          } else if (part === "..") {
            up2++;
          } else if (up2 > 0) {
            if (part === "") {
              parts.splice(i2 + 1, up2);
              up2 = 0;
            } else {
              parts.splice(i2, 2);
              up2--;
            }
          }
        }
        path4 = parts.join("/");
        if (path4 === "") {
          path4 = isAbsolute ? "/" : ".";
        }
        if (url) {
          url.path = path4;
          return urlGenerate(url);
        }
        return path4;
      }
      exports3.normalize = normalize;
      function join22(aRoot, aPath) {
        if (aRoot === "") {
          aRoot = ".";
        }
        if (aPath === "") {
          aPath = ".";
        }
        var aPathUrl = urlParse(aPath);
        var aRootUrl = urlParse(aRoot);
        if (aRootUrl) {
          aRoot = aRootUrl.path || "/";
        }
        if (aPathUrl && !aPathUrl.scheme) {
          if (aRootUrl) {
            aPathUrl.scheme = aRootUrl.scheme;
          }
          return urlGenerate(aPathUrl);
        }
        if (aPathUrl || aPath.match(dataUrlRegexp)) {
          return aPath;
        }
        if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
          aRootUrl.host = aPath;
          return urlGenerate(aRootUrl);
        }
        var joined = aPath.charAt(0) === "/" ? aPath : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
        if (aRootUrl) {
          aRootUrl.path = joined;
          return urlGenerate(aRootUrl);
        }
        return joined;
      }
      exports3.join = join22;
      exports3.isAbsolute = function(aPath) {
        return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
      };
      function relative(aRoot, aPath) {
        if (aRoot === "") {
          aRoot = ".";
        }
        aRoot = aRoot.replace(/\/$/, "");
        var level = 0;
        while (aPath.indexOf(aRoot + "/") !== 0) {
          var index5 = aRoot.lastIndexOf("/");
          if (index5 < 0) {
            return aPath;
          }
          aRoot = aRoot.slice(0, index5);
          if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
            return aPath;
          }
          ++level;
        }
        return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
      }
      exports3.relative = relative;
      var supportsNullProto = function() {
        var obj = /* @__PURE__ */ Object.create(null);
        return !("__proto__" in obj);
      }();
      function identity(s2) {
        return s2;
      }
      function toSetString(aStr) {
        if (isProtoString(aStr)) {
          return "$" + aStr;
        }
        return aStr;
      }
      exports3.toSetString = supportsNullProto ? identity : toSetString;
      function fromSetString(aStr) {
        if (isProtoString(aStr)) {
          return aStr.slice(1);
        }
        return aStr;
      }
      exports3.fromSetString = supportsNullProto ? identity : fromSetString;
      function isProtoString(s2) {
        if (!s2) {
          return false;
        }
        var length = s2.length;
        if (length < 9) {
          return false;
        }
        if (s2.charCodeAt(length - 1) !== 95 || s2.charCodeAt(length - 2) !== 95 || s2.charCodeAt(length - 3) !== 111 || s2.charCodeAt(length - 4) !== 116 || s2.charCodeAt(length - 5) !== 111 || s2.charCodeAt(length - 6) !== 114 || s2.charCodeAt(length - 7) !== 112 || s2.charCodeAt(length - 8) !== 95 || s2.charCodeAt(length - 9) !== 95) {
          return false;
        }
        for (var i2 = length - 10; i2 >= 0; i2--) {
          if (s2.charCodeAt(i2) !== 36) {
            return false;
          }
        }
        return true;
      }
      function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
        var cmp = strcmp(mappingA.source, mappingB.source);
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalLine - mappingB.originalLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalColumn - mappingB.originalColumn;
        if (cmp !== 0 || onlyCompareOriginal) {
          return cmp;
        }
        cmp = mappingA.generatedColumn - mappingB.generatedColumn;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.generatedLine - mappingB.generatedLine;
        if (cmp !== 0) {
          return cmp;
        }
        return strcmp(mappingA.name, mappingB.name);
      }
      exports3.compareByOriginalPositions = compareByOriginalPositions;
      function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
        var cmp = mappingA.generatedLine - mappingB.generatedLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.generatedColumn - mappingB.generatedColumn;
        if (cmp !== 0 || onlyCompareGenerated) {
          return cmp;
        }
        cmp = strcmp(mappingA.source, mappingB.source);
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalLine - mappingB.originalLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalColumn - mappingB.originalColumn;
        if (cmp !== 0) {
          return cmp;
        }
        return strcmp(mappingA.name, mappingB.name);
      }
      exports3.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
      function strcmp(aStr1, aStr2) {
        if (aStr1 === aStr2) {
          return 0;
        }
        if (aStr1 === null) {
          return 1;
        }
        if (aStr2 === null) {
          return -1;
        }
        if (aStr1 > aStr2) {
          return 1;
        }
        return -1;
      }
      function compareByGeneratedPositionsInflated(mappingA, mappingB) {
        var cmp = mappingA.generatedLine - mappingB.generatedLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.generatedColumn - mappingB.generatedColumn;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = strcmp(mappingA.source, mappingB.source);
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalLine - mappingB.originalLine;
        if (cmp !== 0) {
          return cmp;
        }
        cmp = mappingA.originalColumn - mappingB.originalColumn;
        if (cmp !== 0) {
          return cmp;
        }
        return strcmp(mappingA.name, mappingB.name);
      }
      exports3.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
      function parseSourceMapInput(str) {
        return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
      }
      exports3.parseSourceMapInput = parseSourceMapInput;
      function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
        sourceURL = sourceURL || "";
        if (sourceRoot) {
          if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
            sourceRoot += "/";
          }
          sourceURL = sourceRoot + sourceURL;
        }
        if (sourceMapURL) {
          var parsed = urlParse(sourceMapURL);
          if (!parsed) {
            throw new Error("sourceMapURL could not be parsed");
          }
          if (parsed.path) {
            var index5 = parsed.path.lastIndexOf("/");
            if (index5 >= 0) {
              parsed.path = parsed.path.substring(0, index5 + 1);
            }
          }
          sourceURL = join22(urlGenerate(parsed), sourceURL);
        }
        return normalize(sourceURL);
      }
      exports3.computeSourceURL = computeSourceURL;
    });
    var require_array_set = __commonJS3((exports3) => {
      var util2 = require_util3();
      var has = Object.prototype.hasOwnProperty;
      var hasNativeMap = typeof Map !== "undefined";
      function ArraySet() {
        this._array = [];
        this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
      }
      ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
        var set = new ArraySet();
        for (var i2 = 0, len = aArray.length; i2 < len; i2++) {
          set.add(aArray[i2], aAllowDuplicates);
        }
        return set;
      };
      ArraySet.prototype.size = function ArraySet_size() {
        return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
      };
      ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
        var sStr = hasNativeMap ? aStr : util2.toSetString(aStr);
        var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
        var idx = this._array.length;
        if (!isDuplicate || aAllowDuplicates) {
          this._array.push(aStr);
        }
        if (!isDuplicate) {
          if (hasNativeMap) {
            this._set.set(aStr, idx);
          } else {
            this._set[sStr] = idx;
          }
        }
      };
      ArraySet.prototype.has = function ArraySet_has(aStr) {
        if (hasNativeMap) {
          return this._set.has(aStr);
        } else {
          var sStr = util2.toSetString(aStr);
          return has.call(this._set, sStr);
        }
      };
      ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
        if (hasNativeMap) {
          var idx = this._set.get(aStr);
          if (idx >= 0) {
            return idx;
          }
        } else {
          var sStr = util2.toSetString(aStr);
          if (has.call(this._set, sStr)) {
            return this._set[sStr];
          }
        }
        throw new Error('"' + aStr + '" is not in the set.');
      };
      ArraySet.prototype.at = function ArraySet_at(aIdx) {
        if (aIdx >= 0 && aIdx < this._array.length) {
          return this._array[aIdx];
        }
        throw new Error("No element indexed by " + aIdx);
      };
      ArraySet.prototype.toArray = function ArraySet_toArray() {
        return this._array.slice();
      };
      exports3.ArraySet = ArraySet;
    });
    var require_mapping_list = __commonJS3((exports3) => {
      var util2 = require_util3();
      function generatedPositionAfter(mappingA, mappingB) {
        var lineA = mappingA.generatedLine;
        var lineB = mappingB.generatedLine;
        var columnA = mappingA.generatedColumn;
        var columnB = mappingB.generatedColumn;
        return lineB > lineA || lineB == lineA && columnB >= columnA || util2.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
      }
      function MappingList() {
        this._array = [];
        this._sorted = true;
        this._last = { generatedLine: -1, generatedColumn: 0 };
      }
      MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
        this._array.forEach(aCallback, aThisArg);
      };
      MappingList.prototype.add = function MappingList_add(aMapping) {
        if (generatedPositionAfter(this._last, aMapping)) {
          this._last = aMapping;
          this._array.push(aMapping);
        } else {
          this._sorted = false;
          this._array.push(aMapping);
        }
      };
      MappingList.prototype.toArray = function MappingList_toArray() {
        if (!this._sorted) {
          this._array.sort(util2.compareByGeneratedPositionsInflated);
          this._sorted = true;
        }
        return this._array;
      };
      exports3.MappingList = MappingList;
    });
    var require_source_map_generator = __commonJS3((exports3) => {
      var base64VLQ = require_base64_vlq();
      var util2 = require_util3();
      var ArraySet = require_array_set().ArraySet;
      var MappingList = require_mapping_list().MappingList;
      function SourceMapGenerator(aArgs) {
        if (!aArgs) {
          aArgs = {};
        }
        this._file = util2.getArg(aArgs, "file", null);
        this._sourceRoot = util2.getArg(aArgs, "sourceRoot", null);
        this._skipValidation = util2.getArg(aArgs, "skipValidation", false);
        this._sources = new ArraySet();
        this._names = new ArraySet();
        this._mappings = new MappingList();
        this._sourcesContents = null;
      }
      SourceMapGenerator.prototype._version = 3;
      SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
        var sourceRoot = aSourceMapConsumer.sourceRoot;
        var generator = new SourceMapGenerator({
          file: aSourceMapConsumer.file,
          sourceRoot
        });
        aSourceMapConsumer.eachMapping(function(mapping) {
          var newMapping = {
            generated: {
              line: mapping.generatedLine,
              column: mapping.generatedColumn
            }
          };
          if (mapping.source != null) {
            newMapping.source = mapping.source;
            if (sourceRoot != null) {
              newMapping.source = util2.relative(sourceRoot, newMapping.source);
            }
            newMapping.original = {
              line: mapping.originalLine,
              column: mapping.originalColumn
            };
            if (mapping.name != null) {
              newMapping.name = mapping.name;
            }
          }
          generator.addMapping(newMapping);
        });
        aSourceMapConsumer.sources.forEach(function(sourceFile) {
          var sourceRelative = sourceFile;
          if (sourceRoot !== null) {
            sourceRelative = util2.relative(sourceRoot, sourceFile);
          }
          if (!generator._sources.has(sourceRelative)) {
            generator._sources.add(sourceRelative);
          }
          var content = aSourceMapConsumer.sourceContentFor(sourceFile);
          if (content != null) {
            generator.setSourceContent(sourceFile, content);
          }
        });
        return generator;
      };
      SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
        var generated = util2.getArg(aArgs, "generated");
        var original = util2.getArg(aArgs, "original", null);
        var source = util2.getArg(aArgs, "source", null);
        var name = util2.getArg(aArgs, "name", null);
        if (!this._skipValidation) {
          this._validateMapping(generated, original, source, name);
        }
        if (source != null) {
          source = String(source);
          if (!this._sources.has(source)) {
            this._sources.add(source);
          }
        }
        if (name != null) {
          name = String(name);
          if (!this._names.has(name)) {
            this._names.add(name);
          }
        }
        this._mappings.add({
          generatedLine: generated.line,
          generatedColumn: generated.column,
          originalLine: original != null && original.line,
          originalColumn: original != null && original.column,
          source,
          name
        });
      };
      SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
        var source = aSourceFile;
        if (this._sourceRoot != null) {
          source = util2.relative(this._sourceRoot, source);
        }
        if (aSourceContent != null) {
          if (!this._sourcesContents) {
            this._sourcesContents = /* @__PURE__ */ Object.create(null);
          }
          this._sourcesContents[util2.toSetString(source)] = aSourceContent;
        } else if (this._sourcesContents) {
          delete this._sourcesContents[util2.toSetString(source)];
          if (Object.keys(this._sourcesContents).length === 0) {
            this._sourcesContents = null;
          }
        }
      };
      SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
        var sourceFile = aSourceFile;
        if (aSourceFile == null) {
          if (aSourceMapConsumer.file == null) {
            throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);
          }
          sourceFile = aSourceMapConsumer.file;
        }
        var sourceRoot = this._sourceRoot;
        if (sourceRoot != null) {
          sourceFile = util2.relative(sourceRoot, sourceFile);
        }
        var newSources = new ArraySet();
        var newNames = new ArraySet();
        this._mappings.unsortedForEach(function(mapping) {
          if (mapping.source === sourceFile && mapping.originalLine != null) {
            var original = aSourceMapConsumer.originalPositionFor({
              line: mapping.originalLine,
              column: mapping.originalColumn
            });
            if (original.source != null) {
              mapping.source = original.source;
              if (aSourceMapPath != null) {
                mapping.source = util2.join(aSourceMapPath, mapping.source);
              }
              if (sourceRoot != null) {
                mapping.source = util2.relative(sourceRoot, mapping.source);
              }
              mapping.originalLine = original.line;
              mapping.originalColumn = original.column;
              if (original.name != null) {
                mapping.name = original.name;
              }
            }
          }
          var source = mapping.source;
          if (source != null && !newSources.has(source)) {
            newSources.add(source);
          }
          var name = mapping.name;
          if (name != null && !newNames.has(name)) {
            newNames.add(name);
          }
        }, this);
        this._sources = newSources;
        this._names = newNames;
        aSourceMapConsumer.sources.forEach(function(sourceFile2) {
          var content = aSourceMapConsumer.sourceContentFor(sourceFile2);
          if (content != null) {
            if (aSourceMapPath != null) {
              sourceFile2 = util2.join(aSourceMapPath, sourceFile2);
            }
            if (sourceRoot != null) {
              sourceFile2 = util2.relative(sourceRoot, sourceFile2);
            }
            this.setSourceContent(sourceFile2, content);
          }
        }, this);
      };
      SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
        if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
          throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");
        }
        if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
          return;
        } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
          return;
        } else {
          throw new Error("Invalid mapping: " + JSON.stringify({
            generated: aGenerated,
            source: aSource,
            original: aOriginal,
            name: aName
          }));
        }
      };
      SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
        var previousGeneratedColumn = 0;
        var previousGeneratedLine = 1;
        var previousOriginalColumn = 0;
        var previousOriginalLine = 0;
        var previousName = 0;
        var previousSource = 0;
        var result = "";
        var next;
        var mapping;
        var nameIdx;
        var sourceIdx;
        var mappings = this._mappings.toArray();
        for (var i2 = 0, len = mappings.length; i2 < len; i2++) {
          mapping = mappings[i2];
          next = "";
          if (mapping.generatedLine !== previousGeneratedLine) {
            previousGeneratedColumn = 0;
            while (mapping.generatedLine !== previousGeneratedLine) {
              next += ";";
              previousGeneratedLine++;
            }
          } else {
            if (i2 > 0) {
              if (!util2.compareByGeneratedPositionsInflated(mapping, mappings[i2 - 1])) {
                continue;
              }
              next += ",";
            }
          }
          next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
          previousGeneratedColumn = mapping.generatedColumn;
          if (mapping.source != null) {
            sourceIdx = this._sources.indexOf(mapping.source);
            next += base64VLQ.encode(sourceIdx - previousSource);
            previousSource = sourceIdx;
            next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
            previousOriginalLine = mapping.originalLine - 1;
            next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
            previousOriginalColumn = mapping.originalColumn;
            if (mapping.name != null) {
              nameIdx = this._names.indexOf(mapping.name);
              next += base64VLQ.encode(nameIdx - previousName);
              previousName = nameIdx;
            }
          }
          result += next;
        }
        return result;
      };
      SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
        return aSources.map(function(source) {
          if (!this._sourcesContents) {
            return null;
          }
          if (aSourceRoot != null) {
            source = util2.relative(aSourceRoot, source);
          }
          var key = util2.toSetString(source);
          return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
        }, this);
      };
      SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
        var map2 = {
          version: this._version,
          sources: this._sources.toArray(),
          names: this._names.toArray(),
          mappings: this._serializeMappings()
        };
        if (this._file != null) {
          map2.file = this._file;
        }
        if (this._sourceRoot != null) {
          map2.sourceRoot = this._sourceRoot;
        }
        if (this._sourcesContents) {
          map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot);
        }
        return map2;
      };
      SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
        return JSON.stringify(this.toJSON());
      };
      exports3.SourceMapGenerator = SourceMapGenerator;
    });
    var require_binary_search = __commonJS3((exports3) => {
      exports3.GREATEST_LOWER_BOUND = 1;
      exports3.LEAST_UPPER_BOUND = 2;
      function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
        var mid = Math.floor((aHigh - aLow) / 2) + aLow;
        var cmp = aCompare(aNeedle, aHaystack[mid], true);
        if (cmp === 0) {
          return mid;
        } else if (cmp > 0) {
          if (aHigh - mid > 1) {
            return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
          }
          if (aBias == exports3.LEAST_UPPER_BOUND) {
            return aHigh < aHaystack.length ? aHigh : -1;
          } else {
            return mid;
          }
        } else {
          if (mid - aLow > 1) {
            return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
          }
          if (aBias == exports3.LEAST_UPPER_BOUND) {
            return mid;
          } else {
            return aLow < 0 ? -1 : aLow;
          }
        }
      }
      exports3.search = function search(aNeedle, aHaystack, aCompare, aBias) {
        if (aHaystack.length === 0) {
          return -1;
        }
        var index5 = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports3.GREATEST_LOWER_BOUND);
        if (index5 < 0) {
          return -1;
        }
        while (index5 - 1 >= 0) {
          if (aCompare(aHaystack[index5], aHaystack[index5 - 1], true) !== 0) {
            break;
          }
          --index5;
        }
        return index5;
      };
    });
    var require_quick_sort = __commonJS3((exports3) => {
      function swap(ary, x2, y) {
        var temp = ary[x2];
        ary[x2] = ary[y];
        ary[y] = temp;
      }
      function randomIntInRange(low, high) {
        return Math.round(low + Math.random() * (high - low));
      }
      function doQuickSort(ary, comparator, p, r2) {
        if (p < r2) {
          var pivotIndex = randomIntInRange(p, r2);
          var i2 = p - 1;
          swap(ary, pivotIndex, r2);
          var pivot = ary[r2];
          for (var j = p; j < r2; j++) {
            if (comparator(ary[j], pivot) <= 0) {
              i2 += 1;
              swap(ary, i2, j);
            }
          }
          swap(ary, i2 + 1, j);
          var q = i2 + 1;
          doQuickSort(ary, comparator, p, q - 1);
          doQuickSort(ary, comparator, q + 1, r2);
        }
      }
      exports3.quickSort = function(ary, comparator) {
        doQuickSort(ary, comparator, 0, ary.length - 1);
      };
    });
    var require_source_map_consumer = __commonJS3((exports3) => {
      var util2 = require_util3();
      var binarySearch = require_binary_search();
      var ArraySet = require_array_set().ArraySet;
      var base64VLQ = require_base64_vlq();
      var quickSort = require_quick_sort().quickSort;
      function SourceMapConsumer(aSourceMap, aSourceMapURL) {
        var sourceMap = aSourceMap;
        if (typeof aSourceMap === "string") {
          sourceMap = util2.parseSourceMapInput(aSourceMap);
        }
        return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
      }
      SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
        return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
      };
      SourceMapConsumer.prototype._version = 3;
      SourceMapConsumer.prototype.__generatedMappings = null;
      Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", {
        configurable: true,
        enumerable: true,
        get: function() {
          if (!this.__generatedMappings) {
            this._parseMappings(this._mappings, this.sourceRoot);
          }
          return this.__generatedMappings;
        }
      });
      SourceMapConsumer.prototype.__originalMappings = null;
      Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", {
        configurable: true,
        enumerable: true,
        get: function() {
          if (!this.__originalMappings) {
            this._parseMappings(this._mappings, this.sourceRoot);
          }
          return this.__originalMappings;
        }
      });
      SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index5) {
        var c = aStr.charAt(index5);
        return c === ";" || c === ",";
      };
      SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
        throw new Error("Subclasses must implement _parseMappings");
      };
      SourceMapConsumer.GENERATED_ORDER = 1;
      SourceMapConsumer.ORIGINAL_ORDER = 2;
      SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
      SourceMapConsumer.LEAST_UPPER_BOUND = 2;
      SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
        var context = aContext || null;
        var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
        var mappings;
        switch (order) {
          case SourceMapConsumer.GENERATED_ORDER:
            mappings = this._generatedMappings;
            break;
          case SourceMapConsumer.ORIGINAL_ORDER:
            mappings = this._originalMappings;
            break;
          default:
            throw new Error("Unknown order of iteration.");
        }
        var sourceRoot = this.sourceRoot;
        mappings.map(function(mapping) {
          var source = mapping.source === null ? null : this._sources.at(mapping.source);
          source = util2.computeSourceURL(sourceRoot, source, this._sourceMapURL);
          return {
            source,
            generatedLine: mapping.generatedLine,
            generatedColumn: mapping.generatedColumn,
            originalLine: mapping.originalLine,
            originalColumn: mapping.originalColumn,
            name: mapping.name === null ? null : this._names.at(mapping.name)
          };
        }, this).forEach(aCallback, context);
      };
      SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
        var line = util2.getArg(aArgs, "line");
        var needle = {
          source: util2.getArg(aArgs, "source"),
          originalLine: line,
          originalColumn: util2.getArg(aArgs, "column", 0)
        };
        needle.source = this._findSourceIndex(needle.source);
        if (needle.source < 0) {
          return [];
        }
        var mappings = [];
        var index5 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND);
        if (index5 >= 0) {
          var mapping = this._originalMappings[index5];
          if (aArgs.column === void 0) {
            var originalLine = mapping.originalLine;
            while (mapping && mapping.originalLine === originalLine) {
              mappings.push({
                line: util2.getArg(mapping, "generatedLine", null),
                column: util2.getArg(mapping, "generatedColumn", null),
                lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
              });
              mapping = this._originalMappings[++index5];
            }
          } else {
            var originalColumn = mapping.originalColumn;
            while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
              mappings.push({
                line: util2.getArg(mapping, "generatedLine", null),
                column: util2.getArg(mapping, "generatedColumn", null),
                lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
              });
              mapping = this._originalMappings[++index5];
            }
          }
        }
        return mappings;
      };
      exports3.SourceMapConsumer = SourceMapConsumer;
      function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
        var sourceMap = aSourceMap;
        if (typeof aSourceMap === "string") {
          sourceMap = util2.parseSourceMapInput(aSourceMap);
        }
        var version3 = util2.getArg(sourceMap, "version");
        var sources = util2.getArg(sourceMap, "sources");
        var names = util2.getArg(sourceMap, "names", []);
        var sourceRoot = util2.getArg(sourceMap, "sourceRoot", null);
        var sourcesContent = util2.getArg(sourceMap, "sourcesContent", null);
        var mappings = util2.getArg(sourceMap, "mappings");
        var file = util2.getArg(sourceMap, "file", null);
        if (version3 != this._version) {
          throw new Error("Unsupported version: " + version3);
        }
        if (sourceRoot) {
          sourceRoot = util2.normalize(sourceRoot);
        }
        sources = sources.map(String).map(util2.normalize).map(function(source) {
          return sourceRoot && util2.isAbsolute(sourceRoot) && util2.isAbsolute(source) ? util2.relative(sourceRoot, source) : source;
        });
        this._names = ArraySet.fromArray(names.map(String), true);
        this._sources = ArraySet.fromArray(sources, true);
        this._absoluteSources = this._sources.toArray().map(function(s2) {
          return util2.computeSourceURL(sourceRoot, s2, aSourceMapURL);
        });
        this.sourceRoot = sourceRoot;
        this.sourcesContent = sourcesContent;
        this._mappings = mappings;
        this._sourceMapURL = aSourceMapURL;
        this.file = file;
      }
      BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
      BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
      BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
        var relativeSource = aSource;
        if (this.sourceRoot != null) {
          relativeSource = util2.relative(this.sourceRoot, relativeSource);
        }
        if (this._sources.has(relativeSource)) {
          return this._sources.indexOf(relativeSource);
        }
        var i2;
        for (i2 = 0; i2 < this._absoluteSources.length; ++i2) {
          if (this._absoluteSources[i2] == aSource) {
            return i2;
          }
        }
        return -1;
      };
      BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
        var smc = Object.create(BasicSourceMapConsumer.prototype);
        var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
        var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
        smc.sourceRoot = aSourceMap._sourceRoot;
        smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
        smc.file = aSourceMap._file;
        smc._sourceMapURL = aSourceMapURL;
        smc._absoluteSources = smc._sources.toArray().map(function(s2) {
          return util2.computeSourceURL(smc.sourceRoot, s2, aSourceMapURL);
        });
        var generatedMappings = aSourceMap._mappings.toArray().slice();
        var destGeneratedMappings = smc.__generatedMappings = [];
        var destOriginalMappings = smc.__originalMappings = [];
        for (var i2 = 0, length = generatedMappings.length; i2 < length; i2++) {
          var srcMapping = generatedMappings[i2];
          var destMapping = new Mapping();
          destMapping.generatedLine = srcMapping.generatedLine;
          destMapping.generatedColumn = srcMapping.generatedColumn;
          if (srcMapping.source) {
            destMapping.source = sources.indexOf(srcMapping.source);
            destMapping.originalLine = srcMapping.originalLine;
            destMapping.originalColumn = srcMapping.originalColumn;
            if (srcMapping.name) {
              destMapping.name = names.indexOf(srcMapping.name);
            }
            destOriginalMappings.push(destMapping);
          }
          destGeneratedMappings.push(destMapping);
        }
        quickSort(smc.__originalMappings, util2.compareByOriginalPositions);
        return smc;
      };
      BasicSourceMapConsumer.prototype._version = 3;
      Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", {
        get: function() {
          return this._absoluteSources.slice();
        }
      });
      function Mapping() {
        this.generatedLine = 0;
        this.generatedColumn = 0;
        this.source = null;
        this.originalLine = null;
        this.originalColumn = null;
        this.name = null;
      }
      BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
        var generatedLine = 1;
        var previousGeneratedColumn = 0;
        var previousOriginalLine = 0;
        var previousOriginalColumn = 0;
        var previousSource = 0;
        var previousName = 0;
        var length = aStr.length;
        var index5 = 0;
        var cachedSegments = {};
        var temp = {};
        var originalMappings = [];
        var generatedMappings = [];
        var mapping, str, segment, end, value;
        while (index5 < length) {
          if (aStr.charAt(index5) === ";") {
            generatedLine++;
            index5++;
            previousGeneratedColumn = 0;
          } else if (aStr.charAt(index5) === ",") {
            index5++;
          } else {
            mapping = new Mapping();
            mapping.generatedLine = generatedLine;
            for (end = index5; end < length; end++) {
              if (this._charIsMappingSeparator(aStr, end)) {
                break;
              }
            }
            str = aStr.slice(index5, end);
            segment = cachedSegments[str];
            if (segment) {
              index5 += str.length;
            } else {
              segment = [];
              while (index5 < end) {
                base64VLQ.decode(aStr, index5, temp);
                value = temp.value;
                index5 = temp.rest;
                segment.push(value);
              }
              if (segment.length === 2) {
                throw new Error("Found a source, but no line and column");
              }
              if (segment.length === 3) {
                throw new Error("Found a source and line, but no column");
              }
              cachedSegments[str] = segment;
            }
            mapping.generatedColumn = previousGeneratedColumn + segment[0];
            previousGeneratedColumn = mapping.generatedColumn;
            if (segment.length > 1) {
              mapping.source = previousSource + segment[1];
              previousSource += segment[1];
              mapping.originalLine = previousOriginalLine + segment[2];
              previousOriginalLine = mapping.originalLine;
              mapping.originalLine += 1;
              mapping.originalColumn = previousOriginalColumn + segment[3];
              previousOriginalColumn = mapping.originalColumn;
              if (segment.length > 4) {
                mapping.name = previousName + segment[4];
                previousName += segment[4];
              }
            }
            generatedMappings.push(mapping);
            if (typeof mapping.originalLine === "number") {
              originalMappings.push(mapping);
            }
          }
        }
        quickSort(generatedMappings, util2.compareByGeneratedPositionsDeflated);
        this.__generatedMappings = generatedMappings;
        quickSort(originalMappings, util2.compareByOriginalPositions);
        this.__originalMappings = originalMappings;
      };
      BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
        if (aNeedle[aLineName] <= 0) {
          throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
        }
        if (aNeedle[aColumnName] < 0) {
          throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
        }
        return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
      };
      BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
        for (var index5 = 0; index5 < this._generatedMappings.length; ++index5) {
          var mapping = this._generatedMappings[index5];
          if (index5 + 1 < this._generatedMappings.length) {
            var nextMapping = this._generatedMappings[index5 + 1];
            if (mapping.generatedLine === nextMapping.generatedLine) {
              mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
              continue;
            }
          }
          mapping.lastGeneratedColumn = Infinity;
        }
      };
      BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
        var needle = {
          generatedLine: util2.getArg(aArgs, "line"),
          generatedColumn: util2.getArg(aArgs, "column")
        };
        var index5 = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util2.compareByGeneratedPositionsDeflated, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
        if (index5 >= 0) {
          var mapping = this._generatedMappings[index5];
          if (mapping.generatedLine === needle.generatedLine) {
            var source = util2.getArg(mapping, "source", null);
            if (source !== null) {
              source = this._sources.at(source);
              source = util2.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
            }
            var name = util2.getArg(mapping, "name", null);
            if (name !== null) {
              name = this._names.at(name);
            }
            return {
              source,
              line: util2.getArg(mapping, "originalLine", null),
              column: util2.getArg(mapping, "originalColumn", null),
              name
            };
          }
        }
        return {
          source: null,
          line: null,
          column: null,
          name: null
        };
      };
      BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
        if (!this.sourcesContent) {
          return false;
        }
        return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
          return sc == null;
        });
      };
      BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
        if (!this.sourcesContent) {
          return null;
        }
        var index5 = this._findSourceIndex(aSource);
        if (index5 >= 0) {
          return this.sourcesContent[index5];
        }
        var relativeSource = aSource;
        if (this.sourceRoot != null) {
          relativeSource = util2.relative(this.sourceRoot, relativeSource);
        }
        var url;
        if (this.sourceRoot != null && (url = util2.urlParse(this.sourceRoot))) {
          var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
          if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
            return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
          }
          if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) {
            return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
          }
        }
        if (nullOnMissing) {
          return null;
        } else {
          throw new Error('"' + relativeSource + '" is not in the SourceMap.');
        }
      };
      BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
        var source = util2.getArg(aArgs, "source");
        source = this._findSourceIndex(source);
        if (source < 0) {
          return {
            line: null,
            column: null,
            lastColumn: null
          };
        }
        var needle = {
          source,
          originalLine: util2.getArg(aArgs, "line"),
          originalColumn: util2.getArg(aArgs, "column")
        };
        var index5 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
        if (index5 >= 0) {
          var mapping = this._originalMappings[index5];
          if (mapping.source === needle.source) {
            return {
              line: util2.getArg(mapping, "generatedLine", null),
              column: util2.getArg(mapping, "generatedColumn", null),
              lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
            };
          }
        }
        return {
          line: null,
          column: null,
          lastColumn: null
        };
      };
      exports3.BasicSourceMapConsumer = BasicSourceMapConsumer;
      function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
        var sourceMap = aSourceMap;
        if (typeof aSourceMap === "string") {
          sourceMap = util2.parseSourceMapInput(aSourceMap);
        }
        var version3 = util2.getArg(sourceMap, "version");
        var sections = util2.getArg(sourceMap, "sections");
        if (version3 != this._version) {
          throw new Error("Unsupported version: " + version3);
        }
        this._sources = new ArraySet();
        this._names = new ArraySet();
        var lastOffset = {
          line: -1,
          column: 0
        };
        this._sections = sections.map(function(s2) {
          if (s2.url) {
            throw new Error("Support for url field in sections not implemented.");
          }
          var offset = util2.getArg(s2, "offset");
          var offsetLine = util2.getArg(offset, "line");
          var offsetColumn = util2.getArg(offset, "column");
          if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
            throw new Error("Section offsets must be ordered and non-overlapping.");
          }
          lastOffset = offset;
          return {
            generatedOffset: {
              generatedLine: offsetLine + 1,
              generatedColumn: offsetColumn + 1
            },
            consumer: new SourceMapConsumer(util2.getArg(s2, "map"), aSourceMapURL)
          };
        });
      }
      IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
      IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
      IndexedSourceMapConsumer.prototype._version = 3;
      Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", {
        get: function() {
          var sources = [];
          for (var i2 = 0; i2 < this._sections.length; i2++) {
            for (var j = 0; j < this._sections[i2].consumer.sources.length; j++) {
              sources.push(this._sections[i2].consumer.sources[j]);
            }
          }
          return sources;
        }
      });
      IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
        var needle = {
          generatedLine: util2.getArg(aArgs, "line"),
          generatedColumn: util2.getArg(aArgs, "column")
        };
        var sectionIndex = binarySearch.search(needle, this._sections, function(needle2, section2) {
          var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine;
          if (cmp) {
            return cmp;
          }
          return needle2.generatedColumn - section2.generatedOffset.generatedColumn;
        });
        var section = this._sections[sectionIndex];
        if (!section) {
          return {
            source: null,
            line: null,
            column: null,
            name: null
          };
        }
        return section.consumer.originalPositionFor({
          line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
          column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
          bias: aArgs.bias
        });
      };
      IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
        return this._sections.every(function(s2) {
          return s2.consumer.hasContentsOfAllSources();
        });
      };
      IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
        for (var i2 = 0; i2 < this._sections.length; i2++) {
          var section = this._sections[i2];
          var content = section.consumer.sourceContentFor(aSource, true);
          if (content) {
            return content;
          }
        }
        if (nullOnMissing) {
          return null;
        } else {
          throw new Error('"' + aSource + '" is not in the SourceMap.');
        }
      };
      IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
        for (var i2 = 0; i2 < this._sections.length; i2++) {
          var section = this._sections[i2];
          if (section.consumer._findSourceIndex(util2.getArg(aArgs, "source")) === -1) {
            continue;
          }
          var generatedPosition = section.consumer.generatedPositionFor(aArgs);
          if (generatedPosition) {
            var ret = {
              line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
              column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
            };
            return ret;
          }
        }
        return {
          line: null,
          column: null
        };
      };
      IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
        this.__generatedMappings = [];
        this.__originalMappings = [];
        for (var i2 = 0; i2 < this._sections.length; i2++) {
          var section = this._sections[i2];
          var sectionMappings = section.consumer._generatedMappings;
          for (var j = 0; j < sectionMappings.length; j++) {
            var mapping = sectionMappings[j];
            var source = section.consumer._sources.at(mapping.source);
            source = util2.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
            this._sources.add(source);
            source = this._sources.indexOf(source);
            var name = null;
            if (mapping.name) {
              name = section.consumer._names.at(mapping.name);
              this._names.add(name);
              name = this._names.indexOf(name);
            }
            var adjustedMapping = {
              source,
              generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
              generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
              originalLine: mapping.originalLine,
              originalColumn: mapping.originalColumn,
              name
            };
            this.__generatedMappings.push(adjustedMapping);
            if (typeof adjustedMapping.originalLine === "number") {
              this.__originalMappings.push(adjustedMapping);
            }
          }
        }
        quickSort(this.__generatedMappings, util2.compareByGeneratedPositionsDeflated);
        quickSort(this.__originalMappings, util2.compareByOriginalPositions);
      };
      exports3.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
    });
    var require_source_node = __commonJS3((exports3) => {
      var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
      var util2 = require_util3();
      var REGEX_NEWLINE = /(\r?\n)/;
      var NEWLINE_CODE = 10;
      var isSourceNode = "$$$isSourceNode$$$";
      function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
        this.children = [];
        this.sourceContents = {};
        this.line = aLine == null ? null : aLine;
        this.column = aColumn == null ? null : aColumn;
        this.source = aSource == null ? null : aSource;
        this.name = aName == null ? null : aName;
        this[isSourceNode] = true;
        if (aChunks != null)
          this.add(aChunks);
      }
      SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
        var node = new SourceNode();
        var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
        var remainingLinesIndex = 0;
        var shiftNextLine = function() {
          var lineContents = getNextLine();
          var newLine = getNextLine() || "";
          return lineContents + newLine;
          function getNextLine() {
            return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
          }
        };
        var lastGeneratedLine = 1, lastGeneratedColumn = 0;
        var lastMapping = null;
        aSourceMapConsumer.eachMapping(function(mapping) {
          if (lastMapping !== null) {
            if (lastGeneratedLine < mapping.generatedLine) {
              addMappingWithCode(lastMapping, shiftNextLine());
              lastGeneratedLine++;
              lastGeneratedColumn = 0;
            } else {
              var nextLine = remainingLines[remainingLinesIndex] || "";
              var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
              remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
              lastGeneratedColumn = mapping.generatedColumn;
              addMappingWithCode(lastMapping, code);
              lastMapping = mapping;
              return;
            }
          }
          while (lastGeneratedLine < mapping.generatedLine) {
            node.add(shiftNextLine());
            lastGeneratedLine++;
          }
          if (lastGeneratedColumn < mapping.generatedColumn) {
            var nextLine = remainingLines[remainingLinesIndex] || "";
            node.add(nextLine.substr(0, mapping.generatedColumn));
            remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
            lastGeneratedColumn = mapping.generatedColumn;
          }
          lastMapping = mapping;
        }, this);
        if (remainingLinesIndex < remainingLines.length) {
          if (lastMapping) {
            addMappingWithCode(lastMapping, shiftNextLine());
          }
          node.add(remainingLines.splice(remainingLinesIndex).join(""));
        }
        aSourceMapConsumer.sources.forEach(function(sourceFile) {
          var content = aSourceMapConsumer.sourceContentFor(sourceFile);
          if (content != null) {
            if (aRelativePath != null) {
              sourceFile = util2.join(aRelativePath, sourceFile);
            }
            node.setSourceContent(sourceFile, content);
          }
        });
        return node;
        function addMappingWithCode(mapping, code) {
          if (mapping === null || mapping.source === void 0) {
            node.add(code);
          } else {
            var source = aRelativePath ? util2.join(aRelativePath, mapping.source) : mapping.source;
            node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
          }
        }
      };
      SourceNode.prototype.add = function SourceNode_add(aChunk) {
        if (Array.isArray(aChunk)) {
          aChunk.forEach(function(chunk) {
            this.add(chunk);
          }, this);
        } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
          if (aChunk) {
            this.children.push(aChunk);
          }
        } else {
          throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
        }
        return this;
      };
      SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
        if (Array.isArray(aChunk)) {
          for (var i2 = aChunk.length - 1; i2 >= 0; i2--) {
            this.prepend(aChunk[i2]);
          }
        } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
          this.children.unshift(aChunk);
        } else {
          throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
        }
        return this;
      };
      SourceNode.prototype.walk = function SourceNode_walk(aFn) {
        var chunk;
        for (var i2 = 0, len = this.children.length; i2 < len; i2++) {
          chunk = this.children[i2];
          if (chunk[isSourceNode]) {
            chunk.walk(aFn);
          } else {
            if (chunk !== "") {
              aFn(chunk, {
                source: this.source,
                line: this.line,
                column: this.column,
                name: this.name
              });
            }
          }
        }
      };
      SourceNode.prototype.join = function SourceNode_join(aSep) {
        var newChildren;
        var i2;
        var len = this.children.length;
        if (len > 0) {
          newChildren = [];
          for (i2 = 0; i2 < len - 1; i2++) {
            newChildren.push(this.children[i2]);
            newChildren.push(aSep);
          }
          newChildren.push(this.children[i2]);
          this.children = newChildren;
        }
        return this;
      };
      SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
        var lastChild = this.children[this.children.length - 1];
        if (lastChild[isSourceNode]) {
          lastChild.replaceRight(aPattern, aReplacement);
        } else if (typeof lastChild === "string") {
          this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
        } else {
          this.children.push("".replace(aPattern, aReplacement));
        }
        return this;
      };
      SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
        this.sourceContents[util2.toSetString(aSourceFile)] = aSourceContent;
      };
      SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
        for (var i2 = 0, len = this.children.length; i2 < len; i2++) {
          if (this.children[i2][isSourceNode]) {
            this.children[i2].walkSourceContents(aFn);
          }
        }
        var sources = Object.keys(this.sourceContents);
        for (var i2 = 0, len = sources.length; i2 < len; i2++) {
          aFn(util2.fromSetString(sources[i2]), this.sourceContents[sources[i2]]);
        }
      };
      SourceNode.prototype.toString = function SourceNode_toString() {
        var str = "";
        this.walk(function(chunk) {
          str += chunk;
        });
        return str;
      };
      SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
        var generated = {
          code: "",
          line: 1,
          column: 0
        };
        var map2 = new SourceMapGenerator(aArgs);
        var sourceMappingActive = false;
        var lastOriginalSource = null;
        var lastOriginalLine = null;
        var lastOriginalColumn = null;
        var lastOriginalName = null;
        this.walk(function(chunk, original) {
          generated.code += chunk;
          if (original.source !== null && original.line !== null && original.column !== null) {
            if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
              map2.addMapping({
                source: original.source,
                original: {
                  line: original.line,
                  column: original.column
                },
                generated: {
                  line: generated.line,
                  column: generated.column
                },
                name: original.name
              });
            }
            lastOriginalSource = original.source;
            lastOriginalLine = original.line;
            lastOriginalColumn = original.column;
            lastOriginalName = original.name;
            sourceMappingActive = true;
          } else if (sourceMappingActive) {
            map2.addMapping({
              generated: {
                line: generated.line,
                column: generated.column
              }
            });
            lastOriginalSource = null;
            sourceMappingActive = false;
          }
          for (var idx = 0, length = chunk.length; idx < length; idx++) {
            if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
              generated.line++;
              generated.column = 0;
              if (idx + 1 === length) {
                lastOriginalSource = null;
                sourceMappingActive = false;
              } else if (sourceMappingActive) {
                map2.addMapping({
                  source: original.source,
                  original: {
                    line: original.line,
                    column: original.column
                  },
                  generated: {
                    line: generated.line,
                    column: generated.column
                  },
                  name: original.name
                });
              }
            } else {
              generated.column++;
            }
          }
        });
        this.walkSourceContents(function(sourceFile, sourceContent) {
          map2.setSourceContent(sourceFile, sourceContent);
        });
        return { code: generated.code, map: map2 };
      };
      exports3.SourceNode = SourceNode;
    });
    var require_source_map = __commonJS3((exports3) => {
      exports3.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
      exports3.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
      exports3.SourceNode = require_source_node().SourceNode;
    });
    var require_buffer_from = __commonJS3((exports3, module22) => {
      var toString = Object.prototype.toString;
      var isModern = typeof Buffer.alloc === "function" && typeof Buffer.allocUnsafe === "function" && typeof Buffer.from === "function";
      function isArrayBuffer(input) {
        return toString.call(input).slice(8, -1) === "ArrayBuffer";
      }
      function fromArrayBuffer(obj, byteOffset, length) {
        byteOffset >>>= 0;
        var maxLength = obj.byteLength - byteOffset;
        if (maxLength < 0) {
          throw new RangeError("'offset' is out of bounds");
        }
        if (length === void 0) {
          length = maxLength;
        } else {
          length >>>= 0;
          if (length > maxLength) {
            throw new RangeError("'length' is out of bounds");
          }
        }
        return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)));
      }
      function fromString(string2, encoding) {
        if (typeof encoding !== "string" || encoding === "") {
          encoding = "utf8";
        }
        if (!Buffer.isEncoding(encoding)) {
          throw new TypeError('"encoding" must be a valid string encoding');
        }
        return isModern ? Buffer.from(string2, encoding) : new Buffer(string2, encoding);
      }
      function bufferFrom(value, encodingOrOffset, length) {
        if (typeof value === "number") {
          throw new TypeError('"value" argument must not be a number');
        }
        if (isArrayBuffer(value)) {
          return fromArrayBuffer(value, encodingOrOffset, length);
        }
        if (typeof value === "string") {
          return fromString(value, encodingOrOffset);
        }
        return isModern ? Buffer.from(value) : new Buffer(value);
      }
      module22.exports = bufferFrom;
    });
    var require_source_map_support = __commonJS3((exports3, module22) => {
      var SourceMapConsumer = require_source_map().SourceMapConsumer;
      var path4 = require("path");
      var fs32;
      try {
        fs32 = require("fs");
        if (!fs32.existsSync || !fs32.readFileSync) {
          fs32 = null;
        }
      } catch (err2) {
      }
      var bufferFrom = require_buffer_from();
      function dynamicRequire(mod, request) {
        return mod.require(request);
      }
      var errorFormatterInstalled = false;
      var uncaughtShimInstalled = false;
      var emptyCacheBetweenOperations = false;
      var environment = "auto";
      var fileContentsCache = {};
      var sourceMapCache = {};
      var reSourceMap = /^data:application\/json[^,]+base64,/;
      var retrieveFileHandlers = [];
      var retrieveMapHandlers = [];
      function isInBrowser() {
        if (environment === "browser")
          return true;
        if (environment === "node")
          return false;
        return typeof window !== "undefined" && typeof XMLHttpRequest === "function" && !(window.require && window.module && window.process && window.process.type === "renderer");
      }
      function hasGlobalProcessEventEmitter() {
        return typeof process === "object" && process !== null && typeof process.on === "function";
      }
      function handlerExec(list) {
        return function(arg) {
          for (var i2 = 0; i2 < list.length; i2++) {
            var ret = list[i2](arg);
            if (ret) {
              return ret;
            }
          }
          return null;
        };
      }
      var retrieveFile = handlerExec(retrieveFileHandlers);
      retrieveFileHandlers.push(function(path22) {
        path22 = path22.trim();
        if (/^file:/.test(path22)) {
          path22 = path22.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
            return drive ? "" : "/";
          });
        }
        if (path22 in fileContentsCache) {
          return fileContentsCache[path22];
        }
        var contents = "";
        try {
          if (!fs32) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", path22, false);
            xhr.send(null);
            if (xhr.readyState === 4 && xhr.status === 200) {
              contents = xhr.responseText;
            }
          } else if (fs32.existsSync(path22)) {
            contents = fs32.readFileSync(path22, "utf8");
          }
        } catch (er) {
        }
        return fileContentsCache[path22] = contents;
      });
      function supportRelativeURL(file, url) {
        if (!file)
          return url;
        var dir = path4.dirname(file);
        var match2 = /^\w+:\/\/[^\/]*/.exec(dir);
        var protocol = match2 ? match2[0] : "";
        var startPath = dir.slice(protocol.length);
        if (protocol && /^\/\w\:/.test(startPath)) {
          protocol += "/";
          return protocol + path4.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
        }
        return protocol + path4.resolve(dir.slice(protocol.length), url);
      }
      function retrieveSourceMapURL(source) {
        var fileData;
        if (isInBrowser()) {
          try {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", source, false);
            xhr.send(null);
            fileData = xhr.readyState === 4 ? xhr.responseText : null;
            var sourceMapHeader = xhr.getResponseHeader("SourceMap") || xhr.getResponseHeader("X-SourceMap");
            if (sourceMapHeader) {
              return sourceMapHeader;
            }
          } catch (e2) {
          }
        }
        fileData = retrieveFile(source);
        var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
        var lastMatch, match2;
        while (match2 = re.exec(fileData))
          lastMatch = match2;
        if (!lastMatch)
          return null;
        return lastMatch[1];
      }
      var retrieveSourceMap = handlerExec(retrieveMapHandlers);
      retrieveMapHandlers.push(function(source) {
        var sourceMappingURL = retrieveSourceMapURL(source);
        if (!sourceMappingURL)
          return null;
        var sourceMapData;
        if (reSourceMap.test(sourceMappingURL)) {
          var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
          sourceMapData = bufferFrom(rawData, "base64").toString();
          sourceMappingURL = source;
        } else {
          sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
          sourceMapData = retrieveFile(sourceMappingURL);
        }
        if (!sourceMapData) {
          return null;
        }
        return {
          url: sourceMappingURL,
          map: sourceMapData
        };
      });
      function mapSourcePosition(position) {
        var sourceMap = sourceMapCache[position.source];
        if (!sourceMap) {
          var urlAndMap = retrieveSourceMap(position.source);
          if (urlAndMap) {
            sourceMap = sourceMapCache[position.source] = {
              url: urlAndMap.url,
              map: new SourceMapConsumer(urlAndMap.map)
            };
            if (sourceMap.map.sourcesContent) {
              sourceMap.map.sources.forEach(function(source, i2) {
                var contents = sourceMap.map.sourcesContent[i2];
                if (contents) {
                  var url = supportRelativeURL(sourceMap.url, source);
                  fileContentsCache[url] = contents;
                }
              });
            }
          } else {
            sourceMap = sourceMapCache[position.source] = {
              url: null,
              map: null
            };
          }
        }
        if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === "function") {
          var originalPosition = sourceMap.map.originalPositionFor(position);
          if (originalPosition.source !== null) {
            originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source);
            return originalPosition;
          }
        }
        return position;
      }
      function mapEvalOrigin(origin) {
        var match2 = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
        if (match2) {
          var position = mapSourcePosition({
            source: match2[2],
            line: +match2[3],
            column: match2[4] - 1
          });
          return "eval at " + match2[1] + " (" + position.source + ":" + position.line + ":" + (position.column + 1) + ")";
        }
        match2 = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
        if (match2) {
          return "eval at " + match2[1] + " (" + mapEvalOrigin(match2[2]) + ")";
        }
        return origin;
      }
      function CallSiteToString() {
        var fileName;
        var fileLocation = "";
        if (this.isNative()) {
          fileLocation = "native";
        } else {
          fileName = this.getScriptNameOrSourceURL();
          if (!fileName && this.isEval()) {
            fileLocation = this.getEvalOrigin();
            fileLocation += ", ";
          }
          if (fileName) {
            fileLocation += fileName;
          } else {
            fileLocation += "<anonymous>";
          }
          var lineNumber = this.getLineNumber();
          if (lineNumber != null) {
            fileLocation += ":" + lineNumber;
            var columnNumber = this.getColumnNumber();
            if (columnNumber) {
              fileLocation += ":" + columnNumber;
            }
          }
        }
        var line = "";
        var functionName = this.getFunctionName();
        var addSuffix = true;
        var isConstructor = this.isConstructor();
        var isMethodCall = !(this.isToplevel() || isConstructor);
        if (isMethodCall) {
          var typeName = this.getTypeName();
          if (typeName === "[object Object]") {
            typeName = "null";
          }
          var methodName = this.getMethodName();
          if (functionName) {
            if (typeName && functionName.indexOf(typeName) != 0) {
              line += typeName + ".";
            }
            line += functionName;
            if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
              line += " [as " + methodName + "]";
            }
          } else {
            line += typeName + "." + (methodName || "<anonymous>");
          }
        } else if (isConstructor) {
          line += "new " + (functionName || "<anonymous>");
        } else if (functionName) {
          line += functionName;
        } else {
          line += fileLocation;
          addSuffix = false;
        }
        if (addSuffix) {
          line += " (" + fileLocation + ")";
        }
        return line;
      }
      function cloneCallSite(frame) {
        var object = {};
        Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
          object[name] = /^(?:is|get)/.test(name) ? function() {
            return frame[name].call(frame);
          } : frame[name];
        });
        object.toString = CallSiteToString;
        return object;
      }
      function wrapCallSite(frame, state) {
        if (state === void 0) {
          state = { nextPosition: null, curPosition: null };
        }
        if (frame.isNative()) {
          state.curPosition = null;
          return frame;
        }
        var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
        if (source) {
          var line = frame.getLineNumber();
          var column9 = frame.getColumnNumber() - 1;
          var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
          var headerLength = noHeader.test(process.version) ? 0 : 62;
          if (line === 1 && column9 > headerLength && !isInBrowser() && !frame.isEval()) {
            column9 -= headerLength;
          }
          var position = mapSourcePosition({
            source,
            line,
            column: column9
          });
          state.curPosition = position;
          frame = cloneCallSite(frame);
          var originalFunctionName = frame.getFunctionName;
          frame.getFunctionName = function() {
            if (state.nextPosition == null) {
              return originalFunctionName();
            }
            return state.nextPosition.name || originalFunctionName();
          };
          frame.getFileName = function() {
            return position.source;
          };
          frame.getLineNumber = function() {
            return position.line;
          };
          frame.getColumnNumber = function() {
            return position.column + 1;
          };
          frame.getScriptNameOrSourceURL = function() {
            return position.source;
          };
          return frame;
        }
        var origin = frame.isEval() && frame.getEvalOrigin();
        if (origin) {
          origin = mapEvalOrigin(origin);
          frame = cloneCallSite(frame);
          frame.getEvalOrigin = function() {
            return origin;
          };
          return frame;
        }
        return frame;
      }
      function prepareStackTrace(error2, stack) {
        if (emptyCacheBetweenOperations) {
          fileContentsCache = {};
          sourceMapCache = {};
        }
        var name = error2.name || "Error";
        var message = error2.message || "";
        var errorString = name + ": " + message;
        var state = { nextPosition: null, curPosition: null };
        var processedStack = [];
        for (var i2 = stack.length - 1; i2 >= 0; i2--) {
          processedStack.push("\n    at " + wrapCallSite(stack[i2], state));
          state.nextPosition = state.curPosition;
        }
        state.curPosition = state.nextPosition = null;
        return errorString + processedStack.reverse().join("");
      }
      function getErrorSource(error2) {
        var match2 = /\n    at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error2.stack);
        if (match2) {
          var source = match2[1];
          var line = +match2[2];
          var column9 = +match2[3];
          var contents = fileContentsCache[source];
          if (!contents && fs32 && fs32.existsSync(source)) {
            try {
              contents = fs32.readFileSync(source, "utf8");
            } catch (er) {
              contents = "";
            }
          }
          if (contents) {
            var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
            if (code) {
              return source + ":" + line + "\n" + code + "\n" + new Array(column9).join(" ") + "^";
            }
          }
        }
        return null;
      }
      function printErrorAndExit(error2) {
        var source = getErrorSource(error2);
        if (process.stderr._handle && process.stderr._handle.setBlocking) {
          process.stderr._handle.setBlocking(true);
        }
        if (source) {
          console.error();
          console.error(source);
        }
        console.error(error2.stack);
        process.exit(1);
      }
      function shimEmitUncaughtException() {
        var origEmit = process.emit;
        process.emit = function(type) {
          if (type === "uncaughtException") {
            var hasStack = arguments[1] && arguments[1].stack;
            var hasListeners = this.listeners(type).length > 0;
            if (hasStack && !hasListeners) {
              return printErrorAndExit(arguments[1]);
            }
          }
          return origEmit.apply(this, arguments);
        };
      }
      var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
      var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
      exports3.wrapCallSite = wrapCallSite;
      exports3.getErrorSource = getErrorSource;
      exports3.mapSourcePosition = mapSourcePosition;
      exports3.retrieveSourceMap = retrieveSourceMap;
      exports3.install = function(options) {
        options = options || {};
        if (options.environment) {
          environment = options.environment;
          if (["node", "browser", "auto"].indexOf(environment) === -1) {
            throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}");
          }
        }
        if (options.retrieveFile) {
          if (options.overrideRetrieveFile) {
            retrieveFileHandlers.length = 0;
          }
          retrieveFileHandlers.unshift(options.retrieveFile);
        }
        if (options.retrieveSourceMap) {
          if (options.overrideRetrieveSourceMap) {
            retrieveMapHandlers.length = 0;
          }
          retrieveMapHandlers.unshift(options.retrieveSourceMap);
        }
        if (options.hookRequire && !isInBrowser()) {
          var Module = dynamicRequire(module22, "module");
          var $compile = Module.prototype._compile;
          if (!$compile.__sourceMapSupport) {
            Module.prototype._compile = function(content, filename) {
              fileContentsCache[filename] = content;
              sourceMapCache[filename] = void 0;
              return $compile.call(this, content, filename);
            };
            Module.prototype._compile.__sourceMapSupport = true;
          }
        }
        if (!emptyCacheBetweenOperations) {
          emptyCacheBetweenOperations = "emptyCacheBetweenOperations" in options ? options.emptyCacheBetweenOperations : false;
        }
        if (!errorFormatterInstalled) {
          errorFormatterInstalled = true;
          Error.prepareStackTrace = prepareStackTrace;
        }
        if (!uncaughtShimInstalled) {
          var installHandler = "handleUncaughtExceptions" in options ? options.handleUncaughtExceptions : true;
          try {
            var worker_threads = dynamicRequire(module22, "worker_threads");
            if (worker_threads.isMainThread === false) {
              installHandler = false;
            }
          } catch (e2) {
          }
          if (installHandler && hasGlobalProcessEventEmitter()) {
            uncaughtShimInstalled = true;
            shimEmitUncaughtException();
          }
        }
      };
      exports3.resetRetrieveHandlers = function() {
        retrieveFileHandlers.length = 0;
        retrieveMapHandlers.length = 0;
        retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
        retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
        retrieveSourceMap = handlerExec(retrieveMapHandlers);
        retrieveFile = handlerExec(retrieveFileHandlers);
      };
    });
    var require_node_modules_regexp = __commonJS3((exports3, module22) => {
      "use strict";
      module22.exports = /^(?:.*[\\\/])?node_modules(?:[\\\/].*)?$/;
    });
    var require_lib2 = __commonJS3((exports3, module22) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", {
        value: true
      });
      exports3.addHook = addHook2;
      var _module = _interopRequireDefault(require("module"));
      var _path = _interopRequireDefault(require("path"));
      var _nodeModulesRegexp = _interopRequireDefault(require_node_modules_regexp());
      function _interopRequireDefault(obj) {
        return obj && obj.__esModule ? obj : { default: obj };
      }
      var Module = module22.constructor.length > 1 ? module22.constructor : _module.default;
      var HOOK_RETURNED_NOTHING_ERROR_MESSAGE = "[Pirates] A hook returned a non-string, or nothing at all! This is a violation of intergalactic law!\n--------------------\nIf you have no idea what this means or what Pirates is, let me explain: Pirates is a module that makes is easy to implement require hooks. One of the require hooks you're using uses it. One of these require hooks didn't return anything from it's handler, so we don't know what to do. You might want to debug this.";
      function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
        if (typeof filename !== "string") {
          return false;
        }
        if (exts.indexOf(_path.default.extname(filename)) === -1) {
          return false;
        }
        const resolvedFilename = _path.default.resolve(filename);
        if (ignoreNodeModules && _nodeModulesRegexp.default.test(resolvedFilename)) {
          return false;
        }
        if (matcher && typeof matcher === "function") {
          return !!matcher(resolvedFilename);
        }
        return true;
      }
      function addHook2(hook, opts = {}) {
        let reverted = false;
        const loaders = [];
        const oldLoaders = [];
        let exts;
        const originalJSLoader = Module._extensions[".js"];
        const matcher = opts.matcher || null;
        const ignoreNodeModules = opts.ignoreNodeModules !== false;
        exts = opts.extensions || opts.exts || opts.extension || opts.ext || [".js"];
        if (!Array.isArray(exts)) {
          exts = [exts];
        }
        exts.forEach((ext2) => {
          if (typeof ext2 !== "string") {
            throw new TypeError(`Invalid Extension: ${ext2}`);
          }
          const oldLoader = Module._extensions[ext2] || originalJSLoader;
          oldLoaders[ext2] = oldLoader;
          loaders[ext2] = Module._extensions[ext2] = function newLoader(mod, filename) {
            let compile;
            if (!reverted) {
              if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
                compile = mod._compile;
                mod._compile = function _compile(code) {
                  mod._compile = compile;
                  const newCode = hook(code, filename);
                  if (typeof newCode !== "string") {
                    throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
                  }
                  return mod._compile(newCode, filename);
                };
              }
            }
            oldLoader(mod, filename);
          };
        });
        return function revert() {
          if (reverted)
            return;
          reverted = true;
          exts.forEach((ext2) => {
            if (Module._extensions[ext2] === loaders[ext2]) {
              Module._extensions[ext2] = oldLoaders[ext2];
            }
          });
        };
      }
    });
    var require_lib22 = __commonJS3((exports3, module22) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", {
        value: true
      });
      exports3.default = void 0;
      var _fs = _interopRequireDefault(require("fs"));
      var _path = _interopRequireDefault(require("path"));
      function _interopRequireDefault(obj) {
        return obj && obj.__esModule ? obj : { default: obj };
      }
      function asyncGeneratorStep(gen, resolve2, reject, _next, _throw, key, arg) {
        try {
          var info2 = gen[key](arg);
          var value = info2.value;
        } catch (error2) {
          reject(error2);
          return;
        }
        if (info2.done) {
          resolve2(value);
        } else {
          Promise.resolve(value).then(_next, _throw);
        }
      }
      function _asyncToGenerator(fn) {
        return function() {
          var self2 = this, args = arguments;
          return new Promise(function(resolve2, reject) {
            var gen = fn.apply(self2, args);
            function _next(value) {
              asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "next", value);
            }
            function _throw(err2) {
              asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "throw", err2);
            }
            _next(void 0);
          });
        };
      }
      var readFile2 = (fp) => new Promise((resolve2, reject) => {
        _fs.default.readFile(fp, "utf8", (err2, data) => {
          if (err2)
            return reject(err2);
          resolve2(data);
        });
      });
      var readFileSync3 = (fp) => {
        return _fs.default.readFileSync(fp, "utf8");
      };
      var pathExists = (fp) => new Promise((resolve2) => {
        _fs.default.access(fp, (err2) => {
          resolve2(!err2);
        });
      });
      var pathExistsSync = _fs.default.existsSync;
      var JoyCon2 = class {
        constructor({
          files,
          cwd = process.cwd(),
          stopDir,
          packageKey,
          parseJSON = JSON.parse
        } = {}) {
          this.options = {
            files,
            cwd,
            stopDir,
            packageKey,
            parseJSON
          };
          this.existsCache = /* @__PURE__ */ new Map();
          this.loaders = /* @__PURE__ */ new Set();
          this.packageJsonCache = /* @__PURE__ */ new Map();
        }
        addLoader(loader) {
          this.loaders.add(loader);
          return this;
        }
        removeLoader(name) {
          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = void 0;
          try {
            for (var _iterator = this.loaders[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              const loader = _step.value;
              if (name && loader.name === name) {
                this.loaders.delete(loader);
              }
            }
          } catch (err2) {
            _didIteratorError = true;
            _iteratorError = err2;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }
          return this;
        }
        recusivelyResolve(options) {
          var _this = this;
          return _asyncToGenerator(function* () {
            if (options.cwd === options.stopDir || _path.default.basename(options.cwd) === "node_modules") {
              return null;
            }
            var _iteratorNormalCompletion4 = true;
            var _didIteratorError4 = false;
            var _iteratorError4 = void 0;
            try {
              for (var _iterator4 = options.files[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                const filename = _step4.value;
                const file = _path.default.resolve(options.cwd, filename);
                const exists = process.env.NODE_ENV !== "test" && _this.existsCache.has(file) ? _this.existsCache.get(file) : yield pathExists(file);
                _this.existsCache.set(file, exists);
                if (exists) {
                  if (!options.packageKey || _path.default.basename(file) !== "package.json") {
                    return file;
                  }
                  const data = require(file);
                  delete require.cache[file];
                  const hasPackageKey = Object.prototype.hasOwnProperty.call(data, options.packageKey);
                  if (hasPackageKey) {
                    _this.packageJsonCache.set(file, data);
                    return file;
                  }
                }
                continue;
              }
            } catch (err2) {
              _didIteratorError4 = true;
              _iteratorError4 = err2;
            } finally {
              try {
                if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
                  _iterator4.return();
                }
              } finally {
                if (_didIteratorError4) {
                  throw _iteratorError4;
                }
              }
            }
            return _this.recusivelyResolve(Object.assign({}, options, {
              cwd: _path.default.dirname(options.cwd)
            }));
          })();
        }
        recusivelyResolveSync(options) {
          if (options.cwd === options.stopDir || _path.default.basename(options.cwd) === "node_modules") {
            return null;
          }
          var _iteratorNormalCompletion2 = true;
          var _didIteratorError2 = false;
          var _iteratorError2 = void 0;
          try {
            for (var _iterator2 = options.files[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              const filename = _step2.value;
              const file = _path.default.resolve(options.cwd, filename);
              const exists = process.env.NODE_ENV !== "test" && this.existsCache.has(file) ? this.existsCache.get(file) : pathExistsSync(file);
              this.existsCache.set(file, exists);
              if (exists) {
                if (!options.packageKey || _path.default.basename(file) !== "package.json") {
                  return file;
                }
                const data = require(file);
                delete require.cache[file];
                const hasPackageKey = Object.prototype.hasOwnProperty.call(data, options.packageKey);
                if (hasPackageKey) {
                  this.packageJsonCache.set(file, data);
                  return file;
                }
              }
              continue;
            }
          } catch (err2) {
            _didIteratorError2 = true;
            _iteratorError2 = err2;
          } finally {
            try {
              if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                _iterator2.return();
              }
            } finally {
              if (_didIteratorError2) {
                throw _iteratorError2;
              }
            }
          }
          return this.recusivelyResolveSync(Object.assign({}, options, {
            cwd: _path.default.dirname(options.cwd)
          }));
        }
        resolve(...args) {
          var _this2 = this;
          return _asyncToGenerator(function* () {
            const options = _this2.normalizeOptions(args);
            return _this2.recusivelyResolve(options);
          })();
        }
        resolveSync(...args) {
          const options = this.normalizeOptions(args);
          return this.recusivelyResolveSync(options);
        }
        load(...args) {
          var _this3 = this;
          return _asyncToGenerator(function* () {
            const options = _this3.normalizeOptions(args);
            const filepath = yield _this3.recusivelyResolve(options);
            if (filepath) {
              const loader = _this3.findLoader(filepath);
              if (loader) {
                return {
                  path: filepath,
                  data: yield loader.load(filepath)
                };
              }
              const extname2 = _path.default.extname(filepath).slice(1);
              if (extname2 === "js") {
                delete require.cache[filepath];
                return {
                  path: filepath,
                  data: require(filepath)
                };
              }
              if (extname2 === "json") {
                if (_this3.packageJsonCache.has(filepath)) {
                  return {
                    path: filepath,
                    data: _this3.packageJsonCache.get(filepath)[options.packageKey]
                  };
                }
                const data = _this3.options.parseJSON(yield readFile2(filepath));
                return {
                  path: filepath,
                  data
                };
              }
              return {
                path: filepath,
                data: yield readFile2(filepath)
              };
            }
            return {};
          })();
        }
        loadSync(...args) {
          const options = this.normalizeOptions(args);
          const filepath = this.recusivelyResolveSync(options);
          if (filepath) {
            const loader = this.findLoader(filepath);
            if (loader) {
              return {
                path: filepath,
                data: loader.loadSync(filepath)
              };
            }
            const extname2 = _path.default.extname(filepath).slice(1);
            if (extname2 === "js") {
              delete require.cache[filepath];
              return {
                path: filepath,
                data: require(filepath)
              };
            }
            if (extname2 === "json") {
              if (this.packageJsonCache.has(filepath)) {
                return {
                  path: filepath,
                  data: this.packageJsonCache.get(filepath)[options.packageKey]
                };
              }
              const data = this.options.parseJSON(readFileSync3(filepath));
              return {
                path: filepath,
                data
              };
            }
            return {
              path: filepath,
              data: readFileSync3(filepath)
            };
          }
          return {};
        }
        findLoader(filepath) {
          var _iteratorNormalCompletion3 = true;
          var _didIteratorError3 = false;
          var _iteratorError3 = void 0;
          try {
            for (var _iterator3 = this.loaders[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
              const loader = _step3.value;
              if (loader.test && loader.test.test(filepath)) {
                return loader;
              }
            }
          } catch (err2) {
            _didIteratorError3 = true;
            _iteratorError3 = err2;
          } finally {
            try {
              if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
                _iterator3.return();
              }
            } finally {
              if (_didIteratorError3) {
                throw _iteratorError3;
              }
            }
          }
          return null;
        }
        clearCache() {
          this.existsCache.clear();
          this.packageJsonCache.clear();
          return this;
        }
        normalizeOptions(args) {
          const options = Object.assign({}, this.options);
          if (Object.prototype.toString.call(args[0]) === "[object Object]") {
            Object.assign(options, args[0]);
          } else {
            if (args[0]) {
              options.files = args[0];
            }
            if (args[1]) {
              options.cwd = args[1];
            }
            if (args[2]) {
              options.stopDir = args[2];
            }
          }
          options.cwd = _path.default.resolve(options.cwd);
          options.stopDir = options.stopDir ? _path.default.resolve(options.stopDir) : _path.default.parse(options.cwd).root;
          if (!options.files || options.files.length === 0) {
            throw new Error("[joycon] files must be an non-empty array!");
          }
          options.__normalized__ = true;
          return options;
        }
      };
      exports3.default = JoyCon2;
      module22.exports = JoyCon2;
      module22.exports.default = JoyCon2;
    });
    var require_filesystem = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.removeExtension = exports3.fileExistsAsync = exports3.readJsonFromDiskAsync = exports3.readJsonFromDiskSync = exports3.fileExistsSync = void 0;
      var fs32 = require("fs");
      function fileExistsSync(path4) {
        if (!fs32.existsSync(path4)) {
          return false;
        }
        try {
          var stats = fs32.statSync(path4);
          return stats.isFile();
        } catch (err2) {
          return false;
        }
      }
      exports3.fileExistsSync = fileExistsSync;
      function readJsonFromDiskSync(packageJsonPath) {
        if (!fs32.existsSync(packageJsonPath)) {
          return void 0;
        }
        return require(packageJsonPath);
      }
      exports3.readJsonFromDiskSync = readJsonFromDiskSync;
      function readJsonFromDiskAsync(path4, callback) {
        fs32.readFile(path4, "utf8", function(err2, result) {
          if (err2 || !result) {
            return callback();
          }
          var json = JSON.parse(result);
          return callback(void 0, json);
        });
      }
      exports3.readJsonFromDiskAsync = readJsonFromDiskAsync;
      function fileExistsAsync(path22, callback2) {
        fs32.stat(path22, function(err2, stats) {
          if (err2) {
            return callback2(void 0, false);
          }
          callback2(void 0, stats ? stats.isFile() : false);
        });
      }
      exports3.fileExistsAsync = fileExistsAsync;
      function removeExtension(path4) {
        return path4.substring(0, path4.lastIndexOf(".")) || path4;
      }
      exports3.removeExtension = removeExtension;
    });
    var require_mapping_entry = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.getAbsoluteMappingEntries = void 0;
      var path4 = require("path");
      function getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll) {
        var sortedKeys = sortByLongestPrefix(Object.keys(paths));
        var absolutePaths = [];
        for (var _i = 0, sortedKeys_1 = sortedKeys; _i < sortedKeys_1.length; _i++) {
          var key = sortedKeys_1[_i];
          absolutePaths.push({
            pattern: key,
            paths: paths[key].map(function(pathToResolve) {
              return path4.resolve(absoluteBaseUrl, pathToResolve);
            })
          });
        }
        if (!paths["*"] && addMatchAll) {
          absolutePaths.push({
            pattern: "*",
            paths: ["".concat(absoluteBaseUrl.replace(/\/$/, ""), "/*")]
          });
        }
        return absolutePaths;
      }
      exports3.getAbsoluteMappingEntries = getAbsoluteMappingEntries;
      function sortByLongestPrefix(arr) {
        return arr.concat().sort(function(a, b) {
          return getPrefixLength(b) - getPrefixLength(a);
        });
      }
      function getPrefixLength(pattern) {
        var prefixLength = pattern.indexOf("*");
        return pattern.substr(0, prefixLength).length;
      }
    });
    var require_try_path = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.exhaustiveTypeException = exports3.getStrippedPath = exports3.getPathsToTry = void 0;
      var path4 = require("path");
      var path_1 = require("path");
      var filesystem_1 = require_filesystem();
      function getPathsToTry(extensions, absolutePathMappings, requestedModule) {
        if (!absolutePathMappings || !requestedModule || requestedModule[0] === ".") {
          return void 0;
        }
        var pathsToTry = [];
        for (var _i = 0, absolutePathMappings_1 = absolutePathMappings; _i < absolutePathMappings_1.length; _i++) {
          var entry = absolutePathMappings_1[_i];
          var starMatch = entry.pattern === requestedModule ? "" : matchStar(entry.pattern, requestedModule);
          if (starMatch !== void 0) {
            var _loop_1 = function(physicalPathPattern2) {
              var physicalPath = physicalPathPattern2.replace("*", starMatch);
              pathsToTry.push({ type: "file", path: physicalPath });
              pathsToTry.push.apply(pathsToTry, extensions.map(function(e2) {
                return { type: "extension", path: physicalPath + e2 };
              }));
              pathsToTry.push({
                type: "package",
                path: path4.join(physicalPath, "/package.json")
              });
              var indexPath = path4.join(physicalPath, "/index");
              pathsToTry.push.apply(pathsToTry, extensions.map(function(e2) {
                return { type: "index", path: indexPath + e2 };
              }));
            };
            for (var _a = 0, _b = entry.paths; _a < _b.length; _a++) {
              var physicalPathPattern = _b[_a];
              _loop_1(physicalPathPattern);
            }
          }
        }
        return pathsToTry.length === 0 ? void 0 : pathsToTry;
      }
      exports3.getPathsToTry = getPathsToTry;
      function getStrippedPath(tryPath) {
        return tryPath.type === "index" ? (0, path_1.dirname)(tryPath.path) : tryPath.type === "file" ? tryPath.path : tryPath.type === "extension" ? (0, filesystem_1.removeExtension)(tryPath.path) : tryPath.type === "package" ? tryPath.path : exhaustiveTypeException(tryPath.type);
      }
      exports3.getStrippedPath = getStrippedPath;
      function exhaustiveTypeException(check2) {
        throw new Error("Unknown type ".concat(check2));
      }
      exports3.exhaustiveTypeException = exhaustiveTypeException;
      function matchStar(pattern, search) {
        if (search.length < pattern.length) {
          return void 0;
        }
        if (pattern === "*") {
          return search;
        }
        var star2 = pattern.indexOf("*");
        if (star2 === -1) {
          return void 0;
        }
        var part1 = pattern.substring(0, star2);
        var part2 = pattern.substring(star2 + 1);
        if (search.substr(0, star2) !== part1) {
          return void 0;
        }
        if (search.substr(search.length - part2.length) !== part2) {
          return void 0;
        }
        return search.substr(star2, search.length - part2.length);
      }
    });
    var require_match_path_sync = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.matchFromAbsolutePaths = exports3.createMatchPath = void 0;
      var path4 = require("path");
      var Filesystem = require_filesystem();
      var MappingEntry = require_mapping_entry();
      var TryPath = require_try_path();
      function createMatchPath2(absoluteBaseUrl, paths, mainFields, addMatchAll) {
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        if (addMatchAll === void 0) {
          addMatchAll = true;
        }
        var absolutePaths = MappingEntry.getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll);
        return function(requestedModule, readJson, fileExists, extensions) {
          return matchFromAbsolutePaths(absolutePaths, requestedModule, readJson, fileExists, extensions, mainFields);
        };
      }
      exports3.createMatchPath = createMatchPath2;
      function matchFromAbsolutePaths(absolutePathMappings, requestedModule, readJson, fileExists, extensions, mainFields) {
        if (readJson === void 0) {
          readJson = Filesystem.readJsonFromDiskSync;
        }
        if (fileExists === void 0) {
          fileExists = Filesystem.fileExistsSync;
        }
        if (extensions === void 0) {
          extensions = Object.keys(require.extensions);
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        var tryPaths = TryPath.getPathsToTry(extensions, absolutePathMappings, requestedModule);
        if (!tryPaths) {
          return void 0;
        }
        return findFirstExistingPath(tryPaths, readJson, fileExists, mainFields);
      }
      exports3.matchFromAbsolutePaths = matchFromAbsolutePaths;
      function findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExists) {
        for (var index5 = 0; index5 < mainFields.length; index5++) {
          var mainFieldSelector = mainFields[index5];
          var candidateMapping = typeof mainFieldSelector === "string" ? packageJson[mainFieldSelector] : mainFieldSelector.reduce(function(obj, key) {
            return obj[key];
          }, packageJson);
          if (candidateMapping && typeof candidateMapping === "string") {
            var candidateFilePath = path4.join(path4.dirname(packageJsonPath), candidateMapping);
            if (fileExists(candidateFilePath)) {
              return candidateFilePath;
            }
          }
        }
        return void 0;
      }
      function findFirstExistingPath(tryPaths, readJson, fileExists, mainFields) {
        if (readJson === void 0) {
          readJson = Filesystem.readJsonFromDiskSync;
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        for (var _i = 0, tryPaths_1 = tryPaths; _i < tryPaths_1.length; _i++) {
          var tryPath = tryPaths_1[_i];
          if (tryPath.type === "file" || tryPath.type === "extension" || tryPath.type === "index") {
            if (fileExists(tryPath.path)) {
              return TryPath.getStrippedPath(tryPath);
            }
          } else if (tryPath.type === "package") {
            var packageJson = readJson(tryPath.path);
            if (packageJson) {
              var mainFieldMappedFile = findFirstExistingMainFieldMappedFile(packageJson, mainFields, tryPath.path, fileExists);
              if (mainFieldMappedFile) {
                return mainFieldMappedFile;
              }
            }
          } else {
            TryPath.exhaustiveTypeException(tryPath.type);
          }
        }
        return void 0;
      }
    });
    var require_match_path_async = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.matchFromAbsolutePathsAsync = exports3.createMatchPathAsync = void 0;
      var path4 = require("path");
      var TryPath = require_try_path();
      var MappingEntry = require_mapping_entry();
      var Filesystem = require_filesystem();
      function createMatchPathAsync(absoluteBaseUrl, paths, mainFields, addMatchAll) {
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        if (addMatchAll === void 0) {
          addMatchAll = true;
        }
        var absolutePaths = MappingEntry.getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll);
        return function(requestedModule, readJson, fileExists, extensions, callback) {
          return matchFromAbsolutePathsAsync(absolutePaths, requestedModule, readJson, fileExists, extensions, callback, mainFields);
        };
      }
      exports3.createMatchPathAsync = createMatchPathAsync;
      function matchFromAbsolutePathsAsync(absolutePathMappings, requestedModule, readJson, fileExists, extensions, callback, mainFields) {
        if (readJson === void 0) {
          readJson = Filesystem.readJsonFromDiskAsync;
        }
        if (fileExists === void 0) {
          fileExists = Filesystem.fileExistsAsync;
        }
        if (extensions === void 0) {
          extensions = Object.keys(require.extensions);
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        var tryPaths = TryPath.getPathsToTry(extensions, absolutePathMappings, requestedModule);
        if (!tryPaths) {
          return callback();
        }
        findFirstExistingPath(tryPaths, readJson, fileExists, callback, 0, mainFields);
      }
      exports3.matchFromAbsolutePathsAsync = matchFromAbsolutePathsAsync;
      function findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExistsAsync, doneCallback, index5) {
        if (index5 === void 0) {
          index5 = 0;
        }
        if (index5 >= mainFields.length) {
          return doneCallback(void 0, void 0);
        }
        var tryNext = function() {
          return findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExistsAsync, doneCallback, index5 + 1);
        };
        var mainFieldSelector = mainFields[index5];
        var mainFieldMapping = typeof mainFieldSelector === "string" ? packageJson[mainFieldSelector] : mainFieldSelector.reduce(function(obj, key) {
          return obj[key];
        }, packageJson);
        if (typeof mainFieldMapping !== "string") {
          return tryNext();
        }
        var mappedFilePath = path4.join(path4.dirname(packageJsonPath), mainFieldMapping);
        fileExistsAsync(mappedFilePath, function(err2, exists) {
          if (err2) {
            return doneCallback(err2);
          }
          if (exists) {
            return doneCallback(void 0, mappedFilePath);
          }
          return tryNext();
        });
      }
      function findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5, mainFields) {
        if (index5 === void 0) {
          index5 = 0;
        }
        if (mainFields === void 0) {
          mainFields = ["main"];
        }
        var tryPath = tryPaths[index5];
        if (tryPath.type === "file" || tryPath.type === "extension" || tryPath.type === "index") {
          fileExists(tryPath.path, function(err2, exists) {
            if (err2) {
              return doneCallback(err2);
            }
            if (exists) {
              return doneCallback(void 0, TryPath.getStrippedPath(tryPath));
            }
            if (index5 === tryPaths.length - 1) {
              return doneCallback();
            }
            return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5 + 1, mainFields);
          });
        } else if (tryPath.type === "package") {
          readJson(tryPath.path, function(err2, packageJson) {
            if (err2) {
              return doneCallback(err2);
            }
            if (packageJson) {
              return findFirstExistingMainFieldMappedFile(packageJson, mainFields, tryPath.path, fileExists, function(mainFieldErr, mainFieldMappedFile) {
                if (mainFieldErr) {
                  return doneCallback(mainFieldErr);
                }
                if (mainFieldMappedFile) {
                  return doneCallback(void 0, mainFieldMappedFile);
                }
                return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5 + 1, mainFields);
              });
            }
            return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5 + 1, mainFields);
          });
        } else {
          TryPath.exhaustiveTypeException(tryPath.type);
        }
      }
    });
    var require_unicode = __commonJS3((exports3, module22) => {
      module22.exports.Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
      module22.exports.ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
      module22.exports.ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
    });
    var require_util22 = __commonJS3((exports3, module22) => {
      var unicode = require_unicode();
      module22.exports = {
        isSpaceSeparator(c) {
          return typeof c === "string" && unicode.Space_Separator.test(c);
        },
        isIdStartChar(c) {
          return typeof c === "string" && (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "$" || c === "_" || unicode.ID_Start.test(c));
        },
        isIdContinueChar(c) {
          return typeof c === "string" && (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c >= "0" && c <= "9" || c === "$" || c === "_" || c === "\u200C" || c === "\u200D" || unicode.ID_Continue.test(c));
        },
        isDigit(c) {
          return typeof c === "string" && /[0-9]/.test(c);
        },
        isHexDigit(c) {
          return typeof c === "string" && /[0-9A-Fa-f]/.test(c);
        }
      };
    });
    var require_parse3 = __commonJS3((exports3, module22) => {
      var util2 = require_util22();
      var source;
      var parseState;
      var stack;
      var pos;
      var line;
      var column9;
      var token;
      var key;
      var root;
      module22.exports = function parse5(text, reviver) {
        source = String(text);
        parseState = "start";
        stack = [];
        pos = 0;
        line = 1;
        column9 = 0;
        token = void 0;
        key = void 0;
        root = void 0;
        do {
          token = lex();
          parseStates[parseState]();
        } while (token.type !== "eof");
        if (typeof reviver === "function") {
          return internalize({ "": root }, "", reviver);
        }
        return root;
      };
      function internalize(holder, name, reviver) {
        const value = holder[name];
        if (value != null && typeof value === "object") {
          if (Array.isArray(value)) {
            for (let i2 = 0; i2 < value.length; i2++) {
              const key2 = String(i2);
              const replacement = internalize(value, key2, reviver);
              if (replacement === void 0) {
                delete value[key2];
              } else {
                Object.defineProperty(value, key2, {
                  value: replacement,
                  writable: true,
                  enumerable: true,
                  configurable: true
                });
              }
            }
          } else {
            for (const key2 in value) {
              const replacement = internalize(value, key2, reviver);
              if (replacement === void 0) {
                delete value[key2];
              } else {
                Object.defineProperty(value, key2, {
                  value: replacement,
                  writable: true,
                  enumerable: true,
                  configurable: true
                });
              }
            }
          }
        }
        return reviver.call(holder, name, value);
      }
      var lexState;
      var buffer;
      var doubleQuote;
      var sign;
      var c;
      function lex() {
        lexState = "default";
        buffer = "";
        doubleQuote = false;
        sign = 1;
        for (; ; ) {
          c = peek();
          const token2 = lexStates[lexState]();
          if (token2) {
            return token2;
          }
        }
      }
      function peek() {
        if (source[pos]) {
          return String.fromCodePoint(source.codePointAt(pos));
        }
      }
      function read() {
        const c2 = peek();
        if (c2 === "\n") {
          line++;
          column9 = 0;
        } else if (c2) {
          column9 += c2.length;
        } else {
          column9++;
        }
        if (c2) {
          pos += c2.length;
        }
        return c2;
      }
      var lexStates = {
        default() {
          switch (c) {
            case "	":
            case "\v":
            case "\f":
            case " ":
            case "\xA0":
            case "\uFEFF":
            case "\n":
            case "\r":
            case "\u2028":
            case "\u2029":
              read();
              return;
            case "/":
              read();
              lexState = "comment";
              return;
            case void 0:
              read();
              return newToken("eof");
          }
          if (util2.isSpaceSeparator(c)) {
            read();
            return;
          }
          return lexStates[parseState]();
        },
        comment() {
          switch (c) {
            case "*":
              read();
              lexState = "multiLineComment";
              return;
            case "/":
              read();
              lexState = "singleLineComment";
              return;
          }
          throw invalidChar(read());
        },
        multiLineComment() {
          switch (c) {
            case "*":
              read();
              lexState = "multiLineCommentAsterisk";
              return;
            case void 0:
              throw invalidChar(read());
          }
          read();
        },
        multiLineCommentAsterisk() {
          switch (c) {
            case "*":
              read();
              return;
            case "/":
              read();
              lexState = "default";
              return;
            case void 0:
              throw invalidChar(read());
          }
          read();
          lexState = "multiLineComment";
        },
        singleLineComment() {
          switch (c) {
            case "\n":
            case "\r":
            case "\u2028":
            case "\u2029":
              read();
              lexState = "default";
              return;
            case void 0:
              read();
              return newToken("eof");
          }
          read();
        },
        value() {
          switch (c) {
            case "{":
            case "[":
              return newToken("punctuator", read());
            case "n":
              read();
              literal("ull");
              return newToken("null", null);
            case "t":
              read();
              literal("rue");
              return newToken("boolean", true);
            case "f":
              read();
              literal("alse");
              return newToken("boolean", false);
            case "-":
            case "+":
              if (read() === "-") {
                sign = -1;
              }
              lexState = "sign";
              return;
            case ".":
              buffer = read();
              lexState = "decimalPointLeading";
              return;
            case "0":
              buffer = read();
              lexState = "zero";
              return;
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
              buffer = read();
              lexState = "decimalInteger";
              return;
            case "I":
              read();
              literal("nfinity");
              return newToken("numeric", Infinity);
            case "N":
              read();
              literal("aN");
              return newToken("numeric", NaN);
            case '"':
            case "'":
              doubleQuote = read() === '"';
              buffer = "";
              lexState = "string";
              return;
          }
          throw invalidChar(read());
        },
        identifierNameStartEscape() {
          if (c !== "u") {
            throw invalidChar(read());
          }
          read();
          const u = unicodeEscape();
          switch (u) {
            case "$":
            case "_":
              break;
            default:
              if (!util2.isIdStartChar(u)) {
                throw invalidIdentifier();
              }
              break;
          }
          buffer += u;
          lexState = "identifierName";
        },
        identifierName() {
          switch (c) {
            case "$":
            case "_":
            case "\u200C":
            case "\u200D":
              buffer += read();
              return;
            case "\\":
              read();
              lexState = "identifierNameEscape";
              return;
          }
          if (util2.isIdContinueChar(c)) {
            buffer += read();
            return;
          }
          return newToken("identifier", buffer);
        },
        identifierNameEscape() {
          if (c !== "u") {
            throw invalidChar(read());
          }
          read();
          const u = unicodeEscape();
          switch (u) {
            case "$":
            case "_":
            case "\u200C":
            case "\u200D":
              break;
            default:
              if (!util2.isIdContinueChar(u)) {
                throw invalidIdentifier();
              }
              break;
          }
          buffer += u;
          lexState = "identifierName";
        },
        sign() {
          switch (c) {
            case ".":
              buffer = read();
              lexState = "decimalPointLeading";
              return;
            case "0":
              buffer = read();
              lexState = "zero";
              return;
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
              buffer = read();
              lexState = "decimalInteger";
              return;
            case "I":
              read();
              literal("nfinity");
              return newToken("numeric", sign * Infinity);
            case "N":
              read();
              literal("aN");
              return newToken("numeric", NaN);
          }
          throw invalidChar(read());
        },
        zero() {
          switch (c) {
            case ".":
              buffer += read();
              lexState = "decimalPoint";
              return;
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
            case "x":
            case "X":
              buffer += read();
              lexState = "hexadecimal";
              return;
          }
          return newToken("numeric", sign * 0);
        },
        decimalInteger() {
          switch (c) {
            case ".":
              buffer += read();
              lexState = "decimalPoint";
              return;
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util2.isDigit(c)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalPointLeading() {
          if (util2.isDigit(c)) {
            buffer += read();
            lexState = "decimalFraction";
            return;
          }
          throw invalidChar(read());
        },
        decimalPoint() {
          switch (c) {
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util2.isDigit(c)) {
            buffer += read();
            lexState = "decimalFraction";
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalFraction() {
          switch (c) {
            case "e":
            case "E":
              buffer += read();
              lexState = "decimalExponent";
              return;
          }
          if (util2.isDigit(c)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        decimalExponent() {
          switch (c) {
            case "+":
            case "-":
              buffer += read();
              lexState = "decimalExponentSign";
              return;
          }
          if (util2.isDigit(c)) {
            buffer += read();
            lexState = "decimalExponentInteger";
            return;
          }
          throw invalidChar(read());
        },
        decimalExponentSign() {
          if (util2.isDigit(c)) {
            buffer += read();
            lexState = "decimalExponentInteger";
            return;
          }
          throw invalidChar(read());
        },
        decimalExponentInteger() {
          if (util2.isDigit(c)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        hexadecimal() {
          if (util2.isHexDigit(c)) {
            buffer += read();
            lexState = "hexadecimalInteger";
            return;
          }
          throw invalidChar(read());
        },
        hexadecimalInteger() {
          if (util2.isHexDigit(c)) {
            buffer += read();
            return;
          }
          return newToken("numeric", sign * Number(buffer));
        },
        string() {
          switch (c) {
            case "\\":
              read();
              buffer += escape2();
              return;
            case '"':
              if (doubleQuote) {
                read();
                return newToken("string", buffer);
              }
              buffer += read();
              return;
            case "'":
              if (!doubleQuote) {
                read();
                return newToken("string", buffer);
              }
              buffer += read();
              return;
            case "\n":
            case "\r":
              throw invalidChar(read());
            case "\u2028":
            case "\u2029":
              separatorChar(c);
              break;
            case void 0:
              throw invalidChar(read());
          }
          buffer += read();
        },
        start() {
          switch (c) {
            case "{":
            case "[":
              return newToken("punctuator", read());
          }
          lexState = "value";
        },
        beforePropertyName() {
          switch (c) {
            case "$":
            case "_":
              buffer = read();
              lexState = "identifierName";
              return;
            case "\\":
              read();
              lexState = "identifierNameStartEscape";
              return;
            case "}":
              return newToken("punctuator", read());
            case '"':
            case "'":
              doubleQuote = read() === '"';
              lexState = "string";
              return;
          }
          if (util2.isIdStartChar(c)) {
            buffer += read();
            lexState = "identifierName";
            return;
          }
          throw invalidChar(read());
        },
        afterPropertyName() {
          if (c === ":") {
            return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        beforePropertyValue() {
          lexState = "value";
        },
        afterPropertyValue() {
          switch (c) {
            case ",":
            case "}":
              return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        beforeArrayValue() {
          if (c === "]") {
            return newToken("punctuator", read());
          }
          lexState = "value";
        },
        afterArrayValue() {
          switch (c) {
            case ",":
            case "]":
              return newToken("punctuator", read());
          }
          throw invalidChar(read());
        },
        end() {
          throw invalidChar(read());
        }
      };
      function newToken(type, value) {
        return {
          type,
          value,
          line,
          column: column9
        };
      }
      function literal(s2) {
        for (const c2 of s2) {
          const p = peek();
          if (p !== c2) {
            throw invalidChar(read());
          }
          read();
        }
      }
      function escape2() {
        const c2 = peek();
        switch (c2) {
          case "b":
            read();
            return "\b";
          case "f":
            read();
            return "\f";
          case "n":
            read();
            return "\n";
          case "r":
            read();
            return "\r";
          case "t":
            read();
            return "	";
          case "v":
            read();
            return "\v";
          case "0":
            read();
            if (util2.isDigit(peek())) {
              throw invalidChar(read());
            }
            return "\0";
          case "x":
            read();
            return hexEscape();
          case "u":
            read();
            return unicodeEscape();
          case "\n":
          case "\u2028":
          case "\u2029":
            read();
            return "";
          case "\r":
            read();
            if (peek() === "\n") {
              read();
            }
            return "";
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            throw invalidChar(read());
          case void 0:
            throw invalidChar(read());
        }
        return read();
      }
      function hexEscape() {
        let buffer2 = "";
        let c2 = peek();
        if (!util2.isHexDigit(c2)) {
          throw invalidChar(read());
        }
        buffer2 += read();
        c2 = peek();
        if (!util2.isHexDigit(c2)) {
          throw invalidChar(read());
        }
        buffer2 += read();
        return String.fromCodePoint(parseInt(buffer2, 16));
      }
      function unicodeEscape() {
        let buffer2 = "";
        let count = 4;
        while (count-- > 0) {
          const c2 = peek();
          if (!util2.isHexDigit(c2)) {
            throw invalidChar(read());
          }
          buffer2 += read();
        }
        return String.fromCodePoint(parseInt(buffer2, 16));
      }
      var parseStates = {
        start() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          push2();
        },
        beforePropertyName() {
          switch (token.type) {
            case "identifier":
            case "string":
              key = token.value;
              parseState = "afterPropertyName";
              return;
            case "punctuator":
              pop();
              return;
            case "eof":
              throw invalidEOF();
          }
        },
        afterPropertyName() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          parseState = "beforePropertyValue";
        },
        beforePropertyValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          push2();
        },
        beforeArrayValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          if (token.type === "punctuator" && token.value === "]") {
            pop();
            return;
          }
          push2();
        },
        afterPropertyValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          switch (token.value) {
            case ",":
              parseState = "beforePropertyName";
              return;
            case "}":
              pop();
          }
        },
        afterArrayValue() {
          if (token.type === "eof") {
            throw invalidEOF();
          }
          switch (token.value) {
            case ",":
              parseState = "beforeArrayValue";
              return;
            case "]":
              pop();
          }
        },
        end() {
        }
      };
      function push2() {
        let value;
        switch (token.type) {
          case "punctuator":
            switch (token.value) {
              case "{":
                value = {};
                break;
              case "[":
                value = [];
                break;
            }
            break;
          case "null":
          case "boolean":
          case "numeric":
          case "string":
            value = token.value;
            break;
        }
        if (root === void 0) {
          root = value;
        } else {
          const parent = stack[stack.length - 1];
          if (Array.isArray(parent)) {
            parent.push(value);
          } else {
            Object.defineProperty(parent, key, {
              value,
              writable: true,
              enumerable: true,
              configurable: true
            });
          }
        }
        if (value !== null && typeof value === "object") {
          stack.push(value);
          if (Array.isArray(value)) {
            parseState = "beforeArrayValue";
          } else {
            parseState = "beforePropertyName";
          }
        } else {
          const current = stack[stack.length - 1];
          if (current == null) {
            parseState = "end";
          } else if (Array.isArray(current)) {
            parseState = "afterArrayValue";
          } else {
            parseState = "afterPropertyValue";
          }
        }
      }
      function pop() {
        stack.pop();
        const current = stack[stack.length - 1];
        if (current == null) {
          parseState = "end";
        } else if (Array.isArray(current)) {
          parseState = "afterArrayValue";
        } else {
          parseState = "afterPropertyValue";
        }
      }
      function invalidChar(c2) {
        if (c2 === void 0) {
          return syntaxError(`JSON5: invalid end of input at ${line}:${column9}`);
        }
        return syntaxError(`JSON5: invalid character '${formatChar(c2)}' at ${line}:${column9}`);
      }
      function invalidEOF() {
        return syntaxError(`JSON5: invalid end of input at ${line}:${column9}`);
      }
      function invalidIdentifier() {
        column9 -= 5;
        return syntaxError(`JSON5: invalid identifier character at ${line}:${column9}`);
      }
      function separatorChar(c2) {
        console.warn(`JSON5: '${formatChar(c2)}' in strings is not valid ECMAScript; consider escaping`);
      }
      function formatChar(c2) {
        const replacements = {
          "'": "\\'",
          '"': '\\"',
          "\\": "\\\\",
          "\b": "\\b",
          "\f": "\\f",
          "\n": "\\n",
          "\r": "\\r",
          "	": "\\t",
          "\v": "\\v",
          "\0": "\\0",
          "\u2028": "\\u2028",
          "\u2029": "\\u2029"
        };
        if (replacements[c2]) {
          return replacements[c2];
        }
        if (c2 < " ") {
          const hexString = c2.charCodeAt(0).toString(16);
          return "\\x" + ("00" + hexString).substring(hexString.length);
        }
        return c2;
      }
      function syntaxError(message) {
        const err2 = new SyntaxError(message);
        err2.lineNumber = line;
        err2.columnNumber = column9;
        return err2;
      }
    });
    var require_stringify = __commonJS3((exports3, module22) => {
      var util2 = require_util22();
      module22.exports = function stringify3(value, replacer, space) {
        const stack = [];
        let indent = "";
        let propertyList;
        let replacerFunc;
        let gap = "";
        let quote;
        if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
          space = replacer.space;
          quote = replacer.quote;
          replacer = replacer.replacer;
        }
        if (typeof replacer === "function") {
          replacerFunc = replacer;
        } else if (Array.isArray(replacer)) {
          propertyList = [];
          for (const v of replacer) {
            let item;
            if (typeof v === "string") {
              item = v;
            } else if (typeof v === "number" || v instanceof String || v instanceof Number) {
              item = String(v);
            }
            if (item !== void 0 && propertyList.indexOf(item) < 0) {
              propertyList.push(item);
            }
          }
        }
        if (space instanceof Number) {
          space = Number(space);
        } else if (space instanceof String) {
          space = String(space);
        }
        if (typeof space === "number") {
          if (space > 0) {
            space = Math.min(10, Math.floor(space));
            gap = "          ".substr(0, space);
          }
        } else if (typeof space === "string") {
          gap = space.substr(0, 10);
        }
        return serializeProperty("", { "": value });
        function serializeProperty(key, holder) {
          let value2 = holder[key];
          if (value2 != null) {
            if (typeof value2.toJSON5 === "function") {
              value2 = value2.toJSON5(key);
            } else if (typeof value2.toJSON === "function") {
              value2 = value2.toJSON(key);
            }
          }
          if (replacerFunc) {
            value2 = replacerFunc.call(holder, key, value2);
          }
          if (value2 instanceof Number) {
            value2 = Number(value2);
          } else if (value2 instanceof String) {
            value2 = String(value2);
          } else if (value2 instanceof Boolean) {
            value2 = value2.valueOf();
          }
          switch (value2) {
            case null:
              return "null";
            case true:
              return "true";
            case false:
              return "false";
          }
          if (typeof value2 === "string") {
            return quoteString(value2, false);
          }
          if (typeof value2 === "number") {
            return String(value2);
          }
          if (typeof value2 === "object") {
            return Array.isArray(value2) ? serializeArray(value2) : serializeObject(value2);
          }
          return void 0;
        }
        function quoteString(value2) {
          const quotes = {
            "'": 0.1,
            '"': 0.2
          };
          const replacements = {
            "'": "\\'",
            '"': '\\"',
            "\\": "\\\\",
            "\b": "\\b",
            "\f": "\\f",
            "\n": "\\n",
            "\r": "\\r",
            "	": "\\t",
            "\v": "\\v",
            "\0": "\\0",
            "\u2028": "\\u2028",
            "\u2029": "\\u2029"
          };
          let product = "";
          for (let i2 = 0; i2 < value2.length; i2++) {
            const c = value2[i2];
            switch (c) {
              case "'":
              case '"':
                quotes[c]++;
                product += c;
                continue;
              case "\0":
                if (util2.isDigit(value2[i2 + 1])) {
                  product += "\\x00";
                  continue;
                }
            }
            if (replacements[c]) {
              product += replacements[c];
              continue;
            }
            if (c < " ") {
              let hexString = c.charCodeAt(0).toString(16);
              product += "\\x" + ("00" + hexString).substring(hexString.length);
              continue;
            }
            product += c;
          }
          const quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b);
          product = product.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]);
          return quoteChar + product + quoteChar;
        }
        function serializeObject(value2) {
          if (stack.indexOf(value2) >= 0) {
            throw TypeError("Converting circular structure to JSON5");
          }
          stack.push(value2);
          let stepback = indent;
          indent = indent + gap;
          let keys = propertyList || Object.keys(value2);
          let partial = [];
          for (const key of keys) {
            const propertyString = serializeProperty(key, value2);
            if (propertyString !== void 0) {
              let member = serializeKey(key) + ":";
              if (gap !== "") {
                member += " ";
              }
              member += propertyString;
              partial.push(member);
            }
          }
          let final;
          if (partial.length === 0) {
            final = "{}";
          } else {
            let properties;
            if (gap === "") {
              properties = partial.join(",");
              final = "{" + properties + "}";
            } else {
              let separator = ",\n" + indent;
              properties = partial.join(separator);
              final = "{\n" + indent + properties + ",\n" + stepback + "}";
            }
          }
          stack.pop();
          indent = stepback;
          return final;
        }
        function serializeKey(key) {
          if (key.length === 0) {
            return quoteString(key, true);
          }
          const firstChar = String.fromCodePoint(key.codePointAt(0));
          if (!util2.isIdStartChar(firstChar)) {
            return quoteString(key, true);
          }
          for (let i2 = firstChar.length; i2 < key.length; i2++) {
            if (!util2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i2)))) {
              return quoteString(key, true);
            }
          }
          return key;
        }
        function serializeArray(value2) {
          if (stack.indexOf(value2) >= 0) {
            throw TypeError("Converting circular structure to JSON5");
          }
          stack.push(value2);
          let stepback = indent;
          indent = indent + gap;
          let partial = [];
          for (let i2 = 0; i2 < value2.length; i2++) {
            const propertyString = serializeProperty(String(i2), value2);
            partial.push(propertyString !== void 0 ? propertyString : "null");
          }
          let final;
          if (partial.length === 0) {
            final = "[]";
          } else {
            if (gap === "") {
              let properties = partial.join(",");
              final = "[" + properties + "]";
            } else {
              let separator = ",\n" + indent;
              let properties = partial.join(separator);
              final = "[\n" + indent + properties + ",\n" + stepback + "]";
            }
          }
          stack.pop();
          indent = stepback;
          return final;
        }
      };
    });
    var require_lib3 = __commonJS3((exports3, module22) => {
      var parse5 = require_parse3();
      var stringify3 = require_stringify();
      var JSON5 = {
        parse: parse5,
        stringify: stringify3
      };
      module22.exports = JSON5;
    });
    var require_strip_bom = __commonJS3((exports3, module22) => {
      "use strict";
      module22.exports = (x2) => {
        if (typeof x2 !== "string") {
          throw new TypeError("Expected a string, got " + typeof x2);
        }
        if (x2.charCodeAt(0) === 65279) {
          return x2.slice(1);
        }
        return x2;
      };
    });
    var require_tsconfig_loader = __commonJS3((exports3) => {
      "use strict";
      var __assign3 = exports3 && exports3.__assign || function() {
        __assign3 = Object.assign || function(t2) {
          for (var s2, i2 = 1, n = arguments.length; i2 < n; i2++) {
            s2 = arguments[i2];
            for (var p in s2)
              if (Object.prototype.hasOwnProperty.call(s2, p))
                t2[p] = s2[p];
          }
          return t2;
        };
        return __assign3.apply(this, arguments);
      };
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.loadTsconfig = exports3.walkForTsConfig = exports3.tsConfigLoader = void 0;
      var path4 = require("path");
      var fs32 = require("fs");
      var JSON5 = require_lib3();
      var StripBom = require_strip_bom();
      function tsConfigLoader(_a) {
        var getEnv = _a.getEnv, cwd = _a.cwd, _b = _a.loadSync, loadSync = _b === void 0 ? loadSyncDefault : _b;
        var TS_NODE_PROJECT = getEnv("TS_NODE_PROJECT");
        var TS_NODE_BASEURL = getEnv("TS_NODE_BASEURL");
        var loadResult = loadSync(cwd, TS_NODE_PROJECT, TS_NODE_BASEURL);
        return loadResult;
      }
      exports3.tsConfigLoader = tsConfigLoader;
      function loadSyncDefault(cwd, filename, baseUrl) {
        var configPath = resolveConfigPath(cwd, filename);
        if (!configPath) {
          return {
            tsConfigPath: void 0,
            baseUrl: void 0,
            paths: void 0
          };
        }
        var config = loadTsconfig(configPath);
        return {
          tsConfigPath: configPath,
          baseUrl: baseUrl || config && config.compilerOptions && config.compilerOptions.baseUrl,
          paths: config && config.compilerOptions && config.compilerOptions.paths
        };
      }
      function resolveConfigPath(cwd, filename) {
        if (filename) {
          var absolutePath = fs32.lstatSync(filename).isDirectory() ? path4.resolve(filename, "./tsconfig.json") : path4.resolve(cwd, filename);
          return absolutePath;
        }
        if (fs32.statSync(cwd).isFile()) {
          return path4.resolve(cwd);
        }
        var configAbsolutePath = walkForTsConfig(cwd);
        return configAbsolutePath ? path4.resolve(configAbsolutePath) : void 0;
      }
      function walkForTsConfig(directory, readdirSync2) {
        if (readdirSync2 === void 0) {
          readdirSync2 = fs32.readdirSync;
        }
        var files = readdirSync2(directory);
        var filesToCheck = ["tsconfig.json", "jsconfig.json"];
        for (var _i = 0, filesToCheck_1 = filesToCheck; _i < filesToCheck_1.length; _i++) {
          var fileToCheck = filesToCheck_1[_i];
          if (files.indexOf(fileToCheck) !== -1) {
            return path4.join(directory, fileToCheck);
          }
        }
        var parentDirectory = path4.dirname(directory);
        if (directory === parentDirectory) {
          return void 0;
        }
        return walkForTsConfig(parentDirectory, readdirSync2);
      }
      exports3.walkForTsConfig = walkForTsConfig;
      function loadTsconfig(configFilePath, existsSync3, readFileSync3) {
        if (existsSync3 === void 0) {
          existsSync3 = fs32.existsSync;
        }
        if (readFileSync3 === void 0) {
          readFileSync3 = function(filename) {
            return fs32.readFileSync(filename, "utf8");
          };
        }
        if (!existsSync3(configFilePath)) {
          return void 0;
        }
        var configString = readFileSync3(configFilePath);
        var cleanedJson = StripBom(configString);
        var config;
        try {
          config = JSON5.parse(cleanedJson);
        } catch (e2) {
          throw new Error("".concat(configFilePath, " is malformed ").concat(e2.message));
        }
        var extendedConfig = config.extends;
        if (extendedConfig) {
          var base = void 0;
          if (Array.isArray(extendedConfig)) {
            base = extendedConfig.reduce(function(currBase, extendedConfigElement) {
              return mergeTsconfigs(currBase, loadTsconfigFromExtends(configFilePath, extendedConfigElement, existsSync3, readFileSync3));
            }, {});
          } else {
            base = loadTsconfigFromExtends(configFilePath, extendedConfig, existsSync3, readFileSync3);
          }
          return mergeTsconfigs(base, config);
        }
        return config;
      }
      exports3.loadTsconfig = loadTsconfig;
      function loadTsconfigFromExtends(configFilePath, extendedConfigValue, existsSync3, readFileSync3) {
        var _a;
        if (typeof extendedConfigValue === "string" && extendedConfigValue.indexOf(".json") === -1) {
          extendedConfigValue += ".json";
        }
        var currentDir = path4.dirname(configFilePath);
        var extendedConfigPath = path4.join(currentDir, extendedConfigValue);
        if (extendedConfigValue.indexOf("/") !== -1 && extendedConfigValue.indexOf(".") !== -1 && !existsSync3(extendedConfigPath)) {
          extendedConfigPath = path4.join(currentDir, "node_modules", extendedConfigValue);
        }
        var config = loadTsconfig(extendedConfigPath, existsSync3, readFileSync3) || {};
        if ((_a = config.compilerOptions) === null || _a === void 0 ? void 0 : _a.baseUrl) {
          var extendsDir = path4.dirname(extendedConfigValue);
          config.compilerOptions.baseUrl = path4.join(extendsDir, config.compilerOptions.baseUrl);
        }
        return config;
      }
      function mergeTsconfigs(base, config) {
        base = base || {};
        config = config || {};
        return __assign3(__assign3(__assign3({}, base), config), { compilerOptions: __assign3(__assign3({}, base.compilerOptions), config.compilerOptions) });
      }
    });
    var require_config_loader = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.configLoader = exports3.loadConfig = void 0;
      var TsConfigLoader2 = require_tsconfig_loader();
      var path4 = require("path");
      function loadConfig2(cwd) {
        if (cwd === void 0) {
          cwd = process.cwd();
        }
        return configLoader({ cwd });
      }
      exports3.loadConfig = loadConfig2;
      function configLoader(_a) {
        var cwd = _a.cwd, explicitParams = _a.explicitParams, _b = _a.tsConfigLoader, tsConfigLoader = _b === void 0 ? TsConfigLoader2.tsConfigLoader : _b;
        if (explicitParams) {
          var absoluteBaseUrl = path4.isAbsolute(explicitParams.baseUrl) ? explicitParams.baseUrl : path4.join(cwd, explicitParams.baseUrl);
          return {
            resultType: "success",
            configFileAbsolutePath: "",
            baseUrl: explicitParams.baseUrl,
            absoluteBaseUrl,
            paths: explicitParams.paths,
            mainFields: explicitParams.mainFields,
            addMatchAll: explicitParams.addMatchAll
          };
        }
        var loadResult = tsConfigLoader({
          cwd,
          getEnv: function(key) {
            return process.env[key];
          }
        });
        if (!loadResult.tsConfigPath) {
          return {
            resultType: "failed",
            message: "Couldn't find tsconfig.json"
          };
        }
        return {
          resultType: "success",
          configFileAbsolutePath: loadResult.tsConfigPath,
          baseUrl: loadResult.baseUrl,
          absoluteBaseUrl: path4.resolve(path4.dirname(loadResult.tsConfigPath), loadResult.baseUrl || ""),
          paths: loadResult.paths || {},
          addMatchAll: loadResult.baseUrl !== void 0
        };
      }
      exports3.configLoader = configLoader;
    });
    var require_minimist = __commonJS3((exports3, module22) => {
      "use strict";
      function hasKey(obj, keys) {
        var o = obj;
        keys.slice(0, -1).forEach(function(key2) {
          o = o[key2] || {};
        });
        var key = keys[keys.length - 1];
        return key in o;
      }
      function isNumber2(x2) {
        if (typeof x2 === "number") {
          return true;
        }
        if (/^0x[0-9a-f]+$/i.test(x2)) {
          return true;
        }
        return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x2);
      }
      function isConstructorOrProto(obj, key) {
        return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
      }
      module22.exports = function(args, opts) {
        if (!opts) {
          opts = {};
        }
        var flags = {
          bools: {},
          strings: {},
          unknownFn: null
        };
        if (typeof opts.unknown === "function") {
          flags.unknownFn = opts.unknown;
        }
        if (typeof opts.boolean === "boolean" && opts.boolean) {
          flags.allBools = true;
        } else {
          [].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
            flags.bools[key2] = true;
          });
        }
        var aliases = {};
        function aliasIsBoolean(key2) {
          return aliases[key2].some(function(x2) {
            return flags.bools[x2];
          });
        }
        Object.keys(opts.alias || {}).forEach(function(key2) {
          aliases[key2] = [].concat(opts.alias[key2]);
          aliases[key2].forEach(function(x2) {
            aliases[x2] = [key2].concat(aliases[key2].filter(function(y) {
              return x2 !== y;
            }));
          });
        });
        [].concat(opts.string).filter(Boolean).forEach(function(key2) {
          flags.strings[key2] = true;
          if (aliases[key2]) {
            [].concat(aliases[key2]).forEach(function(k) {
              flags.strings[k] = true;
            });
          }
        });
        var defaults2 = opts.default || {};
        var argv = { _: [] };
        function argDefined(key2, arg2) {
          return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
        }
        function setKey(obj, keys, value2) {
          var o = obj;
          for (var i22 = 0; i22 < keys.length - 1; i22++) {
            var key2 = keys[i22];
            if (isConstructorOrProto(o, key2)) {
              return;
            }
            if (o[key2] === void 0) {
              o[key2] = {};
            }
            if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype) {
              o[key2] = {};
            }
            if (o[key2] === Array.prototype) {
              o[key2] = [];
            }
            o = o[key2];
          }
          var lastKey = keys[keys.length - 1];
          if (isConstructorOrProto(o, lastKey)) {
            return;
          }
          if (o === Object.prototype || o === Number.prototype || o === String.prototype) {
            o = {};
          }
          if (o === Array.prototype) {
            o = [];
          }
          if (o[lastKey] === void 0 || flags.bools[lastKey] || typeof o[lastKey] === "boolean") {
            o[lastKey] = value2;
          } else if (Array.isArray(o[lastKey])) {
            o[lastKey].push(value2);
          } else {
            o[lastKey] = [o[lastKey], value2];
          }
        }
        function setArg(key2, val2, arg2) {
          if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
            if (flags.unknownFn(arg2) === false) {
              return;
            }
          }
          var value2 = !flags.strings[key2] && isNumber2(val2) ? Number(val2) : val2;
          setKey(argv, key2.split("."), value2);
          (aliases[key2] || []).forEach(function(x2) {
            setKey(argv, x2.split("."), value2);
          });
        }
        Object.keys(flags.bools).forEach(function(key2) {
          setArg(key2, defaults2[key2] === void 0 ? false : defaults2[key2]);
        });
        var notFlags = [];
        if (args.indexOf("--") !== -1) {
          notFlags = args.slice(args.indexOf("--") + 1);
          args = args.slice(0, args.indexOf("--"));
        }
        for (var i2 = 0; i2 < args.length; i2++) {
          var arg = args[i2];
          var key;
          var next;
          if (/^--.+=/.test(arg)) {
            var m2 = arg.match(/^--([^=]+)=([\s\S]*)$/);
            key = m2[1];
            var value = m2[2];
            if (flags.bools[key]) {
              value = value !== "false";
            }
            setArg(key, value, arg);
          } else if (/^--no-.+/.test(arg)) {
            key = arg.match(/^--no-(.+)/)[1];
            setArg(key, false, arg);
          } else if (/^--.+/.test(arg)) {
            key = arg.match(/^--(.+)/)[1];
            next = args[i2 + 1];
            if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, next, arg);
              i2 += 1;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next === "true", arg);
              i2 += 1;
            } else {
              setArg(key, flags.strings[key] ? "" : true, arg);
            }
          } else if (/^-[^-]+/.test(arg)) {
            var letters = arg.slice(1, -1).split("");
            var broken = false;
            for (var j = 0; j < letters.length; j++) {
              next = arg.slice(j + 2);
              if (next === "-") {
                setArg(letters[j], next, arg);
                continue;
              }
              if (/[A-Za-z]/.test(letters[j]) && next[0] === "=") {
                setArg(letters[j], next.slice(1), arg);
                broken = true;
                break;
              }
              if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                setArg(letters[j], next, arg);
                broken = true;
                break;
              }
              if (letters[j + 1] && letters[j + 1].match(/\W/)) {
                setArg(letters[j], arg.slice(j + 2), arg);
                broken = true;
                break;
              } else {
                setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
              }
            }
            key = arg.slice(-1)[0];
            if (!broken && key !== "-") {
              if (args[i2 + 1] && !/^(-|--)[^-]/.test(args[i2 + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
                setArg(key, args[i2 + 1], arg);
                i2 += 1;
              } else if (args[i2 + 1] && /^(true|false)$/.test(args[i2 + 1])) {
                setArg(key, args[i2 + 1] === "true", arg);
                i2 += 1;
              } else {
                setArg(key, flags.strings[key] ? "" : true, arg);
              }
            }
          } else {
            if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
              argv._.push(flags.strings._ || !isNumber2(arg) ? arg : Number(arg));
            }
            if (opts.stopEarly) {
              argv._.push.apply(argv._, args.slice(i2 + 1));
              break;
            }
          }
        }
        Object.keys(defaults2).forEach(function(k) {
          if (!hasKey(argv, k.split("."))) {
            setKey(argv, k.split("."), defaults2[k]);
            (aliases[k] || []).forEach(function(x2) {
              setKey(argv, x2.split("."), defaults2[k]);
            });
          }
        });
        if (opts["--"]) {
          argv["--"] = notFlags.slice();
        } else {
          notFlags.forEach(function(k) {
            argv._.push(k);
          });
        }
        return argv;
      };
    });
    var require_register = __commonJS3((exports3) => {
      "use strict";
      var __spreadArray3 = exports3 && exports3.__spreadArray || function(to, from, pack) {
        if (pack || arguments.length === 2)
          for (var i2 = 0, l = from.length, ar; i2 < l; i2++) {
            if (ar || !(i2 in from)) {
              if (!ar)
                ar = Array.prototype.slice.call(from, 0, i2);
              ar[i2] = from[i2];
            }
          }
        return to.concat(ar || Array.prototype.slice.call(from));
      };
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.register = void 0;
      var match_path_sync_1 = require_match_path_sync();
      var config_loader_1 = require_config_loader();
      var noOp2 = function() {
        return void 0;
      };
      function getCoreModules(builtinModules2) {
        builtinModules2 = builtinModules2 || [
          "assert",
          "buffer",
          "child_process",
          "cluster",
          "crypto",
          "dgram",
          "dns",
          "domain",
          "events",
          "fs",
          "http",
          "https",
          "net",
          "os",
          "path",
          "punycode",
          "querystring",
          "readline",
          "stream",
          "string_decoder",
          "tls",
          "tty",
          "url",
          "util",
          "v8",
          "vm",
          "zlib"
        ];
        var coreModules = {};
        for (var _i = 0, builtinModules_1 = builtinModules2; _i < builtinModules_1.length; _i++) {
          var module_1 = builtinModules_1[_i];
          coreModules[module_1] = true;
        }
        return coreModules;
      }
      function register2(params) {
        var cwd;
        var explicitParams;
        if (params) {
          cwd = params.cwd;
          if (params.baseUrl || params.paths) {
            explicitParams = params;
          }
        } else {
          var minimist = require_minimist();
          var argv = minimist(process.argv.slice(2), {
            string: ["project"],
            alias: {
              project: ["P"]
            }
          });
          cwd = argv.project;
        }
        var configLoaderResult = (0, config_loader_1.configLoader)({
          cwd: cwd !== null && cwd !== void 0 ? cwd : process.cwd(),
          explicitParams
        });
        if (configLoaderResult.resultType === "failed") {
          console.warn("".concat(configLoaderResult.message, ". tsconfig-paths will be skipped"));
          return noOp2;
        }
        var matchPath = (0, match_path_sync_1.createMatchPath)(configLoaderResult.absoluteBaseUrl, configLoaderResult.paths, configLoaderResult.mainFields, configLoaderResult.addMatchAll);
        var Module = require("module");
        var originalResolveFilename = Module._resolveFilename;
        var coreModules = getCoreModules(Module.builtinModules);
        Module._resolveFilename = function(request, _parent) {
          var isCoreModule = coreModules.hasOwnProperty(request);
          if (!isCoreModule) {
            var found = matchPath(request);
            if (found) {
              var modifiedArguments = __spreadArray3([found], [].slice.call(arguments, 1), true);
              return originalResolveFilename.apply(this, modifiedArguments);
            }
          }
          return originalResolveFilename.apply(this, arguments);
        };
        return function() {
          Module._resolveFilename = originalResolveFilename;
        };
      }
      exports3.register = register2;
    });
    var require_lib4 = __commonJS3((exports3) => {
      "use strict";
      Object.defineProperty(exports3, "__esModule", { value: true });
      exports3.loadConfig = exports3.register = exports3.matchFromAbsolutePathsAsync = exports3.createMatchPathAsync = exports3.matchFromAbsolutePaths = exports3.createMatchPath = void 0;
      var match_path_sync_1 = require_match_path_sync();
      Object.defineProperty(exports3, "createMatchPath", { enumerable: true, get: function() {
        return match_path_sync_1.createMatchPath;
      } });
      Object.defineProperty(exports3, "matchFromAbsolutePaths", { enumerable: true, get: function() {
        return match_path_sync_1.matchFromAbsolutePaths;
      } });
      var match_path_async_1 = require_match_path_async();
      Object.defineProperty(exports3, "createMatchPathAsync", { enumerable: true, get: function() {
        return match_path_async_1.createMatchPathAsync;
      } });
      Object.defineProperty(exports3, "matchFromAbsolutePathsAsync", { enumerable: true, get: function() {
        return match_path_async_1.matchFromAbsolutePathsAsync;
      } });
      var register_1 = require_register();
      Object.defineProperty(exports3, "register", { enumerable: true, get: function() {
        return register_1.register;
      } });
      var config_loader_1 = require_config_loader();
      Object.defineProperty(exports3, "loadConfig", { enumerable: true, get: function() {
        return config_loader_1.loadConfig;
      } });
    });
    var import_source_map_support = __toModule(require_source_map_support());
    var import_pirates = __toModule(require_lib2());
    var _path2 = require("path");
    var _esbuild = require("esbuild");
    var _fs2 = require("fs");
    var _fs3 = _interopRequireDefault2(_fs2);
    var _module2 = require("module");
    var _module3 = _interopRequireDefault2(_module2);
    var _process = require("process");
    var _process2 = _interopRequireDefault2(_process);
    var import_joycon = __toModule(require_lib22());
    var singleComment = Symbol("singleComment");
    var multiComment = Symbol("multiComment");
    var stripWithoutWhitespace = () => "";
    var stripWithWhitespace = (string2, start, end) => string2.slice(start, end).replace(/\S/g, " ");
    var isEscaped = (jsonString, quotePosition) => {
      let index5 = quotePosition - 1;
      let backslashCount = 0;
      while (jsonString[index5] === "\\") {
        index5 -= 1;
        backslashCount += 1;
      }
      return Boolean(backslashCount % 2);
    };
    function stripJsonComments(jsonString, { whitespace = true } = {}) {
      if (typeof jsonString !== "string") {
        throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
      }
      const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace;
      let isInsideString = false;
      let isInsideComment = false;
      let offset = 0;
      let result = "";
      for (let index5 = 0; index5 < jsonString.length; index5++) {
        const currentCharacter = jsonString[index5];
        const nextCharacter = jsonString[index5 + 1];
        if (!isInsideComment && currentCharacter === '"') {
          const escaped = isEscaped(jsonString, index5);
          if (!escaped) {
            isInsideString = !isInsideString;
          }
        }
        if (isInsideString) {
          continue;
        }
        if (!isInsideComment && currentCharacter + nextCharacter === "//") {
          result += jsonString.slice(offset, index5);
          offset = index5;
          isInsideComment = singleComment;
          index5++;
        } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
          index5++;
          isInsideComment = false;
          result += strip(jsonString, offset, index5);
          offset = index5;
          continue;
        } else if (isInsideComment === singleComment && currentCharacter === "\n") {
          isInsideComment = false;
          result += strip(jsonString, offset, index5);
          offset = index5;
        } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
          result += jsonString.slice(offset, index5);
          offset = index5;
          isInsideComment = multiComment;
          index5++;
          continue;
        } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
          index5++;
          isInsideComment = false;
          result += strip(jsonString, offset, index5 + 1);
          offset = index5 + 1;
          continue;
        }
      }
      return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
    }
    var nodeVersion = (process.versions.node.match(/^(\d+)\.(\d+)/) || []).slice(1).map(Number);
    function removeNodePrefix(code) {
      if (nodeVersion[0] <= 14 && nodeVersion[1] < 18) {
        return code.replace(/([\b\(])require\("node:([^"]+)"\)([\b\)])/g, '$1require("$2")$3');
      }
      return code;
    }
    function jsoncParse(data) {
      try {
        return new Function("return " + stripJsonComments(data).trim())();
      } catch (_2) {
        return {};
      }
    }
    var joycon = new import_joycon.default();
    joycon.addLoader({
      test: /\.json$/,
      loadSync: (file) => {
        const content = _fs3.default.readFileSync(file, "utf8");
        return jsoncParse(content);
      }
    });
    var getOptions = (cwd) => {
      var _a, _b, _c, _d;
      const { data, path: path4 } = joycon.loadSync(["tsconfig.json", "jsconfig.json"], cwd);
      if (path4 && data) {
        return {
          jsxFactory: (_a = data.compilerOptions) == null ? void 0 : _a.jsxFactory,
          jsxFragment: (_b = data.compilerOptions) == null ? void 0 : _b.jsxFragmentFactory,
          target: (_d = (_c = data.compilerOptions) == null ? void 0 : _c.target) == null ? void 0 : _d.toLowerCase()
        };
      }
      return {};
    };
    var inferPackageFormat = (cwd, filename) => {
      if (filename.endsWith(".mjs")) {
        return "esm";
      }
      if (filename.endsWith(".cjs")) {
        return "cjs";
      }
      const { data } = joycon.loadSync(["package.json"], cwd);
      return data && data.type === "module" && /\.m?js$/.test(filename) ? "esm" : "cjs";
    };
    var import_tsconfig_paths = __toModule(require_lib4());
    var noOp = () => {
    };
    function registerTsconfigPaths() {
      const configLoaderResult = (0, import_tsconfig_paths.loadConfig)(process.cwd());
      if (configLoaderResult.resultType === "failed") {
        return noOp;
      }
      const matchPath = (0, import_tsconfig_paths.createMatchPath)(configLoaderResult.absoluteBaseUrl, configLoaderResult.paths, configLoaderResult.mainFields, configLoaderResult.addMatchAll);
      const Module = require("module");
      const originalResolveFilename = Module._resolveFilename;
      Module._resolveFilename = function(request, _parent) {
        const isCoreModule = _module2.builtinModules.includes(request);
        if (!isCoreModule) {
          const found = matchPath(request);
          if (found) {
            const modifiedArguments = [found, ...[].slice.call(arguments, 1)];
            return originalResolveFilename.apply(this, modifiedArguments);
          }
        }
        return originalResolveFilename.apply(this, arguments);
      };
      return () => {
        Module._resolveFilename = originalResolveFilename;
      };
    }
    var _debug = require_src2();
    var _debug2 = _interopRequireDefault2(_debug);
    var debug = _debug2.default.call(void 0, "esbuild-register");
    var IMPORT_META_URL_VARIABLE_NAME = "__esbuild_register_import_meta_url__";
    var map = {};
    function installSourceMapSupport() {
      if (_process2.default.setSourceMapsEnabled) {
        ;
        _process2.default.setSourceMapsEnabled(true);
      } else {
        import_source_map_support.default.install({
          handleUncaughtExceptions: false,
          environment: "node",
          retrieveSourceMap(file) {
            if (map[file]) {
              return {
                url: file,
                map: map[file]
              };
            }
            return null;
          }
        });
      }
    }
    function patchCommonJsLoader(compile) {
      const extensions = _module3.default.Module._extensions;
      const jsHandler = extensions[".js"];
      extensions[".js"] = function(module22, filename) {
        try {
          return jsHandler.call(this, module22, filename);
        } catch (error2) {
          if (error2.code !== "ERR_REQUIRE_ESM") {
            throw error2;
          }
          let content = _fs3.default.readFileSync(filename, "utf8");
          content = compile(content, filename, "cjs");
          module22._compile(content, filename);
        }
      };
      return () => {
        extensions[".js"] = jsHandler;
      };
    }
    var FILE_LOADERS = {
      ".js": "js",
      ".jsx": "jsx",
      ".ts": "ts",
      ".tsx": "tsx",
      ".mjs": "js",
      ".mts": "ts",
      ".cts": "ts"
    };
    var DEFAULT_EXTENSIONS = Object.keys(FILE_LOADERS);
    var getLoader = (filename) => FILE_LOADERS[_path2.extname.call(void 0, filename)];
    function register(esbuildOptions = {}) {
      const {
        extensions = DEFAULT_EXTENSIONS,
        hookIgnoreNodeModules = true,
        hookMatcher,
        ...overrides
      } = esbuildOptions;
      const compile = function compile2(code, filename, format) {
        const define2 = {
          "import.meta.url": IMPORT_META_URL_VARIABLE_NAME,
          ...overrides.define
        };
        const banner = `const ${IMPORT_META_URL_VARIABLE_NAME} = require('url').pathToFileURL(__filename).href;${overrides.banner || ""}`;
        if (code.includes(banner)) {
          return code;
        }
        const dir = _path2.dirname.call(void 0, filename);
        const options = getOptions(dir);
        format = format != null ? format : inferPackageFormat(dir, filename);
        const result = _esbuild.transformSync.call(void 0, code, {
          sourcefile: filename,
          loader: getLoader(filename),
          sourcemap: "both",
          target: options.target,
          jsxFactory: options.jsxFactory,
          jsxFragment: options.jsxFragment,
          format,
          define: define2,
          banner,
          ...overrides
        });
        const js = result.code;
        debug("compiled %s", filename);
        debug("%s", js);
        const warnings = result.warnings;
        if (warnings && warnings.length > 0) {
          for (const warning3 of warnings) {
            console.log(warning3.location);
            console.log(warning3.text);
          }
        }
        if (format === "esm")
          return js;
        return removeNodePrefix(js);
      };
      const revert = (0, import_pirates.addHook)(compile, {
        exts: extensions,
        ignoreNodeModules: hookIgnoreNodeModules,
        matcher: hookMatcher
      });
      installSourceMapSupport();
      const unpatchCommonJsLoader = patchCommonJsLoader(compile);
      const unregisterTsconfigPaths = registerTsconfigPaths();
      return {
        unregister() {
          revert();
          unpatchCommonJsLoader();
          unregisterTsconfigPaths();
        }
      };
    }
    exports2.register = register;
  }
});

// src/cli/commands/utils.ts
var import_fs3, import_hanji2, import_path3, assertES5, safeRegister, prepareCheckParams, prepareDropParams, prepareGenerateConfig, prepareExportConfig, flattenDatabaseCredentials, flattenPull, preparePushConfig, preparePullConfig, prepareStudioConfig, migrateConfig, prepareMigrateConfig, drizzleConfigFromFile;
var init_utils3 = __esm({
  "src/cli/commands/utils.ts"() {
    "use strict";
    init_source();
    import_fs3 = require("fs");
    import_hanji2 = __toESM(require_hanji());
    import_path3 = require("path");
    init_lib();
    init_getTablesFilterByExtensions();
    init_global();
    init_schemaValidator();
    init_serializer();
    init_cli();
    init_common();
    init_libsql();
    init_libsql();
    init_mysql();
    init_outputs();
    init_postgres();
    init_singlestore();
    init_sqlite();
    init_studio();
    init_views();
    assertES5 = async (unregister) => {
      try {
        init_es5();
      } catch (e2) {
        if ("errors" in e2 && Array.isArray(e2.errors) && e2.errors.length > 0) {
          const es5Error = e2.errors.filter((it) => {
            var _a;
            return (_a = it.text) == null ? void 0 : _a.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(e2);
        process.exit(1);
      }
    };
    safeRegister = async () => {
      const { register } = await Promise.resolve().then(() => __toESM(require_node2()));
      let res;
      try {
        res = register({
          format: "cjs",
          loader: "ts"
        });
      } catch {
        res = {
          unregister: () => {
          }
        };
      }
      await assertES5(res.unregister);
      return res;
    };
    prepareCheckParams = async (options, from) => {
      const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
      if (!config.out || !config.dialect) {
        let text = `Please provide required params for AWS Data API driver:
`;
        console.log(error(text));
        console.log(wrapParam("database", config.out));
        console.log(wrapParam("secretArn", config.dialect));
        process.exit(1);
      }
      return { out: config.out, dialect: config.dialect };
    };
    prepareDropParams = async (options, from) => {
      const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
      return { out: config.out || "drizzle", bundle: config.driver === "expo" };
    };
    prepareGenerateConfig = async (options, from) => {
      var _a;
      const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
      const { schema: schema6, out, breakpoints, dialect: dialect6, driver: driver2, casing: casing2 } = config;
      if (!schema6 || !dialect6) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("schema", schema6));
        console.log(wrapParam("dialect", dialect6));
        console.log(wrapParam("out", out, true));
        process.exit(1);
      }
      const fileNames = prepareFilenames(schema6);
      if (fileNames.length === 0) {
        (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${schema6} was found`);
        process.exit(0);
      }
      const prefix2 = ("migrations" in config ? (_a = config.migrations) == null ? void 0 : _a.prefix : options.prefix) || "index";
      return {
        dialect: dialect6,
        name: options.name,
        custom: options.custom || false,
        prefix: prefix2,
        breakpoints: breakpoints ?? true,
        schema: schema6,
        out: out || "drizzle",
        bundle: driver2 === "expo" || driver2 === "durable-sqlite",
        casing: casing2,
        driver: driver2
      };
    };
    prepareExportConfig = async (options, from) => {
      const config = from === "config" ? await drizzleConfigFromFile(options.config, true) : options;
      const { schema: schema6, dialect: dialect6, sql } = config;
      if (!schema6 || !dialect6) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("schema", schema6));
        console.log(wrapParam("dialect", dialect6));
        process.exit(1);
      }
      const fileNames = prepareFilenames(schema6);
      if (fileNames.length === 0) {
        (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${schema6} was found`);
        process.exit(0);
      }
      return {
        dialect: dialect6,
        schema: schema6,
        sql
      };
    };
    flattenDatabaseCredentials = (config) => {
      if ("dbCredentials" in config) {
        const { dbCredentials, ...rest } = config;
        return {
          ...rest,
          ...dbCredentials
        };
      }
      return config;
    };
    flattenPull = (config) => {
      if ("dbCredentials" in config) {
        const { dbCredentials, introspect, ...rest } = config;
        return {
          ...rest,
          ...dbCredentials,
          casing: introspect == null ? void 0 : introspect.casing
        };
      }
      return config;
    };
    preparePushConfig = async (options, from) => {
      const raw2 = flattenDatabaseCredentials(
        from === "config" ? await drizzleConfigFromFile(options.config) : options
      );
      raw2.verbose ||= options.verbose;
      raw2.strict ||= options.strict;
      const parsed = pushParams.safeParse(raw2);
      if (parsed.error) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("dialect", raw2.dialect));
        console.log(wrapParam("schema", raw2.schema));
        process.exit(1);
      }
      const config = parsed.data;
      const schemaFiles = prepareFilenames(config.schema);
      if (schemaFiles.length === 0) {
        (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${config.schema} was found`);
        process.exit(0);
      }
      const tablesFilterConfig = config.tablesFilter;
      const tablesFilter = tablesFilterConfig ? typeof tablesFilterConfig === "string" ? [tablesFilterConfig] : tablesFilterConfig : [];
      const schemasFilterConfig = config.schemaFilter;
      const schemasFilter = schemasFilterConfig ? typeof schemasFilterConfig === "string" ? [schemasFilterConfig] : schemasFilterConfig : [];
      tablesFilter.push(...getTablesFilterByExtensions(config));
      if (config.dialect === "postgresql") {
        const parsed2 = postgresCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues3(config);
          process.exit(1);
        }
        return {
          dialect: "postgresql",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter,
          entities: config.entities
        };
      }
      if (config.dialect === "mysql") {
        const parsed2 = mysqlCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues2(config);
          process.exit(1);
        }
        return {
          dialect: "mysql",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter
        };
      }
      if (config.dialect === "singlestore") {
        const parsed2 = singlestoreCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues4(config);
          process.exit(1);
        }
        return {
          dialect: "singlestore",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter
        };
      }
      if (config.dialect === "sqlite") {
        const parsed2 = sqliteCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues5(config, "pull");
          process.exit(1);
        }
        return {
          dialect: "sqlite",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter
        };
      }
      if (config.dialect === "turso") {
        const parsed2 = libSQLCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues5(config, "pull");
          process.exit(1);
        }
        return {
          dialect: "turso",
          schemaPath: config.schema,
          strict: config.strict ?? false,
          verbose: config.verbose ?? false,
          force: options.force ?? false,
          credentials: parsed2.data,
          casing: config.casing,
          tablesFilter,
          schemasFilter
        };
      }
      assertUnreachable(config.dialect);
    };
    preparePullConfig = async (options, from) => {
      var _a, _b, _c, _d, _e;
      const raw2 = flattenPull(
        from === "config" ? await drizzleConfigFromFile(options.config) : options
      );
      const parsed = pullParams.safeParse(raw2);
      if (parsed.error) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("dialect", raw2.dialect));
        process.exit(1);
      }
      const config = parsed.data;
      const dialect6 = config.dialect;
      const tablesFilterConfig = config.tablesFilter;
      const tablesFilter = tablesFilterConfig ? typeof tablesFilterConfig === "string" ? [tablesFilterConfig] : tablesFilterConfig : [];
      if (config.extensionsFilters) {
        if (config.extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
          tablesFilter.push(
            ...["!geography_columns", "!geometry_columns", "!spatial_ref_sys"]
          );
        }
      }
      const schemasFilterConfig = config.schemaFilter;
      const schemasFilter = schemasFilterConfig ? typeof schemasFilterConfig === "string" ? [schemasFilterConfig] : schemasFilterConfig : [];
      if (dialect6 === "postgresql") {
        const parsed2 = postgresCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues3(config);
          process.exit(1);
        }
        return {
          dialect: "postgresql",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "mysql") {
        const parsed2 = mysqlCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues2(config);
          process.exit(1);
        }
        return {
          dialect: "mysql",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "singlestore") {
        const parsed2 = singlestoreCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues4(config);
          process.exit(1);
        }
        return {
          dialect: "singlestore",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "sqlite") {
        const parsed2 = sqliteCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues5(config, "pull");
          process.exit(1);
        }
        return {
          dialect: "sqlite",
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_d = config.migrations) == null ? void 0 : _d.prefix) || "index",
          entities: config.entities
        };
      }
      if (dialect6 === "turso") {
        const parsed2 = libSQLCredentials.safeParse(config);
        if (!parsed2.success) {
          printConfigConnectionIssues(config, "pull");
          process.exit(1);
        }
        return {
          dialect: dialect6,
          out: config.out,
          breakpoints: config.breakpoints,
          casing: config.casing,
          credentials: parsed2.data,
          tablesFilter,
          schemasFilter,
          prefix: ((_e = config.migrations) == null ? void 0 : _e.prefix) || "index",
          entities: config.entities
        };
      }
      assertUnreachable(dialect6);
    };
    prepareStudioConfig = async (options) => {
      const params = studioCliParams.parse(options);
      const config = await drizzleConfigFromFile(params.config);
      const result = studioConfig.safeParse(config);
      if (!result.success) {
        if (!("dialect" in config)) {
          console.log(outputs.studio.noDialect());
        }
        process.exit(1);
      }
      if (!("dbCredentials" in config)) {
        console.log(outputs.studio.noCredentials());
        process.exit(1);
      }
      const { host, port } = params;
      const { dialect: dialect6, schema: schema6 } = result.data;
      const flattened = flattenDatabaseCredentials(config);
      if (dialect6 === "postgresql") {
        const parsed = postgresCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues3(flattened);
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "mysql") {
        const parsed = mysqlCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues2(flattened);
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "singlestore") {
        const parsed = singlestoreCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues4(flattened);
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "sqlite") {
        const parsed = sqliteCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues5(flattened, "studio");
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      if (dialect6 === "turso") {
        const parsed = libSQLCredentials.safeParse(flattened);
        if (!parsed.success) {
          printConfigConnectionIssues(flattened, "studio");
          process.exit(1);
        }
        const credentials2 = parsed.data;
        return {
          dialect: dialect6,
          schema: schema6,
          host,
          port,
          credentials: credentials2
        };
      }
      assertUnreachable(dialect6);
    };
    migrateConfig = objectType({
      dialect: dialect4,
      out: stringType().optional().default("drizzle"),
      migrations: configMigrations
    });
    prepareMigrateConfig = async (configPath) => {
      const config = await drizzleConfigFromFile(configPath);
      const parsed = migrateConfig.safeParse(config);
      if (parsed.error) {
        console.log(error("Please provide required params:"));
        console.log(wrapParam("dialect", config.dialect));
        process.exit(1);
      }
      const { dialect: dialect6, out } = parsed.data;
      const { schema: schema6, table: table5 } = parsed.data.migrations || {};
      const flattened = flattenDatabaseCredentials(config);
      if (dialect6 === "postgresql") {
        const parsed2 = postgresCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues3(flattened);
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table5
        };
      }
      if (dialect6 === "mysql") {
        const parsed2 = mysqlCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues2(flattened);
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table5
        };
      }
      if (dialect6 === "singlestore") {
        const parsed2 = singlestoreCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues4(flattened);
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table5
        };
      }
      if (dialect6 === "sqlite") {
        const parsed2 = sqliteCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues5(flattened, "migrate");
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table5
        };
      }
      if (dialect6 === "turso") {
        const parsed2 = libSQLCredentials.safeParse(flattened);
        if (!parsed2.success) {
          printConfigConnectionIssues(flattened, "migrate");
          process.exit(1);
        }
        const credentials2 = parsed2.data;
        return {
          dialect: dialect6,
          out,
          credentials: credentials2,
          schema: schema6,
          table: table5
        };
      }
      assertUnreachable(dialect6);
    };
    drizzleConfigFromFile = async (configPath, isExport) => {
      const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
      const defaultTsConfigExists = (0, import_fs3.existsSync)((0, import_path3.resolve)((0, import_path3.join)(prefix2, "drizzle.config.ts")));
      const defaultJsConfigExists = (0, import_fs3.existsSync)((0, import_path3.resolve)((0, import_path3.join)(prefix2, "drizzle.config.js")));
      const defaultJsonConfigExists = (0, import_fs3.existsSync)(
        (0, import_path3.join)((0, import_path3.resolve)("drizzle.config.json"))
      );
      const defaultConfigPath = defaultTsConfigExists ? "drizzle.config.ts" : defaultJsConfigExists ? "drizzle.config.js" : "drizzle.config.json";
      if (!configPath && !isExport) {
        console.log(
          source_default.gray(
            `No config path provided, using default '${defaultConfigPath}'`
          )
        );
      }
      const path4 = (0, import_path3.resolve)((0, import_path3.join)(prefix2, configPath ?? defaultConfigPath));
      if (!(0, import_fs3.existsSync)(path4)) {
        console.log(`${path4} file does not exist`);
        process.exit(1);
      }
      if (!isExport)
        console.log(source_default.grey(`Reading config file '${path4}'`));
      const { unregister } = await safeRegister();
      const required = require(`${path4}`);
      const content = required.default ?? required;
      unregister();
      const res = configCommonSchema.safeParse(content);
      if (!res.success) {
        console.log(res.error);
        if (!("dialect" in content)) {
          console.log(error("Please specify 'dialect' param in config file"));
        }
        process.exit(1);
      }
      return res.data;
    };
  }
});

// src/serializer/mysqlImports.ts
var mysqlImports_exports = {};
__export(mysqlImports_exports, {
  prepareFromExports: () => prepareFromExports,
  prepareFromMySqlImports: () => prepareFromMySqlImports
});
var import_drizzle_orm, import_mysql_core, prepareFromExports, prepareFromMySqlImports;
var init_mysqlImports = __esm({
  "src/serializer/mysqlImports.ts"() {
    "use strict";
    import_drizzle_orm = require("drizzle-orm");
    import_mysql_core = require("drizzle-orm/mysql-core");
    init_utils3();
    prepareFromExports = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t2) => {
        if ((0, import_drizzle_orm.is)(t2, import_mysql_core.MySqlTable)) {
          tables.push(t2);
        }
        if ((0, import_drizzle_orm.is)(t2, import_mysql_core.MySqlView)) {
          views.push(t2);
        }
      });
      return { tables, views };
    };
    prepareFromMySqlImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/serializer/utils.ts
function getColumnCasing(column9, casing2) {
  if (!column9.name)
    return "";
  return !column9.keyAsName || casing2 === void 0 ? column9.name : casing2 === "camelCase" ? (0, import_casing.toCamelCase)(column9.name) : (0, import_casing.toSnakeCase)(column9.name);
}
var import_casing, sqlToStr;
var init_utils4 = __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/mysqlSerializer.ts
var mysqlSerializer_exports = {};
__export(mysqlSerializer_exports, {
  fromDatabase: () => fromDatabase,
  generateMySqlSnapshot: () => generateMySqlSnapshot,
  indexName: () => indexName
});
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_orm2, import_mysql_core2, indexName, handleEnumType, generateMySqlSnapshot, fromDatabase;
var init_mysqlSerializer = __esm({
  "src/serializer/mysqlSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm2 = require("drizzle-orm");
    import_mysql_core2 = require("drizzle-orm/mysql-core");
    init_outputs();
    init_utils2();
    init_utils4();
    indexName = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    handleEnumType = (type) => {
      let str = type.split("(")[1];
      str = str.substring(0, str.length - 1);
      const values = str.split(",").map((v) => `'${escapeSingleQuotes(v.substring(1, v.length - 1))}'`);
      return `enum(${values.join(",")})`;
    };
    generateMySqlSnapshot = (tables, views, casing2) => {
      const dialect6 = new import_mysql_core2.MySqlDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { tables: {}, indexes: {} };
      for (const table5 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          schema: schema6,
          checks,
          primaryKeys,
          uniqueConstraints
        } = (0, import_mysql_core2.getTableConfig)(table5);
        const columnsObject = {};
        const indexesObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const checkConstraintObject = {};
        let checksInTable = {};
        columns.forEach((column9) => {
          const name = getColumnCasing(column9, casing2);
          const notNull = column9.notNull;
          const sqlType = column9.getSQLType();
          const sqlTypeLowered = sqlType.toLowerCase();
          const autoIncrement = typeof column9.autoIncrement === "undefined" ? false : column9.autoIncrement;
          const generated = column9.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: column9.hasOnUpdateNow,
            generated: generated ? {
              as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column9.primary) {
            primaryKeysObject[`${tableName}_${name}`] = {
              name: `${tableName}_${name}`,
              columns: [name]
            };
          }
          if (column9.isUnique) {
            const existingUnique = uniqueConstraintObject[column9.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(
                  column9.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[column9.uniqueName] = {
              name: column9.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column9.default !== void 0) {
            if ((0, import_drizzle_orm2.is)(column9.default, import_drizzle_orm2.SQL)) {
              columnToSet.default = sqlToStr(column9.default, casing2);
            } else {
              if (typeof column9.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column9.default)}'`;
              } else {
                if (sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column9.default)}'`;
                } else if (column9.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column9.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column9.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column9.default;
                }
              }
              if (["blob", "text", "json"].includes(column9.getSQLType())) {
                columnToSet.default = `(${columnToSet.default})`;
              }
            }
          }
          columnsObject[name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c) => c.name);
          const columnNames = pk.columns.map((c) => getColumnCasing(c, casing2));
          let name = pk.getName();
          if (casing2 !== void 0) {
            for (let i2 = 0; i2 < originalColumnNames.length; i2++) {
              name = name.replace(originalColumnNames[i2], columnNames[i2]);
            }
          }
          primaryKeysObject[name] = {
            name,
            columns: columnNames
          };
          for (const column9 of pk.columns) {
            columnsObject[getColumnCasing(column9, casing2)].notNull = true;
          }
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c) => getColumnCasing(c, casing2));
          const name = unq.name ?? (0, import_mysql_core2.uniqueKeyName)(table5, 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((fk4) => {
          const tableFrom = tableName;
          const onDelete = fk4.onDelete ?? "no action";
          const onUpdate = fk4.onUpdate ?? "no action";
          const reference = fk4.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 = fk4.getName();
          if (casing2 !== void 0) {
            for (let i2 = 0; i2 < originalColumnsFrom.length; i2++) {
              name = name.replace(originalColumnsFrom[i2], columnsFrom[i2]);
            }
            for (let i2 = 0; i2 < originalColumnsTo.length; i2++) {
              name = name.replace(originalColumnsTo[i2], columnsTo[i2]);
            }
          }
          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) => {
            var _a;
            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 ((_a = internal.indexes[name]) == null ? void 0 : _a.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.algorythm,
            lock: value.config.lock
          };
        });
        checks.forEach((check2) => {
          check2;
          const checkName = check2.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check2.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] = [check2.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check2.value).sql
          };
        });
        if (!schema6) {
          result[tableName] = {
            name: tableName,
            columns: columnsObject,
            indexes: indexesObject,
            foreignKeys: foreignKeysObject,
            compositePrimaryKeys: primaryKeysObject,
            uniqueConstraints: uniqueConstraintObject,
            checkConstraint: checkConstraintObject
          };
        }
      }
      for (const view4 of views) {
        const {
          isExisting,
          name,
          query,
          schema: schema6,
          selectedFields,
          algorithm,
          sqlSecurity,
          withCheckOption
        } = (0, import_mysql_core2.getViewConfig)(view4);
        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_mysql_core2.MySqlColumn)) {
            const column9 = selectedFields[key];
            const notNull = column9.notNull;
            const sqlTypeLowered = column9.getSQLType().toLowerCase();
            const autoIncrement = typeof column9.autoIncrement === "undefined" ? false : column9.autoIncrement;
            const generated = column9.generated;
            const columnToSet = {
              name: column9.name,
              type: column9.getSQLType(),
              primaryKey: false,
              // If field is autoincrement it's notNull by default
              // notNull: autoIncrement ? true : notNull,
              notNull,
              autoincrement: autoIncrement,
              onUpdate: column9.hasOnUpdateNow,
              generated: generated ? {
                as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
                type: generated.mode ?? "stored"
              } : void 0
            };
            if (column9.default !== void 0) {
              if ((0, import_drizzle_orm2.is)(column9.default, import_drizzle_orm2.SQL)) {
                columnToSet.default = sqlToStr(column9.default, casing2);
              } else {
                if (typeof column9.default === "string") {
                  columnToSet.default = `'${column9.default}'`;
                } else {
                  if (sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column9.default)}'`;
                  } else if (column9.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column9.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                      columnToSet.default = `'${column9.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    }
                  } else {
                    columnToSet.default = column9.default;
                  }
                }
                if (["blob", "text", "json"].includes(column9.getSQLType())) {
                  columnToSet.default = `(${columnToSet.default})`;
                }
              }
            }
            columnsObject[column9.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
      };
    };
    fromDatabase = async (db, inputSchema, tablesFilter = (table5) => 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 column9 of response) {
        if (!tablesFilter(column9["TABLE_NAME"]))
          continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema6 = column9["TABLE_SCHEMA"];
        const tableName = column9["TABLE_NAME"];
        tablesCount.add(`${schema6}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column9["COLUMN_NAME"];
        const isNullable = column9["IS_NULLABLE"] === "YES";
        const dataType = column9["DATA_TYPE"];
        const columnType = column9["COLUMN_TYPE"];
        const isPrimary = column9["COLUMN_KEY"] === "PRI";
        const columnDefault = column9["COLUMN_DEFAULT"];
        const collation = column9["CHARACTER_SET_NAME"];
        const geenratedExpression = column9["GENERATION_EXPRESSION"];
        let columnExtra = column9["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column9["EXTRA"] !== "undefined") {
          columnExtra = column9["EXTRA"];
          isAutoincrement = column9["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column9["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema6 !== inputSchema) {
          schemas.push(schema6);
        }
        const table5 = 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 (!table5) {
          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 == null ? void 0 : deleteRule.toLowerCase(),
              onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
            };
          }
          tableInResult.foreignKeys[constraintName].columnsFrom = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsFrom)
          ];
          tableInResult.foreignKeys[constraintName].columnsTo = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsTo)
          ];
        }
      } catch (e2) {
      }
      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 view4 of views) {
        const viewName = view4["TABLE_NAME"];
        const definition = view4["VIEW_DEFINITION"];
        const withCheckOption = view4["CHECK_OPTION"] === "NONE" ? void 0 : view4["CHECK_OPTION"].toLowerCase();
        const sqlSecurity = view4["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/serializer/pgImports.ts
var pgImports_exports = {};
__export(pgImports_exports, {
  prepareFromExports: () => prepareFromExports2,
  prepareFromPgImports: () => prepareFromPgImports
});
var import_drizzle_orm3, import_pg_core, prepareFromExports2, prepareFromPgImports;
var init_pgImports = __esm({
  "src/serializer/pgImports.ts"() {
    "use strict";
    import_drizzle_orm3 = require("drizzle-orm");
    import_pg_core = require("drizzle-orm/pg-core");
    init_utils3();
    prepareFromExports2 = (exports2) => {
      const tables = [];
      const enums = [];
      const schemas = [];
      const sequences = [];
      const roles = [];
      const policies = [];
      const views = [];
      const matViews = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t2) => {
        if ((0, import_pg_core.isPgEnum)(t2)) {
          enums.push(t2);
          return;
        }
        if ((0, import_drizzle_orm3.is)(t2, import_pg_core.PgTable)) {
          tables.push(t2);
        }
        if ((0, import_drizzle_orm3.is)(t2, import_pg_core.PgSchema)) {
          schemas.push(t2);
        }
        if ((0, import_pg_core.isPgView)(t2)) {
          views.push(t2);
        }
        if ((0, import_pg_core.isPgMaterializedView)(t2)) {
          matViews.push(t2);
        }
        if ((0, import_pg_core.isPgSequence)(t2)) {
          sequences.push(t2);
        }
        if ((0, import_drizzle_orm3.is)(t2, import_pg_core.PgRole)) {
          roles.push(t2);
        }
        if ((0, import_drizzle_orm3.is)(t2, import_pg_core.PgPolicy)) {
          policies.push(t2);
        }
      });
      return { tables, enums, schemas, sequences, views, matViews, roles, policies };
    };
    prepareFromPgImports = async (imports) => {
      const tables = [];
      const enums = [];
      const schemas = [];
      const sequences = [];
      const views = [];
      const roles = [];
      const policies = [];
      const matViews = [];
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports2(i0);
        tables.push(...prepared.tables);
        enums.push(...prepared.enums);
        schemas.push(...prepared.schemas);
        sequences.push(...prepared.sequences);
        views.push(...prepared.views);
        matViews.push(...prepared.matViews);
        roles.push(...prepared.roles);
        policies.push(...prepared.policies);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), enums, schemas, sequences, views, matViews, roles, policies };
    };
  }
});

// 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/pgSerializer.ts
var pgSerializer_exports = {};
__export(pgSerializer_exports, {
  buildArrayString: () => buildArrayString,
  fromDatabase: () => fromDatabase2,
  generatePgSnapshot: () => generatePgSnapshot,
  indexName: () => indexName2
});
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_orm4, import_pg_core2, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn, getColumnsInfoQuery;
var init_pgSerializer = __esm({
  "src/serializer/pgSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm4 = require("drizzle-orm");
    import_pg_core2 = require("drizzle-orm/pg-core");
    init_vector();
    init_outputs();
    init_utils2();
    init_utils4();
    indexName2 = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    generatePgSnapshot = (tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
      const dialect6 = new import_pg_core2.PgDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const sequencesToReturn = {};
      const rolesToReturn = {};
      const policiesToReturn = {};
      const indexesInSchema = {};
      for (const table5 of tables) {
        const checksInTable = {};
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          checks,
          schema: schema6,
          primaryKeys,
          uniqueConstraints,
          policies: policies2,
          enableRLS
        } = (0, import_pg_core2.getTableConfig)(table5);
        if (schemaFilter && !schemaFilter.includes(schema6 ?? "public")) {
          continue;
        }
        const columnsObject = {};
        const indexesObject = {};
        const checksObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const policiesObject = {};
        columns.forEach((column9) => {
          var _a2, _b2, _c2, _d2, _e2, _f2;
          const name = getColumnCasing(column9, casing2);
          const notNull = column9.notNull;
          const primaryKey = column9.primary;
          const sqlTypeLowered = column9.getSQLType().toLowerCase();
          const typeSchema = (0, import_drizzle_orm4.is)(column9, import_pg_core2.PgEnumColumn) ? column9.enum.schema || "public" : void 0;
          const generated = column9.generated;
          const identity = column9.generatedIdentity;
          const increment = stringFromIdentityProperty((_a2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _a2.increment) ?? "1";
          const minValue = stringFromIdentityProperty((_b2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _b2.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column9.columnType) : "1");
          const maxValue = stringFromIdentityProperty((_c2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _c2.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column9.getSQLType()));
          const startWith = stringFromIdentityProperty((_d2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _d2.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache = stringFromIdentityProperty((_e2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _e2.cache) ?? "1";
          const columnToSet = {
            name,
            type: column9.getSQLType(),
            typeSchema,
            primaryKey,
            notNull,
            generated: generated ? {
              as: (0, import_drizzle_orm4.is)(generated.as, import_drizzle_orm4.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,
              cycle: ((_f2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _f2.cycle) ?? false
            } : void 0
          };
          if (column9.isUnique) {
            const existingUnique = uniqueConstraintObject[column9.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(
                  column9.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[column9.uniqueName] = {
              name: column9.uniqueName,
              nullsNotDistinct: column9.uniqueType === "not distinct",
              columns: [columnToSet.name]
            };
          }
          if (column9.default !== void 0) {
            if ((0, import_drizzle_orm4.is)(column9.default, import_drizzle_orm4.SQL)) {
              columnToSet.default = sqlToStr(column9.default, casing2);
            } else {
              if (typeof column9.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column9.default)}'`;
              } else {
                if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column9.default)}'::${sqlTypeLowered}`;
                } else if (column9.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column9.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered === "timestamp") {
                    columnToSet.default = `'${column9.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  } else {
                    columnToSet.default = `'${column9.default.toISOString()}'`;
                  }
                } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column9.default)) {
                  columnToSet.default = `'${buildArrayString(column9.default, sqlTypeLowered)}'`;
                } else {
                  columnToSet.default = column9.default;
                }
              }
            }
          }
          columnsObject[name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c) => c.name);
          const columnNames = pk.columns.map((c) => getColumnCasing(c, casing2));
          let name = pk.getName();
          if (casing2 !== void 0) {
            for (let i2 = 0; i2 < originalColumnNames.length; i2++) {
              name = name.replace(originalColumnNames[i2], columnNames[i2]);
            }
          }
          primaryKeysObject[name] = {
            name,
            columns: columnNames
          };
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c) => getColumnCasing(c, casing2));
          const name = unq.name ?? (0, import_pg_core2.uniqueKeyName)(table5, 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((fk4) => {
          const tableFrom = tableName;
          const onDelete = fk4.onDelete;
          const onUpdate = fk4.onUpdate;
          const reference = fk4.reference();
          const tableTo = (0, import_drizzle_orm4.getTableName)(reference.foreignTable);
          const schemaTo = (0, import_pg_core2.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 = fk4.getName();
          if (casing2 !== void 0) {
            for (let i2 = 0; i2 < originalColumnsFrom.length; i2++) {
              name = name.replace(originalColumnsFrom[i2], columnsFrom[i2]);
            }
            for (let i2 = 0; i2 < originalColumnsTo.length; i2++) {
              name = name.replace(originalColumnsTo[i2], columnsTo[i2]);
            }
          }
          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_orm4.is)(it, import_drizzle_orm4.SQL)) {
              if (typeof value.config.name === "undefined") {
                console.log(
                  `
${withStyle.errorWarning(
                    `Please specify an index name in ${(0, import_drizzle_orm4.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_orm4.is)(it, import_drizzle_orm4.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 : indexName2(tableName, indexColumnNames);
          let indexColumns = columns2.map(
            (it) => {
              var _a2, _b2, _c2, _d2, _e2;
              if ((0, import_drizzle_orm4.is)(it, import_drizzle_orm4.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: ((_a2 = it.indexConfig) == null ? void 0 : _a2.order) === "asc",
                  nulls: ((_b2 = it.indexConfig) == null ? void 0 : _b2.nulls) ? (_c2 = it.indexConfig) == null ? void 0 : _c2.nulls : ((_d2 = it.indexConfig) == null ? void 0 : _d2.order) === "desc" ? "first" : "last",
                  opclass: (_e2 = it.indexConfig) == null ? void 0 : _e2.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((policy4) => {
          var _a2, _b2;
          const mappedTo = [];
          if (!policy4.to) {
            mappedTo.push("public");
          } else {
            if (policy4.to && typeof policy4.to === "string") {
              mappedTo.push(policy4.to);
            } else if (policy4.to && (0, import_drizzle_orm4.is)(policy4.to, import_pg_core2.PgRole)) {
              mappedTo.push(policy4.to.name);
            } else if (policy4.to && Array.isArray(policy4.to)) {
              policy4.to.forEach((it) => {
                if (typeof it === "string") {
                  mappedTo.push(it);
                } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) {
                  mappedTo.push(it.name);
                }
              });
            }
          }
          if (policiesObject[policy4.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(
                  policy4.name
                )} name`
              )}`
            );
            process.exit(1);
          }
          policiesObject[policy4.name] = {
            name: policy4.name,
            as: ((_a2 = policy4.as) == null ? void 0 : _a2.toUpperCase()) ?? "PERMISSIVE",
            for: ((_b2 = policy4.for) == null ? void 0 : _b2.toUpperCase()) ?? "ALL",
            to: mappedTo.sort(),
            using: (0, import_drizzle_orm4.is)(policy4.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy4.using).sql : void 0,
            withCheck: (0, import_drizzle_orm4.is)(policy4.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy4.withCheck).sql : void 0
          };
        });
        checks.forEach((check2) => {
          const checkName = check2.name;
          if (typeof checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] !== "undefined") {
            if (checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].includes(check2.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}"`] = [check2.name];
          }
          checksObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check2.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 policy4 of policies) {
        if (!policy4._linkedTable) {
          console.log(
            `
${withStyle.errorWarning(
              `"Policy ${policy4.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_core2.getTableConfig)(policy4._linkedTable);
        const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`;
        const mappedTo = [];
        if (!policy4.to) {
          mappedTo.push("public");
        } else {
          if (policy4.to && typeof policy4.to === "string") {
            mappedTo.push(policy4.to);
          } else if (policy4.to && (0, import_drizzle_orm4.is)(policy4.to, import_pg_core2.PgRole)) {
            mappedTo.push(policy4.to.name);
          } else if (policy4.to && Array.isArray(policy4.to)) {
            policy4.to.forEach((it) => {
              if (typeof it === "string") {
                mappedTo.push(it);
              } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) {
                mappedTo.push(it.name);
              }
            });
          }
        }
        if (((_a = result[tableKey2]) == null ? void 0 : _a.policies[policy4.name]) !== void 0 || policiesToReturn[policy4.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(
                policy4.name
              )} name`
            )}`
          );
          process.exit(1);
        }
        const mappedPolicy = {
          name: policy4.name,
          as: ((_b = policy4.as) == null ? void 0 : _b.toUpperCase()) ?? "PERMISSIVE",
          for: ((_c = policy4.for) == null ? void 0 : _c.toUpperCase()) ?? "ALL",
          to: mappedTo.sort(),
          using: (0, import_drizzle_orm4.is)(policy4.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy4.using).sql : void 0,
          withCheck: (0, import_drizzle_orm4.is)(policy4.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy4.withCheck).sql : void 0
        };
        if (result[tableKey2]) {
          result[tableKey2].policies[policy4.name] = mappedPolicy;
        } else {
          policiesToReturn[policy4.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((_d = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _d.increment) ?? "1";
          const minValue = stringFromIdentityProperty((_e = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _e.minValue) ?? (parseFloat(increment) < 0 ? "-9223372036854775808" : "1");
          const maxValue = stringFromIdentityProperty((_f = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _f.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : "9223372036854775807");
          const startWith = stringFromIdentityProperty((_g = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _g.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache = stringFromIdentityProperty((_h = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _h.cache) ?? "1";
          sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] = {
            name,
            schema: sequence.schema ?? "public",
            increment,
            startWith,
            minValue,
            maxValue,
            cache,
            cycle: ((_i = sequence.seqOptions) == null ? void 0 : _i.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 view4 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_orm4.is)(view4, import_pg_core2.PgView)) {
          ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core2.getViewConfig)(view4));
        } else {
          ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core2.getMaterializedViewConfig)(view4));
          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_orm4.is)(selectedFields[key], import_pg_core2.PgColumn)) {
            const column9 = selectedFields[key];
            const notNull = column9.notNull;
            const primaryKey = column9.primary;
            const sqlTypeLowered = column9.getSQLType().toLowerCase();
            const typeSchema = (0, import_drizzle_orm4.is)(column9, import_pg_core2.PgEnumColumn) ? column9.enum.schema || "public" : void 0;
            const generated = column9.generated;
            const identity = column9.generatedIdentity;
            const increment = stringFromIdentityProperty((_j = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _j.increment) ?? "1";
            const minValue = stringFromIdentityProperty((_k = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _k.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column9.columnType) : "1");
            const maxValue = stringFromIdentityProperty((_l = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _l.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column9.getSQLType()));
            const startWith = stringFromIdentityProperty((_m = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _m.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
            const cache = stringFromIdentityProperty((_n = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _n.cache) ?? "1";
            const columnToSet = {
              name: column9.name,
              type: column9.getSQLType(),
              typeSchema,
              primaryKey,
              notNull,
              generated: generated ? {
                as: (0, import_drizzle_orm4.is)(generated.as, import_drizzle_orm4.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}_${column9.name}_seq`,
                schema: schema6 ?? "public",
                increment,
                startWith,
                minValue,
                maxValue,
                cache,
                cycle: ((_o = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _o.cycle) ?? false
              } : void 0
            };
            if (column9.isUnique) {
              const existingUnique = uniqueConstraintObject[column9.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(column9.uniqueName)} on the ${source_default.underline.blue(
                      column9.name
                    )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
`
                  )}`
                );
                process.exit(1);
              }
              uniqueConstraintObject[column9.uniqueName] = {
                name: column9.uniqueName,
                nullsNotDistinct: column9.uniqueType === "not distinct",
                columns: [columnToSet.name]
              };
            }
            if (column9.default !== void 0) {
              if ((0, import_drizzle_orm4.is)(column9.default, import_drizzle_orm4.SQL)) {
                columnToSet.default = sqlToStr(column9.default, casing2);
              } else {
                if (typeof column9.default === "string") {
                  columnToSet.default = `'${column9.default}'`;
                } else {
                  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column9.default)}'::${sqlTypeLowered}`;
                  } else if (column9.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column9.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered === "timestamp") {
                      columnToSet.default = `'${column9.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    } else {
                      columnToSet.default = `'${column9.default.toISOString()}'`;
                    }
                  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column9.default)) {
                    columnToSet.default = `'${buildArrayString(column9.default, sqlTypeLowered)}'`;
                  } else {
                    columnToSet.default = column9.default;
                  }
                }
              }
            }
            columnsObject[column9.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((map, obj) => {
        const enumSchema3 = obj.schema || "public";
        const key = `${enumSchema3}.${obj.enumName}`;
        map[key] = {
          name: obj.enumName,
          schema: enumSchema3,
          values: obj.enumValues
        };
        return map;
      }, {});
      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();
    };
    fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
      const result = {};
      const views = {};
      const policies = {};
      const internals = { tables: {} };
      const where = schemaFilters.map((t2) => `n.nspname = '${t2}'`).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((t2) => `schemaname = '${t2}'`).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((t2) => `n.nspname = '${t2}'`).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 enumSchema3 = dbEnum.enum_schema || "public";
        const key = `${enumSchema3}.${enumName}`;
        if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) {
          enumsToReturn[key].values.push(enumValue);
        } else {
          enumsToReturn[key] = {
            name: enumName,
            values: [enumValue],
            schema: enumSchema3
          };
        }
      }
      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 == null ? void 0 : tsSchema.policies) ?? {}).map((it) => it.schema);
      const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t2) => `schemaname = '${t2}'`).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 == null ? void 0 : tsSchema.policies[dbPolicy.name]) {
          policies[dbPolicy.name] = {
            ...rest,
            to: parsedTo,
            withCheck: parsedWithCheck,
            using: parsedUsing,
            on: tsSchema == null ? void 0 : 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) => {
          var _a, _b, _c, _d, _e, _f;
          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';`);
            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 fk4 of tableForeignKeys) {
              const columnFrom = fk4.column_name;
              const tableTo = fk4.foreign_table_name;
              const columnTo = fk4.foreign_column_name;
              const schemaTo = fk4.foreign_table_schema;
              const foreignKeyName = fk4.constraint_name;
              const onUpdate = (_a = fk4.update_rule) == null ? void 0 : _a.toLowerCase();
              const onDelete = (_b = fk4.delete_rule) == null ? void 0 : _b.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((c) => c.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 i2 = 1; i2 < Number(columnDimensions); i2++) {
                  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"].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: ((_c = sequencesToReturn[identityName]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[identityName]) == null ? void 0 : _d.cache : ((_e = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _e.cache) ? (_f = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _f.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_expr(
                              i.indexprs,
                              i.indrelid
                          )
                        || '}')::text[]
                  )[k.i]
                ) 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 indexName5 = 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(indexName5))
                continue;
              if (typeof indexToReturn[indexName5] !== "undefined") {
                indexToReturn[indexName5].columns.push({
                  expression: indexColumnName,
                  asc: !desc,
                  nulls: nullsFirst ? "first" : "last",
                  opclass,
                  isExpression
                });
              } else {
                indexToReturn[indexName5] = {
                  name: indexName5,
                  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 (e2) {
            rej(e2);
            return;
          }
          res("");
        });
      });
      if (progressCallback) {
        progressCallback("tables", tableCount, "done");
      }
      for await (const _2 of all) {
      }
      const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
        return new Promise(async (res, rej) => {
          var _a, _b, _c, _d;
          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 i2 = 1; i2 < Number(columnDimensions); i2++) {
                  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"].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: ((_a = sequencesToReturn[identityName]) == null ? void 0 : _a.cache) ? (_b = sequencesToReturn[identityName]) == null ? void 0 : _b.cache : ((_c = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _d.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 (e2) {
            rej(e2);
            return;
          }
          res("");
        });
      });
      viewsCount = allViews.length;
      for await (const _2 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 = (column9, internals, tableName) => {
      var _a, _b;
      const columnName = column9.column_name;
      const isArray3 = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
      if (column9.column_default === null || column9.column_default === void 0 || column9.data_type === "serial" || column9.data_type === "smallserial" || column9.data_type === "bigserial") {
        return void 0;
      }
      if (column9.column_default.endsWith("[]")) {
        column9.column_default = column9.column_default.slice(0, -2);
      }
      column9.column_default = column9.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
      const columnDefaultAsString = column9.column_default.toString();
      if (isArray3) {
        return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
          if (["integer", "smallint", "bigint", "double precision", "real"].includes(column9.data_type.slice(0, -2))) {
            return value;
          } else if (column9.data_type.startsWith("timestamp")) {
            return `${value}`;
          } else if (column9.data_type.slice(0, -2) === "interval") {
            return value.replaceAll('"', `"`);
          } else if (column9.data_type.slice(0, -2) === "boolean") {
            return value === "t" ? "true" : "false";
          } else if (["json", "jsonb"].includes(column9.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(column9.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 (column9.data_type.includes("numeric")) {
        return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
      } else if (column9.data_type === "json" || column9.data_type === "jsonb") {
        const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
        return `'${jsonWithoutSpaces}'::${column9.data_type}`;
      } else if (column9.data_type === "boolean") {
        return column9.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: table5, 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}"."${table5}"', 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 = '${table5}'  -- Filter by table name
ORDER BY 
    a.attnum;  -- Order by column number`
      );
    };
  }
});

// src/serializer/sqliteImports.ts
var sqliteImports_exports = {};
__export(sqliteImports_exports, {
  prepareFromExports: () => prepareFromExports3,
  prepareFromSqliteImports: () => prepareFromSqliteImports
});
var import_drizzle_orm5, import_sqlite_core, prepareFromExports3, prepareFromSqliteImports;
var init_sqliteImports = __esm({
  "src/serializer/sqliteImports.ts"() {
    "use strict";
    import_drizzle_orm5 = require("drizzle-orm");
    import_sqlite_core = require("drizzle-orm/sqlite-core");
    init_utils3();
    prepareFromExports3 = (exports2) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t2) => {
        if ((0, import_drizzle_orm5.is)(t2, import_sqlite_core.SQLiteTable)) {
          tables.push(t2);
        }
        if ((0, import_drizzle_orm5.is)(t2, import_sqlite_core.SQLiteView)) {
          views.push(t2);
        }
      });
      return { tables, views };
    };
    prepareFromSqliteImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        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/serializer/sqliteSerializer.ts
var sqliteSerializer_exports = {};
__export(sqliteSerializer_exports, {
  fromDatabase: () => fromDatabase3,
  generateSqliteSnapshot: () => generateSqliteSnapshot
});
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;
}
var import_drizzle_orm6, import_sqlite_core2, generateSqliteSnapshot, fromDatabase3;
var init_sqliteSerializer = __esm({
  "src/serializer/sqliteSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm6 = require("drizzle-orm");
    import_sqlite_core2 = require("drizzle-orm/sqlite-core");
    init_outputs();
    init_utils2();
    init_utils4();
    generateSqliteSnapshot = (tables, views, casing2) => {
      const dialect6 = new import_sqlite_core2.SQLiteSyncDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { indexes: {} };
      for (const table5 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_core2.getTableConfig)(table5);
        columns.forEach((column9) => {
          const name = getColumnCasing(column9, casing2);
          const notNull = column9.notNull;
          const primaryKey = column9.primary;
          const generated = column9.generated;
          const columnToSet = {
            name,
            type: column9.getSQLType(),
            primaryKey,
            notNull,
            autoincrement: (0, import_drizzle_orm6.is)(column9, import_sqlite_core2.SQLiteBaseInteger) ? column9.autoIncrement : false,
            generated: generated ? {
              as: (0, import_drizzle_orm6.is)(generated.as, import_drizzle_orm6.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 (column9.default !== void 0) {
            if ((0, import_drizzle_orm6.is)(column9.default, import_drizzle_orm6.SQL)) {
              columnToSet.default = sqlToStr(column9.default, casing2);
            } else {
              columnToSet.default = typeof column9.default === "string" ? `'${escapeSingleQuotes(column9.default)}'` : typeof column9.default === "object" || Array.isArray(column9.default) ? `'${JSON.stringify(column9.default)}'` : column9.default;
            }
          }
          columnsObject[name] = columnToSet;
          if (column9.isUnique) {
            const existingUnique = indexesObject[column9.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(
                  column9.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[column9.uniqueName] = {
              name: column9.uniqueName,
              columns: [columnToSet.name],
              isUnique: true
            };
          }
        });
        const foreignKeys = tableForeignKeys.map((fk4) => {
          const tableFrom = tableName;
          const onDelete = fk4.onDelete ?? "no action";
          const onUpdate = fk4.onUpdate ?? "no action";
          const reference = fk4.reference();
          const referenceFT = reference.foreignTable;
          const tableTo = (0, import_drizzle_orm6.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 = fk4.getName();
          if (casing2 !== void 0) {
            for (let i2 = 0; i2 < originalColumnsFrom.length; i2++) {
              name = name.replace(originalColumnsFrom[i2], columnsFrom[i2]);
            }
            for (let i2 = 0; i2 < originalColumnsTo.length; i2++) {
              name = name.replace(originalColumnsTo[i2], columnsTo[i2]);
            }
          }
          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) => {
            var _a;
            if ((0, import_drizzle_orm6.is)(it, import_drizzle_orm6.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof ((_a = internal.indexes[name]) == null ? void 0 : _a.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_orm6.is)(value.config.where, import_drizzle_orm6.SQL)) {
              where = dialect6.sqlToQuery(value.config.where).sql;
            }
          }
          indexesObject[name] = {
            name,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            where
          };
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c) => getColumnCasing(c, casing2));
          const name = unq.name ?? (0, import_sqlite_core2.uniqueKeyName)(table5, 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((c) => c.name);
            const columnNames = it.columns.map((c) => getColumnCasing(c, casing2));
            let name = it.getName();
            if (casing2 !== void 0) {
              for (let i2 = 0; i2 < originalColumnNames.length; i2++) {
                name = name.replace(originalColumnNames[i2], columnNames[i2]);
              }
            }
            primaryKeysObject[name] = {
              columns: columnNames,
              name
            };
          } else {
            columnsObject[getColumnCasing(it.columns[0], casing2)].primaryKey = true;
          }
        });
        checks.forEach((check2) => {
          const checkName = check2.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check2.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] = [check2.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check2.value).sql
          };
        });
        result[tableName] = {
          name: tableName,
          columns: columnsObject,
          indexes: indexesObject,
          foreignKeys: foreignKeysObject,
          compositePrimaryKeys: primaryKeysObject,
          uniqueConstraints: uniqueConstraintObject,
          checkConstraints: checkConstraintObject
        };
      }
      for (const view4 of views) {
        const { name, isExisting, selectedFields, query, schema: schema6 } = (0, import_sqlite_core2.getViewConfig)(view4);
        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_orm6.is)(selectedFields[key], import_sqlite_core2.SQLiteColumn)) {
            const column9 = selectedFields[key];
            const notNull = column9.notNull;
            const primaryKey = column9.primary;
            const generated = column9.generated;
            const columnToSet = {
              name: column9.name,
              type: column9.getSQLType(),
              primaryKey,
              notNull,
              autoincrement: (0, import_drizzle_orm6.is)(column9, import_sqlite_core2.SQLiteBaseInteger) ? column9.autoIncrement : false,
              generated: generated ? {
                as: (0, import_drizzle_orm6.is)(generated.as, import_drizzle_orm6.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 (column9.default !== void 0) {
              if ((0, import_drizzle_orm6.is)(column9.default, import_drizzle_orm6.SQL)) {
                columnToSet.default = sqlToStr(column9.default, casing2);
              } else {
                columnToSet.default = typeof column9.default === "string" ? `'${column9.default}'` : typeof column9.default === "object" || Array.isArray(column9.default) ? `'${JSON.stringify(column9.default)}'` : column9.default;
              }
            }
            columnsObject[column9.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
      };
    };
    fromDatabase3 = async (db, tablesFilter = (table5) => 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 m.tbl_name != 'sqlite_sequence' 
    and m.tbl_name != 'sqlite_stat1' 
    and m.tbl_name != '_litestream_seq' 
    and m.tbl_name != '_litestream_lock' 
    and m.tbl_name != 'libsql_wasm_func_table' 
    and m.tbl_name != '__drizzle_migrations' 
    and m.tbl_name != '_cf_KV';
    `
      );
      const tablesWithSeq = [];
      const seq = await db.query(
        `SELECT * FROM sqlite_master WHERE name != 'sqlite_sequence' 
    and name != 'sqlite_stat1' 
    and name != '_litestream_seq' 
    and name != '_litestream_lock' 
    and tbl_name != '_cf_KV' 
    and sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*';`
      );
      for (const s2 of seq) {
        tablesWithSeq.push(s2.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 column9 of columns) {
        if (!tablesFilter(column9.tableName))
          continue;
        if (column9.type !== "view") {
          columnsCount += 1;
        }
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const tableName = column9.tableName;
        tablesCount.add(tableName);
        if (progressCallback) {
          progressCallback("tables", tablesCount.size, "fetching");
        }
        const columnName = column9.columnName;
        const isNotNull = column9.notNull === 1;
        const columnType = column9.columnType;
        const isPrimary = column9.pk !== 0;
        const columnDefault = column9.defaultValue;
        const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
        if (isPrimary) {
          if (typeof tableToPk[tableName] === "undefined") {
            tableToPk[tableName] = [columnName];
          } else {
            tableToPk[tableName].push(columnName);
          }
        }
        const table5 = result[tableName];
        if (column9.hidden === 2 || column9.hidden === 3) {
          if (typeof tableToGeneratedColumnsInfo[column9.tableName] === "undefined") {
            tableToGeneratedColumnsInfo[column9.tableName] = extractGeneratedColumns(
              column9.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 (!table5) {
          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 m.tbl_name != '_cf_KV';`
        );
        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 == null ? void 0 : deleteRule.toLowerCase(),
              onUpdate: updateRule == null ? void 0 : 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 (e2) {
      }
      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_%'
    and m.tbl_name != '_cf_KV';`
      );
      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 view4 of views) {
        const viewName = view4["view_name"];
        const sql = view4["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 name != 'sqlite_sequence';`);
      for (const check2 of checks) {
        if (!tablesFilter(check2.tableName))
          continue;
        const { tableName, sql } = check2;
        let namedChecks = [...sql.matchAll(namedCheckPattern)];
        if (namedChecks.length > 0) {
          namedChecks.forEach(([_2, checkName, checkValue]) => {
            checkConstraints[checkName] = {
              name: checkName,
              value: checkValue.trim()
            };
          });
        } else {
          let unnamedChecks = [...sql.matchAll(unnamedCheckPattern)];
          unnamedChecks.forEach(([_2, 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 table5 = result[tableName];
        if (!table5) {
          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/serializer/singlestoreImports.ts
var singlestoreImports_exports = {};
__export(singlestoreImports_exports, {
  prepareFromExports: () => prepareFromExports4,
  prepareFromSingleStoreImports: () => prepareFromSingleStoreImports
});
var import_drizzle_orm7, import_singlestore_core, prepareFromExports4, prepareFromSingleStoreImports;
var init_singlestoreImports = __esm({
  "src/serializer/singlestoreImports.ts"() {
    "use strict";
    import_drizzle_orm7 = require("drizzle-orm");
    import_singlestore_core = require("drizzle-orm/singlestore-core");
    init_utils3();
    prepareFromExports4 = (exports2) => {
      const tables = [];
      const i0values = Object.values(exports2);
      i0values.forEach((t2) => {
        if ((0, import_drizzle_orm7.is)(t2, import_singlestore_core.SingleStoreTable)) {
          tables.push(t2);
        }
      });
      return {
        tables
        /* views  */
      };
    };
    prepareFromSingleStoreImports = async (imports) => {
      const tables = [];
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        const i0 = require(`${it}`);
        const prepared = prepareFromExports4(i0);
        tables.push(...prepared.tables);
      }
      unregister();
      return {
        tables: Array.from(new Set(tables))
        /* , views */
      };
    };
  }
});

// src/serializer/singlestoreSerializer.ts
var singlestoreSerializer_exports = {};
__export(singlestoreSerializer_exports, {
  fromDatabase: () => fromDatabase4,
  generateSingleStoreSnapshot: () => generateSingleStoreSnapshot,
  indexName: () => indexName3
});
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_orm8, import_singlestore_core2, dialect5, indexName3, generateSingleStoreSnapshot, fromDatabase4;
var init_singlestoreSerializer = __esm({
  "src/serializer/singlestoreSerializer.ts"() {
    "use strict";
    init_source();
    import_drizzle_orm8 = require("drizzle-orm");
    import_singlestore_core2 = require("drizzle-orm/singlestore-core");
    init_outputs();
    init_utils4();
    dialect5 = new import_singlestore_core2.SingleStoreDialect();
    indexName3 = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    generateSingleStoreSnapshot = (tables, casing2) => {
      const dialect6 = new import_singlestore_core2.SingleStoreDialect({ casing: casing2 });
      const result = {};
      const internal = { tables: {}, indexes: {} };
      for (const table5 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          schema: schema6,
          primaryKeys,
          uniqueConstraints
        } = (0, import_singlestore_core2.getTableConfig)(table5);
        const columnsObject = {};
        const indexesObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        columns.forEach((column9) => {
          const notNull = column9.notNull;
          const sqlTypeLowered = column9.getSQLType().toLowerCase();
          const autoIncrement = typeof column9.autoIncrement === "undefined" ? false : column9.autoIncrement;
          const generated = column9.generated;
          const columnToSet = {
            name: column9.name,
            type: column9.getSQLType(),
            primaryKey: false,
            // If field is autoincrement it's notNull by default
            // notNull: autoIncrement ? true : notNull,
            notNull,
            autoincrement: autoIncrement,
            onUpdate: column9.hasOnUpdateNow,
            generated: generated ? {
              as: (0, import_drizzle_orm8.is)(generated.as, import_drizzle_orm8.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column9.primary) {
            primaryKeysObject[`${tableName}_${column9.name}`] = {
              name: `${tableName}_${column9.name}`,
              columns: [column9.name]
            };
          }
          if (column9.isUnique) {
            const existingUnique = uniqueConstraintObject[column9.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(
                  column9.uniqueName
                )} on the ${source_default.underline.blue(
                  column9.name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column9.uniqueName] = {
              name: column9.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column9.default !== void 0) {
            if ((0, import_drizzle_orm8.is)(column9.default, import_drizzle_orm8.SQL)) {
              columnToSet.default = sqlToStr(column9.default, casing2);
            } else {
              if (typeof column9.default === "string") {
                columnToSet.default = `'${column9.default}'`;
              } else {
                if (sqlTypeLowered === "json" || Array.isArray(column9.default)) {
                  columnToSet.default = `'${JSON.stringify(column9.default)}'`;
                } else if (column9.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column9.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column9.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column9.default;
                }
              }
            }
          }
          columnsObject[column9.name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const columnNames = pk.columns.map((c) => c.name);
          primaryKeysObject[pk.getName()] = {
            name: pk.getName(),
            columns: columnNames
          };
          for (const column9 of pk.columns) {
            columnsObject[column9.name].notNull = true;
          }
        });
        uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
          const columnNames = unq.columns.map((c) => c.name);
          const name = unq.name ?? (0, import_singlestore_core2.uniqueKeyName)(table5, 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) => {
            var _a;
            if ((0, import_drizzle_orm8.is)(it, import_drizzle_orm8.SQL)) {
              const sql = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name] === "undefined") {
                internal.indexes[name] = {
                  columns: {
                    [sql]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof ((_a = internal.indexes[name]) == null ? void 0 : _a.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.algorythm,
            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 = (table5) => 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 column9 of response) {
        if (!tablesFilter(column9["TABLE_NAME"]))
          continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema6 = column9["TABLE_SCHEMA"];
        const tableName = column9["TABLE_NAME"];
        tablesCount.add(`${schema6}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column9["COLUMN_NAME"];
        const isNullable = column9["IS_NULLABLE"] === "YES";
        const dataType = column9["DATA_TYPE"];
        const columnType = column9["COLUMN_TYPE"];
        const isPrimary = column9["COLUMN_KEY"] === "PRI";
        let columnDefault = column9["COLUMN_DEFAULT"];
        const collation = column9["CHARACTER_SET_NAME"];
        const geenratedExpression = column9["GENERATION_EXPRESSION"];
        let columnExtra = column9["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column9["EXTRA"] !== "undefined") {
          columnExtra = column9["EXTRA"];
          isAutoincrement = column9["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column9["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema6 !== inputSchema) {
          schemas.push(schema6);
        }
        const table5 = 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 == null ? void 0 : 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 (!table5) {
          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
      };
    };
  }
});

// src/serializer/index.ts
var import_fs4, glob, import_path4, serializeMySql, serializePg, serializeSQLite, serializeSingleStore, prepareFilenames;
var init_serializer = __esm({
  "src/serializer/index.ts"() {
    "use strict";
    init_source();
    import_fs4 = __toESM(require("fs"));
    glob = __toESM(require_glob());
    import_path4 = __toESM(require("path"));
    init_views();
    serializeMySql = async (path4, casing2) => {
      const filenames = prepareFilenames(path4);
      console.log(source_default.gray(`Reading schema files:
${filenames.join("\n")}
`));
      const { prepareFromMySqlImports: prepareFromMySqlImports2 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
      const { generateMySqlSnapshot: generateMySqlSnapshot2 } = await Promise.resolve().then(() => (init_mysqlSerializer(), mysqlSerializer_exports));
      const { tables, views } = await prepareFromMySqlImports2(filenames);
      return generateMySqlSnapshot2(tables, views, casing2);
    };
    serializePg = async (path4, casing2, schemaFilter) => {
      const filenames = prepareFilenames(path4);
      const { prepareFromPgImports: prepareFromPgImports2 } = await Promise.resolve().then(() => (init_pgImports(), pgImports_exports));
      const { generatePgSnapshot: generatePgSnapshot2 } = await Promise.resolve().then(() => (init_pgSerializer(), pgSerializer_exports));
      const { tables, enums, schemas, sequences, views, matViews, roles, policies } = await prepareFromPgImports2(
        filenames
      );
      return generatePgSnapshot2(tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter);
    };
    serializeSQLite = async (path4, casing2) => {
      const filenames = prepareFilenames(path4);
      const { prepareFromSqliteImports: prepareFromSqliteImports2 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
      const { generateSqliteSnapshot: generateSqliteSnapshot2 } = await Promise.resolve().then(() => (init_sqliteSerializer(), sqliteSerializer_exports));
      const { tables, views } = await prepareFromSqliteImports2(filenames);
      return generateSqliteSnapshot2(tables, views, casing2);
    };
    serializeSingleStore = async (path4, casing2) => {
      const filenames = prepareFilenames(path4);
      console.log(source_default.gray(`Reading schema files:
${filenames.join("\n")}
`));
      const { prepareFromSingleStoreImports: prepareFromSingleStoreImports2 } = await Promise.resolve().then(() => (init_singlestoreImports(), singlestoreImports_exports));
      const { generateSingleStoreSnapshot: generateSingleStoreSnapshot2 } = await Promise.resolve().then(() => (init_singlestoreSerializer(), singlestoreSerializer_exports));
      const {
        tables
        /* views */
      } = await prepareFromSingleStoreImports2(filenames);
      return generateSingleStoreSnapshot2(
        tables,
        /* views, */
        casing2
      );
    };
    prepareFilenames = (path4) => {
      if (typeof path4 === "string") {
        path4 = [path4];
      }
      const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
      const result = path4.reduce((result2, cur) => {
        const globbed = glob.sync(`${prefix2}${cur}`);
        globbed.forEach((it) => {
          const fileName = import_fs4.default.lstatSync(it).isDirectory() ? null : import_path4.default.resolve(it);
          const filenames = fileName ? [fileName] : import_fs4.default.readdirSync(it).map((file) => import_path4.default.join(import_path4.default.resolve(it), file));
          filenames.filter((file) => !import_fs4.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 [${path4.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 import_crypto, import_fs5, prepareMySqlDbPushSnapshot, prepareSingleStoreDbPushSnapshot, prepareSQLiteDbPushSnapshot, prepareMySqlMigrationSnapshot, prepareSingleStoreMigrationSnapshot, prepareSqliteMigrationSnapshot, fillPgSnapshot, preparePgMigrationSnapshot, preparePrevSnapshot;
var init_migrationPreparator = __esm({
  "src/migrationPreparator.ts"() {
    "use strict";
    import_crypto = require("crypto");
    import_fs5 = __toESM(require("fs"));
    init_serializer();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    prepareMySqlDbPushSnapshot = async (prev, schemaPath, casing2) => {
      const serialized = await serializeMySql(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prev.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      return { prev, cur: result };
    };
    prepareSingleStoreDbPushSnapshot = async (prev, schemaPath, casing2) => {
      const serialized = await serializeSingleStore(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prev.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      return { prev, cur: result };
    };
    prepareSQLiteDbPushSnapshot = async (prev, schemaPath, casing2) => {
      const serialized = await serializeSQLite(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prev.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = {
        version: version3,
        dialect: dialect6,
        id,
        prevId: idPrev,
        ...rest
      };
      return { prev, cur: result };
    };
    prepareMySqlMigrationSnapshot = async (migrationFolders, schemaPath, casing2) => {
      const prevSnapshot = mysqlSchema.parse(
        preparePrevSnapshot(migrationFolders, dryMySql)
      );
      const serialized = await serializeMySql(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = {
        id,
        prevId: idPrev,
        ...prevRest
      };
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    prepareSingleStoreMigrationSnapshot = async (migrationFolders, schemaPath, casing2) => {
      const prevSnapshot = singlestoreSchema.parse(
        preparePrevSnapshot(migrationFolders, drySingleStore)
      );
      const serialized = await serializeSingleStore(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = {
        id,
        prevId: idPrev,
        ...prevRest
      };
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    prepareSqliteMigrationSnapshot = async (snapshots, schemaPath, casing2) => {
      const prevSnapshot = sqliteSchema.parse(
        preparePrevSnapshot(snapshots, drySQLite)
      );
      const serialized = await serializeSQLite(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const { version: version3, dialect: dialect6, ...rest } = serialized;
      const result = {
        version: version3,
        dialect: dialect6,
        id,
        prevId: idPrev,
        ...rest
      };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = {
        id,
        prevId: idPrev,
        ...prevRest
      };
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    fillPgSnapshot = ({
      serialized,
      id,
      idPrev
    }) => {
      return { id, prevId: idPrev, ...serialized };
    };
    preparePgMigrationSnapshot = async (snapshots, schemaPath, casing2) => {
      const prevSnapshot = pgSchema.parse(preparePrevSnapshot(snapshots, dryPg));
      const serialized = await serializePg(schemaPath, casing2);
      const id = (0, import_crypto.randomUUID)();
      const idPrev = prevSnapshot.id;
      const result = { id, prevId: idPrev, ...serialized };
      const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
      const custom2 = fillPgSnapshot({ serialized: prevRest, id, idPrev });
      return { prev: prevSnapshot, cur: result, custom: custom2 };
    };
    preparePrevSnapshot = (snapshots, defaultPrev) => {
      let prevSnapshot;
      if (snapshots.length === 0) {
        prevSnapshot = defaultPrev;
      } else {
        const lastSnapshot = snapshots[snapshots.length - 1];
        prevSnapshot = JSON.parse(import_fs5.default.readFileSync(lastSnapshot).toString());
      }
      return prevSnapshot;
    };
  }
});

// ../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) {
    (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(x2, y) {
        if (x2 < y) {
          return -1;
        }
        if (x2 > y) {
          return 1;
        }
        return 0;
      };
      insort = function(a, x2, 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 = a.length;
        }
        while (lo < hi) {
          mid = floor((lo + hi) / 2);
          if (cmp(x2, a[mid]) < 0) {
            hi = mid;
          } else {
            lo = mid + 1;
          }
        }
        return [].splice.apply(a, [lo, lo - lo].concat(x2)), x2;
      };
      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 i2, _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++) {
          i2 = _ref1[_i];
          _results.push(_siftup(array2, i2, 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, n, cmp) {
        var elem, result, _i, _len, _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        result = array2.slice(0, n);
        if (!result.length) {
          return result;
        }
        heapify(result, cmp);
        _ref = array2.slice(n);
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          elem = _ref[_i];
          heappushpop(result, elem, cmp);
        }
        return result.sort(cmp).reverse();
      };
      nsmallest = function(array2, n, cmp) {
        var elem, i2, los, result, _i, _j, _len, _ref, _ref1, _results;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (n * 10 <= array2.length) {
          result = array2.slice(0, n).sort(cmp);
          if (!result.length) {
            return result;
          }
          los = result[result.length - 1];
          _ref = array2.slice(n);
          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 (i2 = _j = 0, _ref1 = min(n, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i2 = 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(x2) {
          return heappush(this.nodes, x2, this.cmp);
        };
        Heap2.prototype.pop = function() {
          return heappop(this.nodes, this.cmp);
        };
        Heap2.prototype.peek = function() {
          return this.nodes[0];
        };
        Heap2.prototype.contains = function(x2) {
          return this.nodes.indexOf(x2) !== -1;
        };
        Heap2.prototype.replace = function(x2) {
          return heapreplace(this.nodes, x2, this.cmp);
        };
        Heap2.prototype.pushpop = function(x2) {
          return heappushpop(this.nodes, x2, this.cmp);
        };
        Heap2.prototype.heapify = function() {
          return heapify(this.nodes, this.cmp);
        };
        Heap2.prototype.updateItem = function(x2) {
          return updateItem(this.nodes, x2, 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) {
    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) {
    (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(a, b) {
        var i2, l, la, lb, ref;
        [la, lb] = [a.length, b.length];
        for (i2 = l = 0, ref = min(la, lb); 0 <= ref ? l < ref : l > ref; i2 = 0 <= ref ? ++l : --l) {
          if (a[i2] < b[i2]) {
            return -1;
          }
          if (a[i2] > b[i2]) {
            return 1;
          }
        }
        return la - lb;
      };
      _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      };
      _any = function(items) {
        var item, l, len;
        for (l = 0, len = items.length; l < len; l++) {
          item = items[l];
          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, a = "", b = "", autojunk = true) {
          this.isjunk = isjunk1;
          this.autojunk = autojunk;
          this.a = this.b = null;
          this.setSeqs(a, b);
        }
        setSeqs(a, b) {
          this.setSeq1(a);
          return this.setSeq2(b);
        }
        setSeq1(a) {
          if (a === this.a) {
            return;
          }
          this.a = a;
          return this.matchingBlocks = this.opcodes = null;
        }
        setSeq2(b) {
          if (b === this.b) {
            return;
          }
          this.b = b;
          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 b, b2j, elt, i2, indices, isjunk, junk, l, len, n, ntest, popular;
          b = this.b;
          this.b2j = b2j = /* @__PURE__ */ new Map();
          for (i2 = l = 0, len = b.length; l < len; i2 = ++l) {
            elt = b[i2];
            if (!b2j.has(elt)) {
              b2j.set(elt, []);
            }
            indices = b2j.get(elt);
            indices.push(i2);
          }
          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();
          n = b.length;
          if (this.autojunk && n >= 200) {
            ntest = floor(n / 100) + 1;
            b2j.forEach(function(idxs, elt2) {
              if (idxs.length > ntest) {
                popular.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          this.isbjunk = function(b2) {
            return junk.has(b2);
          };
          return this.isbpopular = function(b2) {
            return popular.has(b2);
          };
        }
        findLongestMatch(alo, ahi, blo, bhi) {
          var a, b, b2j, besti, bestj, bestsize, i2, isbjunk, j, j2len, jlist, k, l, len, m2, newj2len, ref, ref1;
          [a, b, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk];
          [besti, bestj, bestsize] = [alo, blo, 0];
          j2len = {};
          for (i2 = l = ref = alo, ref1 = ahi; ref <= ref1 ? l < ref1 : l > ref1; i2 = ref <= ref1 ? ++l : --l) {
            newj2len = {};
            jlist = [];
            if (b2j.has(a[i2])) {
              jlist = b2j.get(a[i2]);
            }
            for (m2 = 0, len = jlist.length; m2 < len; m2++) {
              j = jlist[m2];
              if (j < blo) {
                continue;
              }
              if (j >= bhi) {
                break;
              }
              k = newj2len[j] = (j2len[j - 1] || 0) + 1;
              if (k > bestsize) {
                [besti, bestj, bestsize] = [i2 - k + 1, j - k + 1, k];
              }
            }
            j2len = newj2len;
          }
          while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
            bestsize++;
          }
          while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
            bestsize++;
          }
          return [besti, bestj, bestsize];
        }
        getMatchingBlocks() {
          var ahi, alo, bhi, blo, i2, i1, i22, j, j1, j2, k, k1, k2, l, la, lb, len, matchingBlocks, nonAdjacent, queue, x2;
          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();
            [i2, j, k] = x2 = this.findLongestMatch(alo, ahi, blo, bhi);
            if (k) {
              matchingBlocks.push(x2);
              if (alo < i2 && blo < j) {
                queue.push([alo, i2, blo, j]);
              }
              if (i2 + k < ahi && j + k < bhi) {
                queue.push([i2 + k, ahi, j + k, bhi]);
              }
            }
          }
          matchingBlocks.sort(_arrayCmp);
          i1 = j1 = k1 = 0;
          nonAdjacent = [];
          for (l = 0, len = matchingBlocks.length; l < len; l++) {
            [i22, j2, k2] = matchingBlocks[l];
            if (i1 + k1 === i22 && j1 + k1 === j2) {
              k1 += k2;
            } else {
              if (k1) {
                nonAdjacent.push([i1, j1, k1]);
              }
              [i1, j1, k1] = [i22, j2, k2];
            }
          }
          if (k1) {
            nonAdjacent.push([i1, j1, k1]);
          }
          nonAdjacent.push([la, lb, 0]);
          return this.matchingBlocks = nonAdjacent;
        }
        getOpcodes() {
          var ai, answer, bj, i2, j, l, len, ref, size, tag;
          if (this.opcodes) {
            return this.opcodes;
          }
          i2 = j = 0;
          this.opcodes = answer = [];
          ref = this.getMatchingBlocks();
          for (l = 0, len = ref.length; l < len; l++) {
            [ai, bj, size] = ref[l];
            tag = "";
            if (i2 < ai && j < bj) {
              tag = "replace";
            } else if (i2 < ai) {
              tag = "delete";
            } else if (j < bj) {
              tag = "insert";
            }
            if (tag) {
              answer.push([tag, i2, ai, j, bj]);
            }
            [i2, j] = [ai + size, bj + size];
            if (size) {
              answer.push(["equal", ai, i2, bj, j]);
            }
          }
          return answer;
        }
        getGroupedOpcodes(n = 3) {
          var codes, group, groups, i1, i2, j1, j2, l, len, nn, tag;
          codes = this.getOpcodes();
          if (!codes.length) {
            codes = [["equal", 0, 1, 0, 1]];
          }
          if (codes[0][0] === "equal") {
            [tag, i1, i2, j1, j2] = codes[0];
            codes[0] = [tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2];
          }
          if (codes[codes.length - 1][0] === "equal") {
            [tag, i1, i2, j1, j2] = codes[codes.length - 1];
            codes[codes.length - 1] = [tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)];
          }
          nn = n + n;
          groups = [];
          group = [];
          for (l = 0, len = codes.length; l < len; l++) {
            [tag, i1, i2, j1, j2] = codes[l];
            if (tag === "equal" && i2 - i1 > nn) {
              group.push([tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)]);
              groups.push(group);
              group = [];
              [i1, j1] = [max(i1, i2 - n), max(j1, j2 - n)];
            }
            group.push([tag, i1, i2, j1, j2]);
          }
          if (group.length && !(group.length === 1 && group[0][0] === "equal")) {
            groups.push(group);
          }
          return groups;
        }
        ratio() {
          var l, len, match2, matches, ref;
          matches = 0;
          ref = this.getMatchingBlocks();
          for (l = 0, len = ref.length; l < len; l++) {
            match2 = ref[l];
            matches += match2[2];
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        quickRatio() {
          var avail, elt, fullbcount, l, len, len1, m2, matches, numb, ref, ref1;
          if (!this.fullbcount) {
            this.fullbcount = fullbcount = {};
            ref = this.b;
            for (l = 0, len = ref.length; l < len; l++) {
              elt = ref[l];
              fullbcount[elt] = (fullbcount[elt] || 0) + 1;
            }
          }
          fullbcount = this.fullbcount;
          avail = {};
          matches = 0;
          ref1 = this.a;
          for (m2 = 0, len1 = ref1.length; m2 < len1; m2++) {
            elt = ref1[m2];
            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, n = 3, cutoff = 0.6) {
        var l, len, len1, m2, result, results, s2, score, x2;
        if (!(n > 0)) {
          throw new Error(`n must be > 0: (${n})`);
        }
        if (!(0 <= cutoff && cutoff <= 1)) {
          throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`);
        }
        result = [];
        s2 = new SequenceMatcher();
        s2.setSeq2(word);
        for (l = 0, len = possibilities.length; l < len; l++) {
          x2 = possibilities[l];
          s2.setSeq1(x2);
          if (s2.realQuickRatio() >= cutoff && s2.quickRatio() >= cutoff && s2.ratio() >= cutoff) {
            result.push([s2.ratio(), x2]);
          }
        }
        result = Heap.nlargest(result, n, _arrayCmp);
        results = [];
        for (m2 = 0, len1 = result.length; m2 < len1; m2++) {
          [score, x2] = result[m2];
          results.push(x2);
        }
        return results;
      };
      _countLeading = function(line, ch) {
        var i2, n;
        [i2, n] = [0, line.length];
        while (i2 < n && line[i2] === ch) {
          i2++;
        }
        return i2;
      };
      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(a, b) {
          var ahi, alo, bhi, blo, cruncher, g, l, len, len1, line, lines, m2, ref, tag;
          cruncher = new SequenceMatcher(this.linejunk, a, b);
          lines = [];
          ref = cruncher.getOpcodes();
          for (l = 0, len = ref.length; l < len; l++) {
            [tag, alo, ahi, blo, bhi] = ref[l];
            switch (tag) {
              case "replace":
                g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
                break;
              case "delete":
                g = this._dump("-", a, alo, ahi);
                break;
              case "insert":
                g = this._dump("+", b, blo, bhi);
                break;
              case "equal":
                g = this._dump(" ", a, alo, ahi);
                break;
              default:
                throw new Error(`unknow tag (${tag})`);
            }
            for (m2 = 0, len1 = g.length; m2 < len1; m2++) {
              line = g[m2];
              lines.push(line);
            }
          }
          return lines;
        }
        _dump(tag, x2, lo, hi) {
          var i2, l, ref, ref1, results;
          results = [];
          for (i2 = l = ref = lo, ref1 = hi; ref <= ref1 ? l < ref1 : l > ref1; i2 = ref <= ref1 ? ++l : --l) {
            results.push(`${tag} ${x2[i2]}`);
          }
          return results;
        }
        _plainReplace(a, alo, ahi, b, blo, bhi) {
          var first, g, l, len, len1, line, lines, m2, ref, second;
          assert(alo < ahi && blo < bhi);
          if (bhi - blo < ahi - alo) {
            first = this._dump("+", b, blo, bhi);
            second = this._dump("-", a, alo, ahi);
          } else {
            first = this._dump("-", a, alo, ahi);
            second = this._dump("+", b, blo, bhi);
          }
          lines = [];
          ref = [first, second];
          for (l = 0, len = ref.length; l < len; l++) {
            g = ref[l];
            for (m2 = 0, len1 = g.length; m2 < len1; m2++) {
              line = g[m2];
              lines.push(line);
            }
          }
          return lines;
        }
        _fancyReplace(a, alo, ahi, b, blo, bhi) {
          var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i2, j, l, la, lb, len, len1, len2, len3, len4, line, lines, m2, o, p, q, r2, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t2, 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 (j = l = ref = blo, ref1 = bhi; ref <= ref1 ? l < ref1 : l > ref1; j = ref <= ref1 ? ++l : --l) {
            bj = b[j];
            cruncher.setSeq2(bj);
            for (i2 = m2 = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m2 < ref3 : m2 > ref3; i2 = ref2 <= ref3 ? ++m2 : --m2) {
              ai = a[i2];
              if (ai === bj) {
                if (eqi === null) {
                  [eqi, eqj] = [i2, j];
                }
                continue;
              }
              cruncher.setSeq1(ai);
              if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
                [bestRatio, besti, bestj] = [cruncher.ratio(), i2, j];
              }
            }
          }
          if (bestRatio < cutoff) {
            if (eqi === null) {
              ref4 = this._plainReplace(a, alo, ahi, b, blo, bhi);
              for (o = 0, len = ref4.length; o < len; o++) {
                line = ref4[o];
                lines.push(line);
              }
              return lines;
            }
            [besti, bestj, bestRatio] = [eqi, eqj, 1];
          } else {
            eqi = null;
          }
          ref5 = this._fancyHelper(a, alo, besti, b, blo, bestj);
          for (p = 0, len1 = ref5.length; p < len1; p++) {
            line = ref5[p];
            lines.push(line);
          }
          [aelt, belt] = [a[besti], b[bestj]];
          if (eqi === null) {
            atags = btags = "";
            cruncher.setSeqs(aelt, belt);
            ref6 = cruncher.getOpcodes();
            for (q = 0, len2 = ref6.length; q < len2; q++) {
              [tag, ai1, ai2, bj1, bj2] = ref6[q];
              [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 (r2 = 0, len3 = ref7.length; r2 < len3; r2++) {
              line = ref7[r2];
              lines.push(line);
            }
          } else {
            lines.push("  " + aelt);
          }
          ref8 = this._fancyHelper(a, besti + 1, ahi, b, bestj + 1, bhi);
          for (t2 = 0, len4 = ref8.length; t2 < len4; t2++) {
            line = ref8[t2];
            lines.push(line);
          }
          return lines;
        }
        _fancyHelper(a, alo, ahi, b, blo, bhi) {
          var g;
          g = [];
          if (alo < ahi) {
            if (blo < bhi) {
              g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
            } else {
              g = this._dump("-", a, alo, ahi);
            }
          } else if (blo < bhi) {
            g = this._dump("+", b, blo, bhi);
          }
          return g;
        }
        _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(a, b, { fromfile, tofile, fromfiledate, tofiledate, n, lineterm } = {}) {
        var file1Range, file2Range, first, fromdate, group, i1, i2, j1, j2, l, last, len, len1, len2, len3, len4, line, lines, m2, o, p, q, ref, ref1, ref2, ref3, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n == null) {
          n = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        lines = [];
        started = false;
        ref = new SequenceMatcher(null, a, b).getGroupedOpcodes();
        for (l = 0, len = ref.length; l < len; l++) {
          group = ref[l];
          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 (m2 = 0, len1 = group.length; m2 < len1; m2++) {
            [tag, i1, i2, j1, j2] = group[m2];
            if (tag === "equal") {
              ref1 = a.slice(i1, i2);
              for (o = 0, len2 = ref1.length; o < len2; o++) {
                line = ref1[o];
                lines.push(" " + line);
              }
              continue;
            }
            if (tag === "replace" || tag === "delete") {
              ref2 = a.slice(i1, i2);
              for (p = 0, len3 = ref2.length; p < len3; p++) {
                line = ref2[p];
                lines.push("-" + line);
              }
            }
            if (tag === "replace" || tag === "insert") {
              ref3 = b.slice(j1, j2);
              for (q = 0, len4 = ref3.length; q < len4; q++) {
                line = ref3[q];
                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(a, b, { fromfile, tofile, fromfiledate, tofiledate, n, lineterm } = {}) {
        var _2, file1Range, file2Range, first, fromdate, group, i1, i2, j1, j2, l, last, len, len1, len2, len3, len4, line, lines, m2, o, p, prefix2, q, ref, ref1, ref2, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n == null) {
          n = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        prefix2 = {
          insert: "+ ",
          delete: "- ",
          replace: "! ",
          equal: "  "
        };
        started = false;
        lines = [];
        ref = new SequenceMatcher(null, a, b).getGroupedOpcodes();
        for (l = 0, len = ref.length; l < len; l++) {
          group = ref[l];
          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, m3, results;
              results = [];
              for (m3 = 0, len12 = group.length; m3 < len12; m3++) {
                [tag, _2, _2, _2, _2] = group[m3];
                results.push(tag === "replace" || tag === "delete");
              }
              return results;
            }())) {
              for (m2 = 0, len1 = group.length; m2 < len1; m2++) {
                [tag, i1, i2, _2, _2] = group[m2];
                if (tag !== "insert") {
                  ref1 = a.slice(i1, i2);
                  for (o = 0, len2 = ref1.length; o < len2; o++) {
                    line = ref1[o];
                    lines.push(prefix2[tag] + line);
                  }
                }
              }
            }
            file2Range = _formatRangeContext(first[3], last[4]);
            lines.push(`--- ${file2Range} ----${lineterm}`);
            if (_any(function() {
              var len32, p2, results;
              results = [];
              for (p2 = 0, len32 = group.length; p2 < len32; p2++) {
                [tag, _2, _2, _2, _2] = group[p2];
                results.push(tag === "replace" || tag === "insert");
              }
              return results;
            }())) {
              for (p = 0, len3 = group.length; p < len3; p++) {
                [tag, _2, _2, j1, j2] = group[p];
                if (tag !== "delete") {
                  ref2 = b.slice(j1, j2);
                  for (q = 0, len4 = ref2.length; q < len4; q++) {
                    line = ref2[q];
                    lines.push(prefix2[tag] + line);
                  }
                }
              }
            }
          }
        }
        return lines;
      };
      ndiff = function(a, b, linejunk, charjunk = IS_CHARACTER_JUNK) {
        return new Differ(linejunk, charjunk).compare(a, b);
      };
      restore = function(delta, which) {
        var l, 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 (l = 0, len = delta.length; l < len; l++) {
          line = delta[l];
          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) {
    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) {
    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((x2) => roundObj(x2, 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) {
    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_flag2 = __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_flag2();
    var env3 = 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 env3) {
      forceColor = env3.FORCE_COLOR.length === 0 || parseInt(env3.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 env3) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
          return sign in env3;
        }) || env3.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env3) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
      }
      if ("TERM_PROGRAM" in env3) {
        var version3 = parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env3.TERM_PROGRAM) {
          case "iTerm.app":
            return version3 >= 3 ? 3 : 2;
          case "Hyper":
            return 3;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env3.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env3) {
        return 1;
      }
      if (env3.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) {
    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(c) {
        c = c.toLowerCase();
        var chars = trap[c] || [" "];
        var rand = Math.floor(Math.random() * chars.length);
        if (typeof trap[c] !== "undefined") {
          result += trap[c][rand];
        } else {
          result += c;
        }
      });
      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) {
    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 r2 = Math.floor(Math.random() * range);
        return r2;
      }
      function isChar(character) {
        var bool = false;
        all.filter(function(i2) {
          bool = i2 === character;
        });
        return bool;
      }
      function heComes(text2, options2) {
        var result = "";
        var counts;
        var l;
        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 (l in text2) {
          if (isChar(l)) {
            continue;
          }
          result = result + text2[l];
          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 d in arr) {
            var index5 = arr[d];
            for (var i2 = 0; i2 <= counts[index5]; i2++) {
              if (options2[index5]) {
                result = result + soul[index5][randomNumber(soul[index5].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) {
    module2["exports"] = function(colors) {
      return function(letter, i2, exploded) {
        if (letter === " ")
          return letter;
        switch (i2 % 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) {
    module2["exports"] = function(colors) {
      return function(letter, i2, exploded) {
        return i2 % 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) {
    module2["exports"] = function(colors) {
      var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
      return function(letter, i2, exploded) {
        if (letter === " ") {
          return letter;
        } else {
          return colors[rainbowColors[i2++ % 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) {
    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, i2, 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) {
    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 i2 = nestedStyles.length;
      while (i2--) {
        var code = ansiStyles2[nestedStyles[i2]];
        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 i2 in theme[style2]) {
                out = colors[theme[style2][i2]](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(map2, str) {
      var exploded = str.split("");
      exploded = exploded.map(map2);
      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 (map in colors.maps) {
      (function(map2) {
        colors[map2] = function(str) {
          return sequencer(colors.maps[map2], str);
        };
      })(map);
    }
    var map;
    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) {
    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) {
    var color = require_safe();
    var { extendedTypeOf } = require_util();
    var Theme = {
      " "(s2) {
        return s2;
      },
      "+": color.green,
      "-": color.red
    };
    var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) {
      let subvalue;
      const prefix2 = key ? `${key}: ` : "";
      const subindent = indent + "  ";
      const outputElisions = (n) => {
        const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions;
        if (n < maxElisions) {
          for (let i2 = 0; i2 < n; i2++) {
            output(" ", subindent + "...");
          }
        } else {
          output(" ", subindent + `... (${n} 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 m2;
              subvalue = diff2[subkey];
              if (m2 = subkey.match(/^(.*)__deleted$/)) {
                subcolorizeToCallback(options, m2[1], subvalue, output, "-", subindent);
              } else if (m2 = subkey.match(/^(.*)__added$/)) {
                subcolorizeToCallback(options, m2[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) {
    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, index5, fuzzyOriginals) {
        let bestMatch = null;
        for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
          if (key !== "__next") {
            const indexDistance = Math.abs(matchIndex - index5);
            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 index5 = 0; index5 < array2.length; index5++) {
            const item = array2[index5];
            if (this.isScalar(item)) {
              continue;
            }
            const bestMatch = this.findMatchingObject(item, index5, fuzzyOriginals);
            if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
              keyScores[bestMatch.key] = { score: bestMatch.score, index: index5 };
            }
          }
          for (const [key, match2] of Object.entries(keyScores)) {
            fuzzyMatches[match2.index] = key;
          }
        }
        const result = [];
        for (let index5 = 0; index5 < array2.length; index5++) {
          const item = array2[index5];
          if (this.isScalar(item)) {
            result.push(item);
          } else {
            const key = fuzzyMatches[index5] || "__$!SCALAR" + originals.__next++;
            originals[key] = { item, index: index5 };
            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, i2, j1, j2] of opcodes) {
          let i3, j;
          let asc, end;
          let asc1, end1;
          let asc2, end2;
          if (!(op === "equal" || this.options.keysOnly && op === "replace")) {
            equal = false;
          }
          switch (op) {
            case "equal":
              for (i3 = i1, end = i2, asc = i1 <= end; asc ? i3 < end : i3 > end; asc ? i3++ : i3--) {
                const item = seq1[i3];
                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 (i3 = i1, end1 = i2, asc1 = i1 <= end1; asc1 ? i3 < end1 : i3 > end1; asc1 ? i3++ : i3--) {
                result.push(["-", this.descalarize(seq1[i3], originals1)]);
                score -= 5;
              }
              break;
            case "insert":
              for (j = j1, end2 = j2, asc2 = j1 <= end2; asc2 ? j < end2 : j > end2; asc2 ? j++ : j--) {
                result.push(["+", this.descalarize(seq2[j], originals2)]);
                score -= 5;
              }
              break;
            case "replace":
              if (!this.options.keysOnly) {
                let asc3, end3;
                let asc4, end4;
                for (i3 = i1, end3 = i2, asc3 = i1 <= end3; asc3 ? i3 < end3 : i3 > end3; asc3 ? i3++ : i3--) {
                  result.push(["-", this.descalarize(seq1[i3], originals1)]);
                  score -= 5;
                }
                for (j = j1, end4 = j2, asc4 = j1 <= end4; asc4 ? j < end4 : j > end4; asc4 ? j++ : j--) {
                  result.push(["+", this.descalarize(seq2[j], originals2)]);
                  score -= 5;
                }
              } else {
                let asc5, end5;
                for (i3 = i1, end5 = i2, asc5 = i1 <= end5; asc5 ? i3 < end5 : i3 > end5; asc5 ? i3++ : i3--) {
                  const change = this.diff(
                    this.descalarize(seq1[i3], originals1),
                    this.descalarize(seq2[i3 - 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 table5 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table5.name, schema: table5.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 table5 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table5.name, schema: table5.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 table5 = json1.tables[key];
    difference.tables[key] = {
      name: table5.name,
      schema: table5.schema,
      ...difference.tables[key]
    };
  }
  for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
    const table5 = 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 table5.columns[key];
        continue;
      }
    }
    if (Object.keys(columns).length === 0) {
      delete table5["columns"];
    }
    if ("name" in table5 && "schema" in table5 && Object.keys(table5).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, view4]) => {
      const deletedWithOption = view4.with__deleted;
      const addedWithOption = view4.with__added;
      const deletedWith = Object.fromEntries(
        Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
          return [key.replace("__deleted", ""), value];
        })
      );
      const addedWith = Object.fromEntries(
        Object.entries(view4.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
          return [key.replace("__added", ""), value];
        })
      );
      const alterWith = Object.fromEntries(
        Object.entries(view4.with || {}).filter(
          (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
        ).map(
          (it) => {
            return [it[0], it[1].__new];
          }
        )
      );
      const alteredSchema = view4.schema;
      const alteredDefinition = view4.definition;
      const alteredExisting = view4.isExisting;
      const addedTablespace = view4.tablespace__added;
      const droppedTablespace = view4.tablespace__deleted;
      const alterTablespaceTo = view4.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 = view4.using__added;
      const droppedUsing = view4.using__deleted;
      const alterUsingTo = view4.using;
      let alteredUsing;
      if (addedUsing)
        alteredUsing = { __new: addedUsing, __old: "heap" };
      if (droppedUsing)
        alteredUsing = { __new: "heap", __old: droppedUsing };
      if (alterUsingTo)
        alteredUsing = alterUsingTo;
      const alteredMeta = view4.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(([_2, value]) => value !== void 0)
      );
    }
  );
  const alteredTablesWithColumns = Object.values(difference.tables).map(
    (table5) => {
      return findAlternationsInTable(table5);
    }
  );
  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 i2 = 0; i2 < diff2.length; i2++) {
        const it = diff2[i2];
        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 = (table5) => {
      const columns = table5.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(table5.indexes__deleted || {}).concat(
          Object.entries(table5.indexes || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedIndexes = Object.fromEntries(
        Object.entries(table5.indexes__added || {}).concat(
          Object.entries(table5.indexes || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredIndexes = Object.fromEntries(
        Object.entries(table5.indexes || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedPolicies = Object.fromEntries(
        Object.entries(table5.policies__deleted || {}).concat(
          Object.entries(table5.policies || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedPolicies = Object.fromEntries(
        Object.entries(table5.policies__added || {}).concat(
          Object.entries(table5.policies || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredPolicies = Object.fromEntries(
        Object.entries(table5.policies || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedForeignKeys = Object.fromEntries(
        Object.entries(table5.foreignKeys__deleted || {}).concat(
          Object.entries(table5.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedForeignKeys = Object.fromEntries(
        Object.entries(table5.foreignKeys__added || {}).concat(
          Object.entries(table5.foreignKeys || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredForeignKeys = Object.fromEntries(
        Object.entries(table5.foreignKeys || {}).filter(
          (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
        ).map((entry) => [entry[0], entry[1]])
      );
      const addedCompositePKs = Object.fromEntries(
        Object.entries(table5.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCompositePKs = Object.fromEntries(
        Object.entries(table5.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCompositePKs = Object.fromEntries(
        Object.entries(table5.compositePrimaryKeys || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedUniqueConstraints = Object.fromEntries(
        Object.entries(table5.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedUniqueConstraints = Object.fromEntries(
        Object.entries(table5.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredUniqueConstraints = Object.fromEntries(
        Object.entries(table5.uniqueConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedCheckConstraints = Object.fromEntries(
        Object.entries(table5.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCheckConstraints = Object.fromEntries(
        Object.entries(table5.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCheckConstraints = Object.fromEntries(
        Object.entries(table5.checkConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
      return {
        name: table5.name,
        schema: table5.schema || "",
        altered: mappedAltered,
        addedIndexes,
        deletedIndexes,
        alteredIndexes,
        addedForeignKeys,
        deletedForeignKeys,
        alteredForeignKeys,
        addedCompositePKs,
        deletedCompositePKs,
        alteredCompositePKs,
        addedUniqueConstraints,
        deletedUniqueConstraints,
        alteredUniqueConstraints,
        deletedPolicies,
        addedPolicies,
        alteredPolicies,
        addedCheckConstraints,
        deletedCheckConstraints,
        alteredCheckConstraints
      };
    };
    alternationsInColumn = (column9) => {
      const altered = [column9];
      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_utils2();
    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"
      ];
      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) {
        var _a, _b, _c;
        const policy4 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = policy4.using ? ` USING (${policy4.using})` : "";
        const withCheckPart = policy4.withCheck ? ` WITH CHECK (${policy4.withCheck})` : "";
        const policyToPart = (_a = policy4.to) == null ? void 0 : _a.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy4.name}" ON ${tableNameWithSchema} AS ${(_b = policy4.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy4.for) == null ? void 0 : _c.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy4 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `DROP POLICY "${policy4.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) {
        var _a, _b, _c;
        const policy4 = statement.data;
        const usingPart = policy4.using ? ` USING (${policy4.using})` : "";
        const withCheckPart = policy4.withCheck ? ` WITH CHECK (${policy4.withCheck})` : "";
        const policyToPart = (_a = policy4.to) == null ? void 0 : _a.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy4.name}" ON ${policy4.on} AS ${(_b = policy4.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy4.for) == null ? void 0 : _c.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy4 = statement.data;
        return `DROP POLICY "${policy4.name}" ON ${policy4.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 i2 = 0; i2 < columns.length; i2++) {
          const column9 = columns[i2];
          const primaryKeyStatement = column9.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column9.notNull && !column9.identity ? " NOT NULL" : "";
          const defaultStatement = column9.default !== void 0 ? ` DEFAULT ${column9.default}` : "";
          const uniqueConstraint5 = column9.isUnique ? ` CONSTRAINT "${column9.uniqueName}" UNIQUE${column9.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
          const schemaPrefix = column9.typeSchema && column9.typeSchema !== "public" ? `"${column9.typeSchema}".` : "";
          const type = parseType(schemaPrefix, column9.type);
          const generated = column9.generated;
          const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) STORED` : "";
          const unsquashedIdentity = column9.identity ? PgSquasher.unsquashIdentity(column9.identity) : void 0;
          const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : 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 += `	"${column9.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint5}${identity}`;
          statement += i2 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK5 = PgSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK5.columns.join(`","`)}")`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint5);
            statement += `	CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint4 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint4);
            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) {
        var _a, _b;
        const {
          tableName,
          columns,
          schema: schema6,
          checkConstraints,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i2 = 0; i2 < columns.length; i2++) {
          const column9 = columns[i2];
          const primaryKeyStatement = column9.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column9.notNull ? " NOT NULL" : "";
          const defaultStatement = column9.default !== void 0 ? ` DEFAULT ${column9.default}` : "";
          const onUpdateStatement = column9.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column9.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column9.generated ? ` GENERATED ALWAYS AS (${(_a = column9.generated) == null ? void 0 : _a.as}) ${(_b = column9.generated) == null ? void 0 : _b.type.toUpperCase()}` : "";
          statement += `	\`${column9.name}\` ${column9.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
          statement += i2 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK5 = MySqlSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK5.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint5);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              var _a2, _b2;
              return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a2 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a2.columns[it]) == null ? void 0 : _b2.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint4 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint4);
            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) {
        var _a, _b;
        const {
          tableName,
          columns,
          schema: schema6,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i2 = 0; i2 < columns.length; i2++) {
          const column9 = columns[i2];
          const primaryKeyStatement = column9.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column9.notNull ? " NOT NULL" : "";
          const defaultStatement = column9.default !== void 0 ? ` DEFAULT ${column9.default}` : "";
          const onUpdateStatement = column9.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column9.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column9.generated ? ` GENERATED ALWAYS AS (${(_a = column9.generated) == null ? void 0 : _a.as}) ${(_b = column9.generated) == null ? void 0 : _b.type.toUpperCase()}` : "";
          statement += `	\`${column9.name}\` ${column9.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`;
          statement += i2 === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK5 = SingleStoreSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${compositePK5.name}\` PRIMARY KEY(\`${compositePK5.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint5);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              var _a2, _b2;
              return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a2 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a2.columns[it]) == null ? void 0 : _b2.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 i2 = 0; i2 < columns.length; i2++) {
          const column9 = columns[i2];
          const primaryKeyStatement = column9.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column9.notNull ? " NOT NULL" : "";
          const defaultStatement = column9.default !== void 0 ? ` DEFAULT ${column9.default}` : "";
          const autoincrementStatement = column9.autoincrement ? " AUTOINCREMENT" : "";
          const generatedStatement = column9.generated ? ` GENERATED ALWAYS AS ${column9.generated.as} ${column9.generated.type.toUpperCase()}` : "";
          statement += "	";
          statement += `\`${column9.name}\` ${column9.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`;
          statement += i2 === columns.length - 1 ? "" : ",\n";
        }
        compositePKs.forEach((it) => {
          statement += ",\n	";
          statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`;
        });
        for (let i2 = 0; i2 < referenceData.length; i2++) {
          const {
            name,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          } = referenceData[i2];
          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 uniqueConstraint5 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint5);
            statement += `	CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const check2 of checkConstraints) {
            statement += ",\n";
            const { value, name } = SQLiteSquasher.unsquashCheck(check2);
            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 == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : 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, 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}` : ""}${cache ? ` CACHE ${cache}` : ""}${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, schema: schema6 } = st;
        const statements = [];
        for (const withEnum of columnsWithEnum) {
          statements.push(
            `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
          );
        }
        statements.push(new DropTypeEnumConvertor().convert({ name, schema: schema6, type: "drop_type_enum" }));
        statements.push(new CreateTypeEnumConvertor().convert({
          name,
          schema: schema6,
          values: newValues,
          type: "create_type_enum"
        }));
        for (const withEnum of columnsWithEnum) {
          statements.push(
            `ALTER TABLE "${withEnum.schema}"."${withEnum.table}" ALTER COLUMN "${withEnum.column}" SET DATA TYPE "${schema6}"."${name}" USING "${withEnum.column}"::"${schema6}"."${name}";`
          );
        }
        return statements;
      }
    };
    PgDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "postgresql";
      }
      convert(statement, _d, action) {
        const { tableName, schema: schema6, policies } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const dropPolicyConvertor = new PgDropPolicyConvertor();
        const droppedPolicies = (policies == null ? void 0 : policies.map((p) => {
          return dropPolicyConvertor.convert({
            type: "drop_policy",
            tableName,
            data: action === "push" ? PgSquasher.unsquashPolicyPush(p) : PgSquasher.unsquashPolicy(p),
            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: column9, schema: schema6 } = statement;
        const { name, type, notNull, generated, primaryKey, identity } = column9;
        const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        const defaultStatement = `${column9.default !== void 0 ? ` DEFAULT ${column9.default}` : ""}`;
        const schemaPrefix = column9.typeSchema && column9.typeSchema !== "public" ? `"${column9.typeSchema}".` : "";
        const fixedType = parseType(schemaPrefix, column9.type);
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
        const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : 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 == null ? void 0 : 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: column9 } = statement;
        const {
          name,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column9;
        const defaultStatement = `${column9.default !== void 0 ? ` DEFAULT ${column9.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 == null ? void 0 : generated.as}) ${generated == null ? void 0 : 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: column9 } = statement;
        const {
          name,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column9;
        const defaultStatement = `${column9.default !== void 0 ? ` DEFAULT ${column9.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 == null ? void 0 : generated.as}) ${generated == null ? void 0 : 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: column9, referenceData } = statement;
        const { name, type, notNull, primaryKey, generated } = column9;
        const defaultStatement = `${column9.default !== void 0 ? ` DEFAULT ${column9.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 === "alter_table_alter_column_set_type" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, newDataType, schema: schema6 } = statement;
        const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${newDataType};`;
      }
    };
    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 table5 of Object.values(json2.tables)) {
          for (const index5 of Object.values(table5.indexes)) {
            const unsquashed = SQLiteSquasher.unsquashIdx(index5);
            sqlStatements.push(`DROP INDEX "${unsquashed.name}";`);
            indexes.push({ ...unsquashed, tableName: table5.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 index5 of indexes) {
          const indexPart = index5.isUnique ? "UNIQUE INDEX" : "INDEX";
          const whereStatement = index5.where ? ` WHERE ${index5.where}` : "";
          const uniqueString = index5.columns.map((it) => `\`${it}\``).join(",");
          const tableName2 = index5.tableName;
          sqlStatements.push(
            `CREATE ${indexPart} \`${index5.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) {
        var _a, _b, _c, _d, _e, _f, _g;
        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 (((_a = statement.columnGenerated) == null ? void 0 : _a.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 (${(_b = statement.columnGenerated) == null ? void 0 : _b.as}) ${(_c = statement.columnGenerated) == null ? void 0 : _c.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 (((_e = (_d = statement.oldColumn) == null ? void 0 : _d.generated) == null ? void 0 : _e.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 (${(_f = statement.columnGenerated) == null ? void 0 : _f.as}) ${(_g = statement.columnGenerated) == null ? void 0 : _g.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) {
        var _a, _b, _c, _d, _e, _f, _g;
        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 (((_a = statement.columnGenerated) == null ? void 0 : _a.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 (${(_b = statement.columnGenerated) == null ? void 0 : _b.as}) ${(_c = statement.columnGenerated) == null ? void 0 : _c.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 (((_e = (_d = statement.oldColumn) == null ? void 0 : _d.generated) == null ? void 0 : _e.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 (${(_f = statement.columnGenerated) == null ? void 0 : _f.as}) ${(_g = statement.columnGenerated) == null ? void 0 : _g.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) => {
          var _a, _b, _c, _d;
          return ((_a = statement.internal) == null ? void 0 : _a.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.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) => {
          var _a, _b, _c, _d;
          return ((_a = statement.internal) == null ? void 0 : _a.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.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) => {
          var _a, _b, _c, _d;
          return ((_a = statement.internal) == null ? void 0 : _a.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.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_utils2();
    _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(
          (c) => `"${c}"`
        );
        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 table5 of Object.values(json2.tables)) {
            const tablesRefs = Object.values(json2.tables[table5.name].foreignKeys).filter((t2) => SQLiteSquasher.unsquashPushFK(t2).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 = (table5, json2) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table5;
      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 = (table5, json2, internals) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table5;
      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 = (table5, json2, internals) => {
      const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints } = table5;
      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 = (table5, action) => {
      const { name, columns, uniqueConstraints, checkConstraints } = table5;
      const references2 = Object.values(table5.foreignKeys);
      const composites = Object.values(table5.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 = (table5) => {
      return {
        type: "drop_table",
        tableName: table5.name,
        schema: table5.schema,
        policies: table5.policies ? Object.values(table5.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 table5 = json2.tables[tableKey2];
        for (const columnKey in table5.columns) {
          const column9 = table5.columns[columnKey];
          if (column9.type === name && column9.typeSchema === schema6) {
            affectedColumns.push({ schema: table5.schema || "public", table: table5.name, column: column9.name });
          }
        }
      }
      return [{
        type: "alter_type_drop_value",
        name,
        schema: 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) => {
        var _a;
        const columnsWithReference = unsquashed.find((t2) => t2.columnsFrom.includes(it.name));
        if (((_a = it.generated) == null ? void 0 : _a.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) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column9 of columns) {
        const columnName = typeof column9.name !== "string" ? column9.name.new : column9.name;
        const table5 = json2.tables[tableName];
        const snapshotColumn = table5.columns[columnName];
        const columnType = snapshotColumn.type;
        const columnDefault = snapshotColumn.default;
        const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0;
        const columnNotNull = table5.columns[columnName].notNull;
        const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false;
        const columnPk = table5.columns[columnName].primaryKey;
        if (((_a = column9.autoincrement) == null ? void 0 : _a.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_b = column9.autoincrement) == null ? void 0 : _b.type) === "changed") {
          const type = column9.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 (((_c = column9.autoincrement) == null ? void 0 : _c.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      for (const column9 of columns) {
        const columnName = typeof column9.name !== "string" ? column9.name.new : column9.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 column9.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column9.name.old,
            newColumnName: column9.name.new,
            schema: schema6
          });
        }
        if (((_d = column9.type) == null ? void 0 : _d.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column9.type.new,
            oldDataType: column9.type.old,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_e = column9.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column9.primaryKey) == null ? void 0 : _f.type) === "changed" && !column9.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_g = column9.default) == null ? void 0 : _g.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column9.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_h = column9.default) == null ? void 0 : _h.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column9.default.new,
            oldDefaultValue: column9.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_i = column9.default) == null ? void 0 : _i.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_j = column9.notNull) == null ? void 0 : _j.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_k = column9.notNull) == null ? void 0 : _k.type) === "changed") {
          const type = column9.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 (((_l = column9.notNull) == null ? void 0 : _l.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_m = column9.generated) == null ? void 0 : _m.type) === "added") {
          if ((columnGenerated == null ? void 0 : 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 (((_n = column9.generated) == null ? void 0 : _n.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 (((_o = column9.generated) == null ? void 0 : _o.type) === "deleted") {
          if ((columnGenerated == null ? void 0 : 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 (((_p = column9.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column9.primaryKey) == null ? void 0 : _q.type) === "changed" && column9.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 (((_r = column9.onUpdate) == null ? void 0 : _r.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_s = column9.onUpdate) == null ? void 0 : _s.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, action) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
      const tableKey2 = `${schema6 || "public"}.${_tableName}`;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column9 of columns) {
        const columnName = typeof column9.name !== "string" ? column9.name.new : column9.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 compositePk = json2.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (typeof column9.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column9.name.old,
            newColumnName: column9.name.new,
            schema: schema6
          });
        }
        if (((_a = column9.type) == null ? void 0 : _a.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column9.type.new,
            oldDataType: column9.type.old,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_b = column9.primaryKey) == null ? void 0 : _b.type) === "deleted" || ((_c = column9.primaryKey) == null ? void 0 : _c.type) === "changed" && !column9.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_d = column9.default) == null ? void 0 : _d.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column9.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_e = column9.default) == null ? void 0 : _e.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column9.default.new,
            oldDefaultValue: column9.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_f = column9.default) == null ? void 0 : _f.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_g = column9.notNull) == null ? void 0 : _g.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_h = column9.notNull) == null ? void 0 : _h.type) === "changed") {
          const type = column9.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 (((_i = column9.notNull) == null ? void 0 : _i.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_j = column9.identity) == null ? void 0 : _j.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_identity",
            tableName,
            columnName,
            schema: schema6,
            identity: column9.identity.value
          });
        }
        if (((_k = column9.identity) == null ? void 0 : _k.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_change_identity",
            tableName,
            columnName,
            schema: schema6,
            identity: column9.identity.new,
            oldIdentity: column9.identity.old
          });
        }
        if (((_l = column9.identity) == null ? void 0 : _l.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_identity",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_m = column9.generated) == null ? void 0 : _m.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_n = column9.generated) == null ? void 0 : _n.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 (((_o = column9.generated) == null ? void 0 : _o.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_p = column9.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column9.primaryKey) == null ? void 0 : _q.type) === "changed" && column9.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 (((_r = column9.onUpdate) == null ? void 0 : _r.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_s = column9.onUpdate) == null ? void 0 : _s.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) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column9 of columns) {
        const columnName = typeof column9.name !== "string" ? column9.name.new : column9.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 (((_a = column9.autoincrement) == null ? void 0 : _a.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_b = column9.autoincrement) == null ? void 0 : _b.type) === "changed") {
          const type = column9.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 (((_c = column9.autoincrement) == null ? void 0 : _c.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (typeof column9.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column9.name.old,
            newColumnName: column9.name.new,
            schema: schema6
          });
        }
        if (((_d = column9.type) == null ? void 0 : _d.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column9.type.new,
            oldDataType: column9.type.old,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_e = column9.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column9.primaryKey) == null ? void 0 : _f.type) === "changed" && !column9.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema6
          });
        }
        if (((_g = column9.default) == null ? void 0 : _g.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column9.default.value,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_h = column9.default) == null ? void 0 : _h.type) === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column9.default.new,
            oldDefaultValue: column9.default.old,
            schema: schema6,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_i = column9.default) == null ? void 0 : _i.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema6,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (((_j = column9.notNull) == null ? void 0 : _j.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_k = column9.notNull) == null ? void 0 : _k.type) === "changed") {
          const type = column9.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 (((_l = column9.notNull) == null ? void 0 : _l.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_m = column9.generated) == null ? void 0 : _m.type) === "added") {
          if ((columnGenerated == null ? void 0 : 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 (((_n = column9.generated) == null ? void 0 : _n.type) === "changed") {
          if ((columnGenerated == null ? void 0 : 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 (((_o = column9.generated) == null ? void 0 : _o.type) === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (((_p = column9.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column9.primaryKey) == null ? void 0 : _q.type) === "changed" && column9.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 (((_r = column9.onUpdate) == null ? void 0 : _r.type) === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema6,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (((_s = column9.onUpdate) == null ? void 0 : _s.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, check2) => {
      return Object.values(check2).map((it) => {
        return {
          type: "create_check_constraint",
          tableName,
          data: it,
          schema: schema6
        };
      });
    };
    prepareDeleteCheckConstraint = (tableName, schema6, check2) => {
      return Object.values(check2).map((it) => {
        return {
          type: "delete_check_constraint",
          tableName,
          constraintName: PgSquasher.unsquashCheck(it).name,
          schema: schema6
        };
      });
    };
    prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
      var _a, _b;
      const res = [];
      for (const it of Object.values(pks)) {
        const unsquashed = MySqlSquasher.unsquashPK(it);
        if (unsquashed.columns.length === 1 && ((_b = (_a = json1.tables[tableName]) == null ? void 0 : _a.columns[unsquashed.columns[0]]) == null ? void 0 : _b.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 = (view4) => {
      return { type: "alter_mysql_view", ...view4 };
    };
  }
});

// src/statementCombiner.ts
var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements;
var init_statementCombiner = __esm({
  "src/statementCombiner.ts"() {
    "use strict";
    init_jsonStatements();
    init_sqliteSchema();
    prepareLibSQLRecreateTable = (table5, action) => {
      const { name, columns, uniqueConstraints, indexes, checkConstraints } = table5;
      const composites = Object.values(table5.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table5.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 = (table5, action) => {
      const { name, columns, uniqueConstraints, indexes, checkConstraints } = table5;
      const composites = Object.values(table5.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table5.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 = (table5) => {
      const { name, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table5;
      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 makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema2, 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_lib();
    init_jsonDiffer();
    init_sqlgenerator();
    init_jsonStatements();
    init_global();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    init_statementCombiner();
    init_utils2();
    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
        })
      ]);
    };
    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();
    enumSchema2 = 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: mergedViewWithOption.optional(),
        addedWithOption: mergedViewWithOption.optional(),
        addedWith: mergedViewWithOption.optional(),
        deletedWith: mergedViewWithOption.optional(),
        alteredWith: mergedViewWithOption.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: sequenceSquashed.array(),
      alteredRoles: roleSchema.array(),
      alteredPolicies: policySquashed.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 = (table5, renamedSchemas) => {
      for (let ren of renamedSchemas) {
        if (table5.schema === ren.from.name) {
          return { key: `${ren.to.name}.${table5.name}`, schema: ren.to.name };
        }
      }
      return {
        key: `${table5.schema || "public"}.${table5.name}`,
        schema: table5.schema
      };
    };
    nameChangeFor = (table5, renamed) => {
      for (let ren of renamed) {
        if (table5.name === ren.from.name) {
          return { name: ren.to.name };
        }
      }
      return {
        name: table5.name
      };
    };
    nameSchemaChangeFor = (table5, renamedTables) => {
      for (let ren of renamedTables) {
        if (table5.name === ren.from.name && table5.schema === ren.from.schema) {
          return {
            key: `${ren.to.schema || "public"}.${ren.to.name}`,
            name: ren.to.name,
            schema: ren.to.schema
          };
        }
      }
      return {
        key: `${table5.schema || "public"}.${table5.name}`,
        name: table5.name,
        schema: table5.schema
      };
    };
    columnChangeFor = (column9, renamedColumns) => {
      for (let ren of renamedColumns) {
        if (column9 === ren.from.name) {
          return ren.to.name;
        }
      }
      return column9;
    };
    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,
        (_2, it) => {
          const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
          it.schema = schema6;
          return [key, it];
        }
      );
      schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_2, 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, (_2, 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, (column9) => {
            const key = `${column9.typeSchema || "public"}.${column9.type}`;
            const change = columnTypesChangeMap[key] || columnTypesMovesMap[key];
            if (change) {
              column9.type = change.nameTo;
              column9.typeSchema = change.schemaTo;
            }
            return column9;
          });
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      schemasPatchedSnap1.sequences = mapEntries(
        schemasPatchedSnap1.sequences,
        (_2, 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,
        (_2, 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, (column9) => {
            const key = `${column9.typeSchema || "public"}.${column9.type}`;
            const change = sequencesChangeMap[key] || sequencesMovesMap[key];
            if (change) {
              column9.type = change.nameTo;
              column9.typeSchema = change.schemaTo;
            }
            return column9;
          });
          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,
        (_2, 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, (_2, 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, column9) => {
              const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(columnKey, rens);
              column9.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, policy4) => {
              const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(policyKey, rens);
              const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy4) : PgSquasher.unsquashPolicy(policy4);
              unsquashedPolicy.name = newName;
              policy4 = 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(
          (t2) => action === "push" ? PgSquasher.unsquashPolicyPush(t2.values) : PgSquasher.unsquashPolicy(t2.values)
        ),
        created: indPolicyRes.added.map(
          (t2) => action === "push" ? PgSquasher.unsquashPolicyPush(t2.values) : PgSquasher.unsquashPolicy(t2.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 k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted2[k] = it.alteredUniqueConstraints[k].__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 k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted2[k] = it.alteredCheckConstraints[k].__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,
          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 policy4 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values);
        const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy4.name].values) : PgSquasher.unsquashPolicy(json2.policies[policy4.name].values);
        const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy4.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy4.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 table5 of Object.values(json2.tables)) {
          const policiesInCurrentState = Object.keys(table5.policies);
          const tableInPreviousState = columnsPatchedSnap1.tables[`${table5.schema === "" ? "public" : table5.schema}.${table5.name}`];
          const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
          if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table5.isRLSEnabled) {
            jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table5.name, schema: table5.schema });
          }
          if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table5.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table5.name, schema: table5.schema });
          }
          const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false;
          if (table5.isRLSEnabled !== wasRlsEnabled) {
            if (table5.isRLSEnabled) {
              jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table5.name, schema: table5.schema });
            } else if (!table5.isRLSEnabled && policiesInCurrentState.length === 0) {
              jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table5.name, schema: table5.schema });
            }
          }
        }
        for (const table5 of Object.values(columnsPatchedSnap1.tables)) {
          const tableInCurrentState = json2.tables[`${table5.schema === "" ? "public" : table5.schema}.${table5.name}`];
          if (tableInCurrentState === void 0 && !table5.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table5.name, schema: table5.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(
        (t2) => t2.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
        (t2) => t2.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(...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(...jsonAlterEnumsWithDroppedValues);
      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 (jsonStatements.find(
            (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.schema === st.schema
          )) {
            return false;
          }
        }
        return true;
      });
      const sqlStatements = fromJson(filteredEnumsJsonStatements, "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: filteredEnumsJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      for (const tableName in json1.tables) {
        const table5 = json1.tables[tableName];
        for (const indexName5 in table5.indexes) {
          const index5 = MySqlSquasher.unsquashIdx(table5.indexes[indexName5]);
          if (index5.isUnique) {
            table5.uniqueConstraints[indexName5] = MySqlSquasher.squashUnique({
              name: index5.name,
              columns: index5.columns
            });
            delete json1.tables[tableName].indexes[index5.name];
          }
        }
      }
      for (const tableName in json2.tables) {
        const table5 = json2.tables[tableName];
        for (const indexName5 in table5.indexes) {
          const index5 = MySqlSquasher.unsquashIdx(table5.indexes[indexName5]);
          if (index5.isUnique) {
            table5.uniqueConstraints[indexName5] = MySqlSquasher.squashUnique({
              name: index5.name,
              columns: index5.columns
            });
            delete json2.tables[tableName].indexes[index5.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, (_2, 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, column9) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column9.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 k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__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 k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__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(
        (t2) => t2.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t2) => t2.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 view4 = curFull["views"][alteredView.name];
          alterViews.push(
            prepareMySqlAlterView(view4)
          );
        }
      }
      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 table5 = json1.tables[tableName];
        for (const indexName5 in table5.indexes) {
          const index5 = SingleStoreSquasher.unsquashIdx(table5.indexes[indexName5]);
          if (index5.isUnique) {
            table5.uniqueConstraints[indexName5] = SingleStoreSquasher.squashUnique({
              name: index5.name,
              columns: index5.columns
            });
            delete json1.tables[tableName].indexes[index5.name];
          }
        }
      }
      for (const tableName in json2.tables) {
        const table5 = json2.tables[tableName];
        for (const indexName5 in table5.indexes) {
          const index5 = SingleStoreSquasher.unsquashIdx(table5.indexes[indexName5]);
          if (index5.isUnique) {
            table5.uniqueConstraints[indexName5] = SingleStoreSquasher.squashUnique({
              name: index5.name,
              columns: index5.columns
            });
            delete json2.tables[tableName].indexes[index5.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, (_2, 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, column9) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column9.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 k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__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 k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__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, (_2, 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, column9) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column9.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 k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__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 k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__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 k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__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(
        (t2) => t2.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t2) => t2.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, (_2, 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, column9) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column9.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 k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__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 k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__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(
        (t2) => t2.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t2) => t2.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 prepareMigrationMetadata, adjectives, heroes;
var init_words = __esm({
  "src/utils/words.ts"() {
    "use strict";
    prepareMigrationMetadata = (idx, prefixMode, name) => {
      const prefix2 = prefixMode === "index" ? idx.toFixed(0).padStart(4, "0") : prefixMode === "timestamp" || prefixMode === "supabase" ? (/* @__PURE__ */ new Date()).toISOString().replace("T", "").replaceAll("-", "").replaceAll(":", "").slice(0, 14) : prefixMode === "unix" ? Math.floor(Date.now() / 1e3) : "";
      const suffix = name || `${adjectives.random()}_${heroes.random()}`;
      const tag = `${prefix2}_${suffix}`;
      return { prefix: prefix2, suffix, tag };
    };
    adjectives = [
      "abandoned",
      "aberrant",
      "abnormal",
      "absent",
      "absurd",
      "acoustic",
      "adorable",
      "amazing",
      "ambiguous",
      "ambitious",
      "amused",
      "amusing",
      "ancient",
      "aromatic",
      "aspiring",
      "awesome",
      "bent",
      "big",
      "bitter",
      "bizarre",
      "black",
      "blue",
      "blushing",
      "bored",
      "boring",
      "bouncy",
      "brainy",
      "brave",
      "breezy",
      "brief",
      "bright",
      "broad",
      "broken",
      "brown",
      "bumpy",
      "burly",
      "busy",
      "calm",
      "careful",
      "careless",
      "certain",
      "charming",
      "cheerful",
      "chemical",
      "chief",
      "chilly",
      "chubby",
      "chunky",
      "clammy",
      "classy",
      "clean",
      "clear",
      "clever",
      "cloudy",
      "closed",
      "clumsy",
      "cold",
      "colorful",
      "colossal",
      "common",
      "complete",
      "complex",
      "concerned",
      "condemned",
      "confused",
      "conscious",
      "cooing",
      "cool",
      "crazy",
      "cuddly",
      "cultured",
      "curious",
      "curly",
      "curved",
      "curvy",
      "cute",
      "cynical",
      "daffy",
      "daily",
      "damp",
      "dapper",
      "dark",
      "dashing",
      "dazzling",
      "dear",
      "deep",
      "demonic",
      "dizzy",
      "dry",
      "dusty",
      "eager",
      "early",
      "easy",
      "elite",
      "eminent",
      "empty",
      "equal",
      "even",
      "exotic",
      "fair",
      "faithful",
      "familiar",
      "famous",
      "fancy",
      "fantastic",
      "far",
      "fast",
      "fat",
      "faulty",
      "fearless",
      "fine",
      "first",
      "fixed",
      "flaky",
      "flashy",
      "flat",
      "flawless",
      "flimsy",
      "flippant",
      "flowery",
      "fluffy",
      "foamy",
      "free",
      "freezing",
      "fresh",
      "friendly",
      "funny",
      "furry",
      "futuristic",
      "fuzzy",
      "giant",
      "gifted",
      "gigantic",
      "glamorous",
      "glorious",
      "glossy",
      "good",
      "goofy",
      "gorgeous",
      "graceful",
      "gray",
      "great",
      "greedy",
      "green",
      "grey",
      "groovy",
      "handy",
      "happy",
      "hard",
      "harsh",
      "heavy",
      "hesitant",
      "high",
      "hot",
      "huge",
      "icy",
      "illegal",
      "jazzy",
      "jittery",
      "keen",
      "kind",
      "known",
      "lame",
      "large",
      "last",
      "late",
      "lazy",
      "lean",
      "left",
      "legal",
      "lethal",
      "light",
      "little",
      "lively",
      "living",
      "lonely",
      "long",
      "loose",
      "loud",
      "lovely",
      "loving",
      "low",
      "lowly",
      "lucky",
      "lumpy",
      "lush",
      "luxuriant",
      "lying",
      "lyrical",
      "magenta",
      "magical",
      "majestic",
      "many",
      "massive",
      "married",
      "marvelous",
      "material",
      "mature",
      "mean",
      "medical",
      "melodic",
      "melted",
      "messy",
      "mighty",
      "military",
      "milky",
      "minor",
      "misty",
      "mixed",
      "moaning",
      "modern",
      "motionless",
      "mushy",
      "mute",
      "mysterious",
      "naive",
      "nappy",
      "narrow",
      "nasty",
      "natural",
      "neat",
      "nebulous",
      "needy",
      "nervous",
      "new",
      "next",
      "nice",
      "nifty",
      "noisy",
      "normal",
      "nostalgic",
      "nosy",
      "numerous",
      "odd",
      "old",
      "omniscient",
      "open",
      "opposite",
      "optimal",
      "orange",
      "ordinary",
      "organic",
      "outgoing",
      "outstanding",
      "oval",
      "overconfident",
      "overjoyed",
      "overrated",
      "pale",
      "panoramic",
      "parallel",
      "parched",
      "past",
      "peaceful",
      "perfect",
      "perpetual",
      "petite",
      "pink",
      "plain",
      "polite",
      "powerful",
      "premium",
      "pretty",
      "previous",
      "productive",
      "public",
      "purple",
      "puzzling",
      "quick",
      "quiet",
      "rainy",
      "rapid",
      "rare",
      "real",
      "red",
      "redundant",
      "reflective",
      "regular",
      "remarkable",
      "rich",
      "right",
      "robust",
      "romantic",
      "round",
      "sad",
      "safe",
      "salty",
      "same",
      "secret",
      "serious",
      "shallow",
      "sharp",
      "shiny",
      "shocking",
      "short",
      "silent",
      "silky",
      "silly",
      "simple",
      "skinny",
      "sleepy",
      "slim",
      "slimy",
      "slippery",
      "sloppy",
      "slow",
      "small",
      "smart",
      "smiling",
      "smooth",
      "soft",
      "solid",
      "sour",
      "sparkling",
      "special",
      "spicy",
      "spooky",
      "spotty",
      "square",
      "stale",
      "steady",
      "steep",
      "sticky",
      "stiff",
      "stormy",
      "strange",
      "striped",
      "strong",
      "sturdy",
      "sudden",
      "superb",
      "supreme",
      "sweet",
      "swift",
      "talented",
      "tan",
      "tearful",
      "tense",
      "thankful",
      "thick",
      "thin",
      "third",
      "tidy",
      "tiny",
      "tired",
      "tiresome",
      "tough",
      "tranquil",
      "tricky",
      "true",
      "typical",
      "uneven",
      "unique",
      "unknown",
      "unusual",
      "useful",
      "vengeful",
      "violet",
      "volatile",
      "wakeful",
      "wandering",
      "warm",
      "watery",
      "wealthy",
      "wet",
      "white",
      "whole",
      "wide",
      "wild",
      "windy",
      "wise",
      "wonderful",
      "wooden",
      "woozy",
      "workable",
      "worried",
      "worthless",
      "yellow",
      "yielding",
      "young",
      "youthful",
      "yummy",
      "zippy"
    ];
    heroes = [
      "aaron_stack",
      "abomination",
      "absorbing_man",
      "adam_destine",
      "adam_warlock",
      "agent_brand",
      "agent_zero",
      "albert_cleary",
      "alex_power",
      "alex_wilder",
      "alice",
      "amazoness",
      "amphibian",
      "angel",
      "anita_blake",
      "annihilus",
      "anthem",
      "apocalypse",
      "aqueduct",
      "arachne",
      "archangel",
      "arclight",
      "ares",
      "argent",
      "avengers",
      "azazel",
      "banshee",
      "baron_strucker",
      "baron_zemo",
      "barracuda",
      "bastion",
      "beast",
      "bedlam",
      "ben_grimm",
      "ben_parker",
      "ben_urich",
      "betty_brant",
      "betty_ross",
      "beyonder",
      "big_bertha",
      "bill_hollister",
      "bishop",
      "black_bird",
      "black_bolt",
      "black_cat",
      "black_crow",
      "black_knight",
      "black_panther",
      "black_queen",
      "black_tarantula",
      "black_tom",
      "black_widow",
      "blackheart",
      "blacklash",
      "blade",
      "blazing_skull",
      "blindfold",
      "blink",
      "blizzard",
      "blob",
      "blockbuster",
      "blonde_phantom",
      "bloodaxe",
      "bloodscream",
      "bloodstorm",
      "bloodstrike",
      "blue_blade",
      "blue_marvel",
      "blue_shield",
      "blur",
      "boom_boom",
      "boomer",
      "boomerang",
      "bromley",
      "brood",
      "brother_voodoo",
      "bruce_banner",
      "bucky",
      "bug",
      "bulldozer",
      "bullseye",
      "bushwacker",
      "butterfly",
      "cable",
      "callisto",
      "calypso",
      "cammi",
      "cannonball",
      "captain_america",
      "captain_britain",
      "captain_cross",
      "captain_flint",
      "captain_marvel",
      "captain_midlands",
      "captain_stacy",
      "captain_universe",
      "cardiac",
      "caretaker",
      "cargill",
      "carlie_cooper",
      "carmella_unuscione",
      "carnage",
      "cassandra_nova",
      "catseye",
      "celestials",
      "centennial",
      "cerebro",
      "cerise",
      "chamber",
      "chameleon",
      "champions",
      "changeling",
      "charles_xavier",
      "chat",
      "chimera",
      "christian_walker",
      "chronomancer",
      "clea",
      "clint_barton",
      "cloak",
      "cobalt_man",
      "colleen_wing",
      "colonel_america",
      "colossus",
      "corsair",
      "crusher_hogan",
      "crystal",
      "cyclops",
      "dagger",
      "daimon_hellstrom",
      "dakota_north",
      "daredevil",
      "dark_beast",
      "dark_phoenix",
      "darkhawk",
      "darkstar",
      "darwin",
      "dazzler",
      "deadpool",
      "deathbird",
      "deathstrike",
      "demogoblin",
      "devos",
      "dexter_bennett",
      "diamondback",
      "doctor_doom",
      "doctor_faustus",
      "doctor_octopus",
      "doctor_spectrum",
      "doctor_strange",
      "domino",
      "donald_blake",
      "doomsday",
      "doorman",
      "dorian_gray",
      "dormammu",
      "dracula",
      "dragon_lord",
      "dragon_man",
      "drax",
      "dreadnoughts",
      "dreaming_celestial",
      "dust",
      "earthquake",
      "echo",
      "eddie_brock",
      "edwin_jarvis",
      "ego",
      "electro",
      "elektra",
      "emma_frost",
      "enchantress",
      "ender_wiggin",
      "energizer",
      "epoch",
      "eternals",
      "eternity",
      "excalibur",
      "exiles",
      "exodus",
      "expediter",
      "ezekiel",
      "ezekiel_stane",
      "fabian_cortez",
      "falcon",
      "fallen_one",
      "famine",
      "fantastic_four",
      "fat_cobra",
      "felicia_hardy",
      "fenris",
      "firebird",
      "firebrand",
      "firedrake",
      "firelord",
      "firestar",
      "fixer",
      "flatman",
      "forge",
      "forgotten_one",
      "frank_castle",
      "franklin_richards",
      "franklin_storm",
      "freak",
      "frightful_four",
      "frog_thor",
      "gabe_jones",
      "galactus",
      "gambit",
      "gamma_corps",
      "gamora",
      "gargoyle",
      "garia",
      "gateway",
      "gauntlet",
      "genesis",
      "george_stacy",
      "gertrude_yorkes",
      "ghost_rider",
      "giant_girl",
      "giant_man",
      "gideon",
      "gladiator",
      "glorian",
      "goblin_queen",
      "golden_guardian",
      "goliath",
      "gorgon",
      "gorilla_man",
      "grandmaster",
      "gravity",
      "green_goblin",
      "gressill",
      "grey_gargoyle",
      "greymalkin",
      "grim_reaper",
      "groot",
      "guardian",
      "guardsmen",
      "gunslinger",
      "gwen_stacy",
      "hairball",
      "hammerhead",
      "hannibal_king",
      "hardball",
      "harpoon",
      "harrier",
      "harry_osborn",
      "havok",
      "hawkeye",
      "hedge_knight",
      "hellcat",
      "hellfire_club",
      "hellion",
      "hemingway",
      "hercules",
      "hex",
      "hiroim",
      "hitman",
      "hobgoblin",
      "hulk",
      "human_cannonball",
      "human_fly",
      "human_robot",
      "human_torch",
      "husk",
      "hydra",
      "iceman",
      "ikaris",
      "imperial_guard",
      "impossible_man",
      "inertia",
      "infant_terrible",
      "inhumans",
      "ink",
      "invaders",
      "invisible_woman",
      "iron_fist",
      "iron_lad",
      "iron_man",
      "iron_monger",
      "iron_patriot",
      "ironclad",
      "jack_flag",
      "jack_murdock",
      "jack_power",
      "jackal",
      "jackpot",
      "james_howlett",
      "jamie_braddock",
      "jane_foster",
      "jasper_sitwell",
      "jazinda",
      "jean_grey",
      "jetstream",
      "jigsaw",
      "jimmy_woo",
      "jocasta",
      "johnny_blaze",
      "johnny_storm",
      "joseph",
      "joshua_kane",
      "joystick",
      "jubilee",
      "juggernaut",
      "junta",
      "justice",
      "justin_hammer",
      "kabuki",
      "kang",
      "karen_page",
      "karma",
      "karnak",
      "kat_farrell",
      "kate_bishop",
      "katie_power",
      "ken_ellis",
      "khan",
      "kid_colt",
      "killer_shrike",
      "killmonger",
      "killraven",
      "king_bedlam",
      "king_cobra",
      "kingpin",
      "kinsey_walden",
      "kitty_pryde",
      "klaw",
      "komodo",
      "korath",
      "korg",
      "korvac",
      "kree",
      "krista_starr",
      "kronos",
      "kulan_gath",
      "kylun",
      "la_nuit",
      "lady_bullseye",
      "lady_deathstrike",
      "lady_mastermind",
      "lady_ursula",
      "lady_vermin",
      "lake",
      "landau",
      "layla_miller",
      "leader",
      "leech",
      "legion",
      "lenny_balinger",
      "leo",
      "leopardon",
      "leper_queen",
      "lester",
      "lethal_legion",
      "lifeguard",
      "lightspeed",
      "lila_cheney",
      "lilandra",
      "lilith",
      "lily_hollister",
      "lionheart",
      "living_lightning",
      "living_mummy",
      "living_tribunal",
      "liz_osborn",
      "lizard",
      "loa",
      "lockheed",
      "lockjaw",
      "logan",
      "loki",
      "loners",
      "longshot",
      "lord_hawal",
      "lord_tyger",
      "lorna_dane",
      "luckman",
      "lucky_pierre",
      "luke_cage",
      "luminals",
      "lyja",
      "ma_gnuci",
      "mac_gargan",
      "mach_iv",
      "machine_man",
      "mad_thinker",
      "madame_hydra",
      "madame_masque",
      "madame_web",
      "maddog",
      "madelyne_pryor",
      "madripoor",
      "madrox",
      "maelstrom",
      "maestro",
      "magdalene",
      "maggott",
      "magik",
      "maginty",
      "magma",
      "magneto",
      "magus",
      "major_mapleleaf",
      "makkari",
      "malcolm_colcord",
      "malice",
      "mandarin",
      "mandrill",
      "mandroid",
      "manta",
      "mantis",
      "marauders",
      "maria_hill",
      "mariko_yashida",
      "marrow",
      "marten_broadcloak",
      "martin_li",
      "marvel_apes",
      "marvel_boy",
      "marvel_zombies",
      "marvex",
      "masked_marvel",
      "masque",
      "master_chief",
      "master_mold",
      "mastermind",
      "mathemanic",
      "matthew_murdock",
      "mattie_franklin",
      "mauler",
      "maverick",
      "maximus",
      "may_parker",
      "medusa",
      "meggan",
      "meltdown",
      "menace",
      "mentallo",
      "mentor",
      "mephisto",
      "mephistopheles",
      "mercury",
      "mesmero",
      "metal_master",
      "meteorite",
      "micromacro",
      "microbe",
      "microchip",
      "micromax",
      "midnight",
      "miek",
      "mikhail_rasputin",
      "millenium_guard",
      "mimic",
      "mindworm",
      "miracleman",
      "miss_america",
      "mister_fear",
      "mister_sinister",
      "misty_knight",
      "mockingbird",
      "moira_mactaggert",
      "mojo",
      "mole_man",
      "molecule_man",
      "molly_hayes",
      "molten_man",
      "mongoose",
      "mongu",
      "monster_badoon",
      "moon_knight",
      "moondragon",
      "moonstone",
      "morbius",
      "mordo",
      "morg",
      "morgan_stark",
      "morlocks",
      "morlun",
      "morph",
      "mother_askani",
      "mulholland_black",
      "multiple_man",
      "mysterio",
      "mystique",
      "namor",
      "namora",
      "namorita",
      "naoko",
      "natasha_romanoff",
      "nebula",
      "nehzno",
      "nekra",
      "nemesis",
      "network",
      "newton_destine",
      "next_avengers",
      "nextwave",
      "nick_fury",
      "nico_minoru",
      "nicolaos",
      "night_nurse",
      "night_thrasher",
      "nightcrawler",
      "nighthawk",
      "nightmare",
      "nightshade",
      "nitro",
      "nocturne",
      "nomad",
      "norman_osborn",
      "norrin_radd",
      "northstar",
      "nova",
      "nuke",
      "obadiah_stane",
      "odin",
      "ogun",
      "old_lace",
      "omega_flight",
      "omega_red",
      "omega_sentinel",
      "onslaught",
      "oracle",
      "orphan",
      "otto_octavius",
      "outlaw_kid",
      "overlord",
      "owl",
      "ozymandias",
      "paibok",
      "paladin",
      "pandemic",
      "paper_doll",
      "patch",
      "patriot",
      "payback",
      "penance",
      "pepper_potts",
      "pestilence",
      "pet_avengers",
      "pete_wisdom",
      "peter_parker",
      "peter_quill",
      "phalanx",
      "phantom_reporter",
      "phil_sheldon",
      "photon",
      "piledriver",
      "pixie",
      "plazm",
      "polaris",
      "post",
      "power_man",
      "power_pack",
      "praxagora",
      "preak",
      "pretty_boy",
      "pride",
      "prima",
      "princess_powerful",
      "prism",
      "prodigy",
      "proemial_gods",
      "professor_monster",
      "proteus",
      "proudstar",
      "prowler",
      "psylocke",
      "psynapse",
      "puck",
      "puff_adder",
      "puma",
      "punisher",
      "puppet_master",
      "purifiers",
      "purple_man",
      "pyro",
      "quasar",
      "quasimodo",
      "queen_noir",
      "quentin_quire",
      "quicksilver",
      "rachel_grey",
      "radioactive_man",
      "rafael_vega",
      "rage",
      "raider",
      "randall",
      "randall_flagg",
      "random",
      "rattler",
      "ravenous",
      "rawhide_kid",
      "raza",
      "reaper",
      "reavers",
      "red_ghost",
      "red_hulk",
      "red_shift",
      "red_skull",
      "red_wolf",
      "redwing",
      "reptil",
      "retro_girl",
      "revanche",
      "rhino",
      "rhodey",
      "richard_fisk",
      "rick_jones",
      "ricochet",
      "rictor",
      "riptide",
      "risque",
      "robbie_robertson",
      "robin_chapel",
      "rocket_raccoon",
      "rocket_racer",
      "rockslide",
      "rogue",
      "roland_deschain",
      "romulus",
      "ronan",
      "roughhouse",
      "roulette",
      "roxanne_simpson",
      "rumiko_fujikawa",
      "runaways",
      "sabra",
      "sabretooth",
      "sage",
      "sally_floyd",
      "salo",
      "sandman",
      "santa_claus",
      "saracen",
      "sasquatch",
      "satana",
      "sauron",
      "scalphunter",
      "scarecrow",
      "scarlet_spider",
      "scarlet_witch",
      "scorpion",
      "scourge",
      "scrambler",
      "scream",
      "screwball",
      "sebastian_shaw",
      "secret_warriors",
      "selene",
      "senator_kelly",
      "sentinel",
      "sentinels",
      "sentry",
      "ser_duncan",
      "serpent_society",
      "sersi",
      "shadow_king",
      "shadowcat",
      "shaman",
      "shape",
      "shard",
      "sharon_carter",
      "sharon_ventura",
      "shatterstar",
      "shen",
      "sheva_callister",
      "shinko_yamashiro",
      "shinobi_shaw",
      "shiva",
      "shiver_man",
      "shocker",
      "shockwave",
      "shooting_star",
      "shotgun",
      "shriek",
      "silhouette",
      "silk_fever",
      "silver_centurion",
      "silver_fox",
      "silver_sable",
      "silver_samurai",
      "silver_surfer",
      "silverclaw",
      "silvermane",
      "sinister_six",
      "sir_ram",
      "siren",
      "sister_grimm",
      "skaar",
      "skin",
      "skreet",
      "skrulls",
      "skullbuster",
      "slapstick",
      "slayback",
      "sleeper",
      "sleepwalker",
      "slipstream",
      "slyde",
      "smasher",
      "smiling_tiger",
      "snowbird",
      "solo",
      "songbird",
      "spacker_dave",
      "spectrum",
      "speed",
      "speed_demon",
      "speedball",
      "spencer_smythe",
      "sphinx",
      "spiral",
      "spirit",
      "spitfire",
      "spot",
      "sprite",
      "spyke",
      "squadron_sinister",
      "squadron_supreme",
      "squirrel_girl",
      "star_brand",
      "starbolt",
      "stardust",
      "starfox",
      "starhawk",
      "starjammers",
      "stark_industries",
      "stature",
      "steel_serpent",
      "stellaris",
      "stepford_cuckoos",
      "stephen_strange",
      "steve_rogers",
      "stick",
      "stingray",
      "stone_men",
      "storm",
      "stranger",
      "strong_guy",
      "stryfe",
      "sue_storm",
      "sugar_man",
      "sumo",
      "sunfire",
      "sunset_bain",
      "sunspot",
      "supernaut",
      "supreme_intelligence",
      "surge",
      "susan_delgado",
      "swarm",
      "sway",
      "switch",
      "swordsman",
      "synch",
      "tag",
      "talisman",
      "talkback",
      "talon",
      "talos",
      "tana_nile",
      "tarantula",
      "tarot",
      "taskmaster",
      "tattoo",
      "ted_forrester",
      "tempest",
      "tenebrous",
      "terrax",
      "terror",
      "texas_twister",
      "thaddeus_ross",
      "thanos",
      "the_anarchist",
      "the_call",
      "the_captain",
      "the_enforcers",
      "the_executioner",
      "the_fallen",
      "the_fury",
      "the_hand",
      "the_hood",
      "the_hunter",
      "the_initiative",
      "the_leader",
      "the_liberteens",
      "the_order",
      "the_phantom",
      "the_professor",
      "the_renegades",
      "the_santerians",
      "the_spike",
      "the_stranger",
      "the_twelve",
      "the_watchers",
      "thena",
      "thing",
      "thor",
      "thor_girl",
      "thunderball",
      "thunderbird",
      "thunderbolt",
      "thunderbolt_ross",
      "thunderbolts",
      "thundra",
      "tiger_shark",
      "tigra",
      "timeslip",
      "tinkerer",
      "titania",
      "titanium_man",
      "toad",
      "toad_men",
      "tomas",
      "tombstone",
      "tomorrow_man",
      "tony_stark",
      "toro",
      "toxin",
      "trauma",
      "triathlon",
      "trish_tilby",
      "triton",
      "true_believers",
      "turbo",
      "tusk",
      "tyger_tiger",
      "typhoid_mary",
      "tyrannus",
      "ulik",
      "ultimates",
      "ultimatum",
      "ultimo",
      "ultragirl",
      "ultron",
      "umar",
      "unicorn",
      "union_jack",
      "unus",
      "valeria_richards",
      "valkyrie",
      "vampiro",
      "vance_astro",
      "vanisher",
      "vapor",
      "vargas",
      "vector",
      "veda",
      "vengeance",
      "venom",
      "venus",
      "vermin",
      "vertigo",
      "victor_mancha",
      "vin_gonzales",
      "vindicator",
      "violations",
      "viper",
      "virginia_dare",
      "vision",
      "vivisector",
      "vulcan",
      "vulture",
      "wallflower",
      "wallop",
      "wallow",
      "war_machine",
      "warbird",
      "warbound",
      "warhawk",
      "warlock",
      "warpath",
      "warstar",
      "wasp",
      "weapon_omega",
      "wendell_rand",
      "wendell_vaughn",
      "wendigo",
      "whiplash",
      "whirlwind",
      "whistler",
      "white_queen",
      "white_tiger",
      "whizzer",
      "wiccan",
      "wild_child",
      "wild_pack",
      "wildside",
      "william_stryker",
      "wilson_fisk",
      "wind_dancer",
      "winter_soldier",
      "wither",
      "wolf_cub",
      "wolfpack",
      "wolfsbane",
      "wolverine",
      "wonder_man",
      "wong",
      "wraith",
      "wrecker",
      "wrecking_crew",
      "xavin",
      "xorn",
      "yellow_claw",
      "yellowjacket",
      "young_avengers",
      "zaladane",
      "zaran",
      "zarda",
      "zarek",
      "zeigeist",
      "zemo",
      "zodiak",
      "zombie",
      "zuras",
      "zzzax"
    ];
  }
});

// src/cli/commands/migrate.ts
var migrate_exports = {};
__export(migrate_exports, {
  BREAKPOINT: () => BREAKPOINT,
  columnsResolver: () => columnsResolver,
  embeddedMigrations: () => embeddedMigrations,
  enumsResolver: () => enumsResolver,
  indPolicyResolver: () => indPolicyResolver,
  mySqlViewsResolver: () => mySqlViewsResolver,
  policyResolver: () => policyResolver,
  prepareAndExportLibSQL: () => prepareAndExportLibSQL,
  prepareAndExportMysql: () => prepareAndExportMysql,
  prepareAndExportPg: () => prepareAndExportPg,
  prepareAndExportSinglestore: () => prepareAndExportSinglestore,
  prepareAndExportSqlite: () => prepareAndExportSqlite,
  prepareAndMigrateLibSQL: () => prepareAndMigrateLibSQL,
  prepareAndMigrateMysql: () => prepareAndMigrateMysql,
  prepareAndMigratePg: () => prepareAndMigratePg,
  prepareAndMigrateSingleStore: () => prepareAndMigrateSingleStore,
  prepareAndMigrateSqlite: () => prepareAndMigrateSqlite,
  prepareLibSQLPush: () => prepareLibSQLPush,
  prepareMySQLPush: () => prepareMySQLPush,
  preparePgPush: () => preparePgPush,
  prepareSQLitePush: () => prepareSQLitePush,
  prepareSingleStorePush: () => prepareSingleStorePush,
  prepareSnapshotFolderName: () => prepareSnapshotFolderName,
  promptColumnsConflicts: () => promptColumnsConflicts,
  promptNamedConflict: () => promptNamedConflict,
  promptNamedWithSchemasConflict: () => promptNamedWithSchemasConflict,
  promptSchemasConflict: () => promptSchemasConflict,
  roleResolver: () => roleResolver,
  schemasResolver: () => schemasResolver,
  sequencesResolver: () => sequencesResolver,
  sqliteViewsResolver: () => sqliteViewsResolver,
  tablesResolver: () => tablesResolver,
  viewsResolver: () => viewsResolver,
  writeResult: () => writeResult
});
var import_fs6, import_hanji3, import_path5, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, indPolicyResolver, enumsResolver, columnsResolver, prepareAndMigratePg, prepareAndExportPg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareSingleStorePush, prepareAndMigrateSingleStore, prepareAndExportSinglestore, prepareAndExportMysql, prepareAndMigrateSqlite, prepareAndExportSqlite, prepareAndMigrateLibSQL, prepareAndExportLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
var init_migrate = __esm({
  "src/cli/commands/migrate.ts"() {
    "use strict";
    import_fs6 = __toESM(require("fs"));
    init_migrationPreparator();
    init_source();
    import_hanji3 = __toESM(require_hanji());
    import_path5 = __toESM(require("path"));
    init_singlestoreSchema();
    init_mysqlSchema();
    init_pgSchema();
    init_sqliteSchema();
    init_snapshotsDiffer();
    init_utils2();
    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 (e2) {
        console.error(e2);
        throw e2;
      }
    };
    tablesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "table"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e2) {
        console.error(e2);
        throw e2;
      }
    };
    viewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e2) {
        console.error(e2);
        throw e2;
      }
    };
    mySqlViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e2) {
        console.error(e2);
        throw e2;
      }
    };
    sqliteViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e2) {
        console.error(e2);
        throw e2;
      }
    };
    sequencesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "sequence"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e2) {
        console.error(e2);
        throw e2;
      }
    };
    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 (e2) {
        console.error(e2);
        throw e2;
      }
    };
    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
      };
    };
    prepareAndMigratePg = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(
          outFolder,
          "postgresql"
        );
        const { prev, cur, custom: custom2 } = await preparePgMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = pgSchema.parse(prev);
        const validatedCur = pgSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashPgScheme(validatedPrev);
        const squashedCur = squashPgScheme(validatedCur);
        const { sqlStatements, _meta } = await applyPgSnapshotsDiff(
          squashedPrev,
          squashedCur,
          schemasResolver,
          enumsResolver,
          sequencesResolver,
          policyResolver,
          indPolicyResolver,
          roleResolver,
          tablesResolver,
          columnsResolver,
          viewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          prefixMode: config.prefix
        });
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareAndExportPg = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur } = await preparePgMigrationSnapshot(
          [],
          // no snapshots before
          schemaPath,
          void 0
        );
        const validatedPrev = pgSchema.parse(prev);
        const validatedCur = pgSchema.parse(cur);
        const squashedPrev = squashPgScheme(validatedPrev);
        const squashedCur = squashPgScheme(validatedCur);
        const { sqlStatements } = await applyPgSnapshotsDiff(
          squashedPrev,
          squashedCur,
          schemasResolver,
          enumsResolver,
          sequencesResolver,
          policyResolver,
          indPolicyResolver,
          roleResolver,
          tablesResolver,
          columnsResolver,
          viewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e2) {
        console.error(e2);
      }
    };
    preparePgPush = async (cur, prev) => {
      const validatedPrev = pgSchema.parse(prev);
      const validatedCur = pgSchema.parse(cur);
      const squashedPrev = squashPgScheme(validatedPrev, "push");
      const squashedCur = squashPgScheme(validatedCur, "push");
      const { sqlStatements, statements, _meta } = await applyPgSnapshotsDiff(
        squashedPrev,
        squashedCur,
        schemasResolver,
        enumsResolver,
        sequencesResolver,
        policyResolver,
        indPolicyResolver,
        roleResolver,
        tablesResolver,
        columnsResolver,
        viewsResolver,
        validatedPrev,
        validatedCur,
        "push"
      );
      return { sqlStatements, statements, squashedPrev, squashedCur };
    };
    prepareMySQLPush = async (schemaPath, snapshot, casing2) => {
      try {
        const { prev, cur } = await prepareMySqlDbPushSnapshot(
          snapshot,
          schemaPath,
          casing2
        );
        const validatedPrev = mysqlSchema.parse(prev);
        const validatedCur = mysqlSchema.parse(cur);
        const squashedPrev = squashMysqlScheme(validatedPrev);
        const squashedCur = squashMysqlScheme(validatedCur);
        const { sqlStatements, statements } = await applyMysqlSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          validatedPrev,
          validatedCur,
          "push"
        );
        return { sqlStatements, statements, validatedCur, validatedPrev };
      } catch (e2) {
        console.error(e2);
        process.exit(1);
      }
    };
    prepareAndMigrateMysql = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "mysql");
        const { prev, cur, custom: custom2 } = await prepareMySqlMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = mysqlSchema.parse(prev);
        const validatedCur = mysqlSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashMysqlScheme(validatedPrev);
        const squashedCur = squashMysqlScheme(validatedCur);
        const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          prefixMode: config.prefix
        });
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareSingleStorePush = async (schemaPath, snapshot, casing2) => {
      try {
        const { prev, cur } = await prepareSingleStoreDbPushSnapshot(
          snapshot,
          schemaPath,
          casing2
        );
        const validatedPrev = singlestoreSchema.parse(prev);
        const validatedCur = singlestoreSchema.parse(cur);
        const squashedPrev = squashSingleStoreScheme(validatedPrev);
        const squashedCur = squashSingleStoreScheme(validatedCur);
        const { sqlStatements, statements } = await applySingleStoreSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          validatedPrev,
          validatedCur,
          "push"
        );
        return { sqlStatements, statements, validatedCur, validatedPrev };
      } catch (e2) {
        console.error(e2);
        process.exit(1);
      }
    };
    prepareAndMigrateSingleStore = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "singlestore");
        const { prev, cur, custom: custom2 } = await prepareSingleStoreMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = singlestoreSchema.parse(prev);
        const validatedCur = singlestoreSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashSingleStoreScheme(validatedPrev);
        const squashedCur = squashSingleStoreScheme(validatedCur);
        const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          prefixMode: config.prefix
        });
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareAndExportSinglestore = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur } = await prepareSingleStoreMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = singlestoreSchema.parse(prev);
        const validatedCur = singlestoreSchema.parse(cur);
        const squashedPrev = squashSingleStoreScheme(validatedPrev);
        const squashedCur = squashSingleStoreScheme(validatedCur);
        const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareAndExportMysql = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur, custom: custom2 } = await prepareMySqlMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = mysqlSchema.parse(prev);
        const validatedCur = mysqlSchema.parse(cur);
        const squashedPrev = squashMysqlScheme(validatedPrev);
        const squashedCur = squashMysqlScheme(validatedCur);
        const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareAndMigrateSqlite = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
        const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            bundle: config.bundle,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          bundle: config.bundle,
          prefixMode: config.prefix,
          driver: config.driver
        });
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareAndExportSqlite = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur } = await prepareSqliteMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareAndMigrateLibSQL = async (config) => {
      const outFolder = config.out;
      const schemaPath = config.schema;
      const casing2 = config.casing;
      try {
        assertV1OutFolder(outFolder);
        const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
        const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
          snapshots,
          schemaPath,
          casing2
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        if (config.custom) {
          writeResult({
            cur: custom2,
            sqlStatements: [],
            journal,
            outFolder,
            name: config.name,
            breakpoints: config.breakpoints,
            bundle: config.bundle,
            type: "custom",
            prefixMode: config.prefix
          });
          return;
        }
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        writeResult({
          cur,
          sqlStatements,
          journal,
          _meta,
          outFolder,
          name: config.name,
          breakpoints: config.breakpoints,
          bundle: config.bundle,
          prefixMode: config.prefix
        });
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareAndExportLibSQL = async (config) => {
      const schemaPath = config.schema;
      try {
        const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
          [],
          schemaPath,
          void 0
        );
        const validatedPrev = sqliteSchema.parse(prev);
        const validatedCur = sqliteSchema.parse(cur);
        const squashedPrev = squashSqliteScheme(validatedPrev);
        const squashedCur = squashSqliteScheme(validatedCur);
        const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
          squashedPrev,
          squashedCur,
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          validatedPrev,
          validatedCur
        );
        console.log(sqlStatements.join("\n"));
      } catch (e2) {
        console.error(e2);
      }
    };
    prepareSQLitePush = async (schemaPath, snapshot, casing2) => {
      const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing2);
      const validatedPrev = sqliteSchema.parse(prev);
      const validatedCur = sqliteSchema.parse(cur);
      const squashedPrev = squashSqliteScheme(validatedPrev, "push");
      const squashedCur = squashSqliteScheme(validatedCur, "push");
      const { sqlStatements, statements, _meta } = await applySqliteSnapshotsDiff(
        squashedPrev,
        squashedCur,
        tablesResolver,
        columnsResolver,
        sqliteViewsResolver,
        validatedPrev,
        validatedCur,
        "push"
      );
      return {
        sqlStatements,
        statements,
        squashedPrev,
        squashedCur,
        meta: _meta
      };
    };
    prepareLibSQLPush = async (schemaPath, snapshot, casing2) => {
      const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing2);
      const validatedPrev = sqliteSchema.parse(prev);
      const validatedCur = sqliteSchema.parse(cur);
      const squashedPrev = squashSqliteScheme(validatedPrev, "push");
      const squashedCur = squashSqliteScheme(validatedCur, "push");
      const { sqlStatements, statements, _meta } = await applyLibSQLSnapshotsDiff(
        squashedPrev,
        squashedCur,
        tablesResolver,
        columnsResolver,
        sqliteViewsResolver,
        validatedPrev,
        validatedCur,
        "push"
      );
      return {
        sqlStatements,
        statements,
        squashedPrev,
        squashedCur,
        meta: _meta
      };
    };
    promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
      if (newColumns.length === 0 || missingColumns.length === 0) {
        return { created: newColumns, renamed: [], deleted: missingColumns };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index5 = 0;
      let leftMissing = [...missingColumns];
      do {
        const created = newColumns[index5];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.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);
        }
        index5 += 1;
      } while (index5 < 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 index5 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index5];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.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);
        }
        index5 += 1;
      } while (index5 < 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 index5 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index5];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.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);
        }
        index5 += 1;
      } while (index5 < 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 index5 = 0;
      let leftMissing = [...missingSchemas];
      do {
        const created = newSchemas[index5];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji3.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);
        }
        index5 += 1;
      } while (index5 < newSchemas.length);
      console.log(source_default.gray("--- all schemas conflicts resolved ---\n"));
      result.deleted.push(...leftMissing);
      return result;
    };
    BREAKPOINT = "--> statement-breakpoint\n";
    writeResult = ({
      cur,
      sqlStatements,
      journal,
      _meta = {
        columns: {},
        schemas: {},
        tables: {}
      },
      outFolder,
      breakpoints,
      name,
      bundle = false,
      type = "none",
      prefixMode,
      driver: driver2
    }) => {
      if (type === "none") {
        console.log(schema4(cur));
        if (sqlStatements.length === 0) {
          console.log("No schema changes, nothing to migrate \u{1F634}");
          return;
        }
      }
      const lastEntryInJournal = journal.entries[journal.entries.length - 1];
      const idx = typeof lastEntryInJournal === "undefined" ? 0 : lastEntryInJournal.idx + 1;
      const { prefix: prefix2, tag } = prepareMigrationMetadata(idx, prefixMode, name);
      const toSave = JSON.parse(JSON.stringify(cur));
      toSave["_meta"] = _meta;
      const metaFolderPath = (0, import_path5.join)(outFolder, "meta");
      const metaJournal = (0, import_path5.join)(metaFolderPath, "_journal.json");
      import_fs6.default.writeFileSync(
        (0, import_path5.join)(metaFolderPath, `${prefix2}_snapshot.json`),
        JSON.stringify(toSave, null, 2)
      );
      const sqlDelimiter = breakpoints ? BREAKPOINT : "\n";
      let sql = sqlStatements.join(sqlDelimiter);
      if (type === "introspect") {
        sql = `-- Current sql file was generated after introspecting the database
-- If you want to run this migration please uncomment this code before executing migrations
/*
${sql}
*/`;
      }
      if (type === "custom") {
        console.log("Prepared empty file for your custom SQL migration!");
        sql = "-- Custom SQL migration file, put your code below! --";
      }
      journal.entries.push({
        idx,
        version: cur.version,
        when: +/* @__PURE__ */ new Date(),
        tag,
        breakpoints
      });
      import_fs6.default.writeFileSync(metaJournal, JSON.stringify(journal, null, 2));
      import_fs6.default.writeFileSync(`${outFolder}/${tag}.sql`, sql);
      if (bundle) {
        const js = embeddedMigrations(journal, driver2);
        import_fs6.default.writeFileSync(`${outFolder}/migrations.js`, js);
      }
      (0, import_hanji3.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your SQL migration file \u279C ${source_default.bold.underline.blue(
          import_path5.default.join(`${outFolder}/${tag}.sql`)
        )} \u{1F680}`
      );
    };
    embeddedMigrations = (journal, driver2) => {
      let content = driver2 === "expo" ? "// This file is required for Expo/React Native SQLite migrations - https://orm.drizzle.team/quick-sqlite/expo\n\n" : "";
      content += "import journal from './meta/_journal.json';\n";
      journal.entries.forEach((entry) => {
        content += `import m${entry.idx.toString().padStart(4, "0")} from './${entry.tag}.sql';
`;
      });
      content += `
  export default {
    journal,
    migrations: {
      ${journal.entries.map((it) => `m${it.idx.toString().padStart(4, "0")}`).join(",\n")}
    }
  }
  `;
      return content;
    };
    prepareSnapshotFolderName = () => {
      const now = /* @__PURE__ */ new Date();
      return `${now.getFullYear()}${two(now.getUTCMonth() + 1)}${two(
        now.getUTCDate()
      )}${two(now.getUTCHours())}${two(now.getUTCMinutes())}${two(
        now.getUTCSeconds()
      )}`;
    };
    two = (input) => {
      return input.toString().padStart(2, "0");
    };
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/internal/constants.js
var require_constants = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/internal/constants.js"(exports2, module2) {
    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.6.2/node_modules/semver/internal/debug.js
var require_debug = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/internal/debug.js"(exports2, module2) {
    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.6.2/node_modules/semver/internal/re.js
var require_re = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/internal/re.js"(exports2, module2) {
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants();
    var debug = require_debug();
    exports2 = module2.exports = {};
    var re = exports2.re = [];
    var safeRe = exports2.safeRe = [];
    var src = exports2.src = [];
    var t2 = 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 index5 = R++;
      debug(name, index5, value);
      t2[name] = index5;
      src[index5] = value;
      re[index5] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index5] = 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[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t2.NUMERICIDENTIFIER]}|${src[t2.NONNUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t2.NUMERICIDENTIFIERLOOSE]}|${src[t2.NONNUMERICIDENTIFIER]})`);
    createToken("PRERELEASE", `(?:-(${src[t2.PRERELEASEIDENTIFIER]}(?:\\.${src[t2.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t2.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t2.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t2.BUILDIDENTIFIER]}(?:\\.${src[t2.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t2.MAINVERSION]}${src[t2.PRERELEASE]}?${src[t2.BUILD]}?`);
    createToken("FULL", `^${src[t2.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t2.MAINVERSIONLOOSE]}${src[t2.PRERELEASELOOSE]}?${src[t2.BUILD]}?`);
    createToken("LOOSE", `^${src[t2.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t2.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t2.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:${src[t2.PRERELEASE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:${src[t2.PRERELEASELOOSE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t2.GTLT]}\\s*${src[t2.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[t2.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t2.COERCEPLAIN] + `(?:${src[t2.PRERELEASE]})?(?:${src[t2.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t2.COERCE], true);
    createToken("COERCERTLFULL", src[t2.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t2.LONETILDE]}\\s+`, true);
    exports2.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t2.LONECARET]}\\s+`, true);
    exports2.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t2.GTLT]}\\s*(${src[t2.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]}|${src[t2.XRANGEPLAIN]})`, true);
    exports2.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t2.XRANGEPLAIN]})\\s+-\\s+(${src[t2.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t2.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t2.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.6.2/node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/internal/parse-options.js"(exports2, module2) {
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions2 = (options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    };
    module2.exports = parseOptions2;
  }
});

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

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/classes/semver.js
var require_semver = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/classes/semver.js"(exports2, module2) {
    var debug = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
    var { safeRe: re, t: t2 } = require_re();
    var parseOptions2 = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      constructor(version3, options) {
        options = parseOptions2(options);
        if (version3 instanceof _SemVer) {
          if (version3.loose === !!options.loose && version3.includePrerelease === !!options.includePrerelease) {
            return version3;
          } else {
            version3 = version3.version;
          }
        } else if (typeof version3 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version3}".`);
        }
        if (version3.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug("SemVer", version3, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m2 = version3.trim().match(options.loose ? re[t2.LOOSE] : re[t2.FULL]);
        if (!m2) {
          throw new TypeError(`Invalid Version: ${version3}`);
        }
        this.raw = version3;
        this.major = +m2[1];
        this.minor = +m2[2];
        this.patch = +m2[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 (!m2[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m2[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 = m2[5] ? m2[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 i2 = 0;
        do {
          const a = this.prerelease[i2];
          const b = other.prerelease[i2];
          debug("prerelease compare", i2, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i2);
      }
      compareBuild(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        let i2 = 0;
        do {
          const a = this.build[i2];
          const b = other.build[i2];
          debug("build compare", i2, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i2);
      }
      // 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(release, identifier, identifierBase) {
        switch (release) {
          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;
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            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;
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (!identifier && identifierBase === false) {
              throw new Error("invalid increment argument: identifier is empty");
            }
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i2 = this.prerelease.length;
              while (--i2 >= 0) {
                if (typeof this.prerelease[i2] === "number") {
                  this.prerelease[i2]++;
                  i2 = -2;
                }
              }
              if (i2 === -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: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module2.exports = SemVer;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/parse.js
var require_parse2 = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/parse.js"(exports2, module2) {
    var SemVer = require_semver();
    var parse5 = (version3, options, throwErrors = false) => {
      if (version3 instanceof SemVer) {
        return version3;
      }
      try {
        return new SemVer(version3, options);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    };
    module2.exports = parse5;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/valid.js"(exports2, module2) {
    var parse5 = require_parse2();
    var valid = (version3, options) => {
      const v = parse5(version3, options);
      return v ? v.version : null;
    };
    module2.exports = valid;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/clean.js
var require_clean = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/clean.js"(exports2, module2) {
    var parse5 = require_parse2();
    var clean = (version3, options) => {
      const s2 = parse5(version3.trim().replace(/^[=v]+/, ""), options);
      return s2 ? s2.version : null;
    };
    module2.exports = clean;
  }
});

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

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/diff.js
var require_diff = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/diff.js"(exports2, module2) {
    var parse5 = require_parse2();
    var diff2 = (version1, version22) => {
      const v12 = parse5(version1, null, true);
      const v2 = parse5(version22, null, true);
      const comparison = v12.compare(v2);
      if (comparison === 0) {
        return null;
      }
      const v1Higher = comparison > 0;
      const highVersion = v1Higher ? v12 : v2;
      const lowVersion = v1Higher ? v2 : v12;
      const highHasPre = !!highVersion.prerelease.length;
      const lowHasPre = !!lowVersion.prerelease.length;
      if (lowHasPre && !highHasPre) {
        if (!lowVersion.patch && !lowVersion.minor) {
          return "major";
        }
        if (highVersion.patch) {
          return "patch";
        }
        if (highVersion.minor) {
          return "minor";
        }
        return "major";
      }
      const prefix2 = highHasPre ? "pre" : "";
      if (v12.major !== v2.major) {
        return prefix2 + "major";
      }
      if (v12.minor !== v2.minor) {
        return prefix2 + "minor";
      }
      if (v12.patch !== v2.patch) {
        return prefix2 + "patch";
      }
      return "prerelease";
    };
    module2.exports = diff2;
  }
});

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

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

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

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/prerelease.js"(exports2, module2) {
    var parse5 = require_parse2();
    var prerelease = (version3, options) => {
      const parsed = parse5(version3, options);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    };
    module2.exports = prerelease;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/compare.js
var require_compare = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/compare.js"(exports2, module2) {
    var SemVer = require_semver();
    var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
    module2.exports = compare;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/rcompare.js"(exports2, module2) {
    var compare = require_compare();
    var rcompare = (a, b, loose) => compare(b, a, loose);
    module2.exports = rcompare;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/compare-loose.js"(exports2, module2) {
    var compare = require_compare();
    var compareLoose = (a, b) => compare(a, b, true);
    module2.exports = compareLoose;
  }
});

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

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/sort.js
var require_sort = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/sort.js"(exports2, module2) {
    var compareBuild = require_compare_build();
    var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
    module2.exports = sort;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/rsort.js
var require_rsort = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/rsort.js"(exports2, module2) {
    var compareBuild = require_compare_build();
    var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
    module2.exports = rsort;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/gt.js
var require_gt = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/gt.js"(exports2, module2) {
    var compare = require_compare();
    var gt = (a, b, loose) => compare(a, b, loose) > 0;
    module2.exports = gt;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/lt.js
var require_lt = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/lt.js"(exports2, module2) {
    var compare = require_compare();
    var lt = (a, b, loose) => compare(a, b, loose) < 0;
    module2.exports = lt;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/eq.js
var require_eq = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/eq.js"(exports2, module2) {
    var compare = require_compare();
    var eq = (a, b, loose) => compare(a, b, loose) === 0;
    module2.exports = eq;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/neq.js
var require_neq = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/neq.js"(exports2, module2) {
    var compare = require_compare();
    var neq = (a, b, loose) => compare(a, b, loose) !== 0;
    module2.exports = neq;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/gte.js
var require_gte = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/gte.js"(exports2, module2) {
    var compare = require_compare();
    var gte = (a, b, loose) => compare(a, b, loose) >= 0;
    module2.exports = gte;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/lte.js
var require_lte = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/lte.js"(exports2, module2) {
    var compare = require_compare();
    var lte = (a, b, loose) => compare(a, b, loose) <= 0;
    module2.exports = lte;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/cmp.js"(exports2, module2) {
    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 = (a, op, b, loose) => {
      switch (op) {
        case "===":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a === b;
        case "!==":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a !== b;
        case "":
        case "=":
        case "==":
          return eq(a, b, loose);
        case "!=":
          return neq(a, b, loose);
        case ">":
          return gt(a, b, loose);
        case ">=":
          return gte(a, b, loose);
        case "<":
          return lt(a, b, loose);
        case "<=":
          return lte(a, b, loose);
        default:
          throw new TypeError(`Invalid operator: ${op}`);
      }
    };
    module2.exports = cmp;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/coerce.js
var require_coerce = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/functions/coerce.js"(exports2, module2) {
    var SemVer = require_semver();
    var parse5 = require_parse2();
    var { safeRe: re, t: t2 } = require_re();
    var coerce2 = (version3, options) => {
      if (version3 instanceof SemVer) {
        return version3;
      }
      if (typeof version3 === "number") {
        version3 = String(version3);
      }
      if (typeof version3 !== "string") {
        return null;
      }
      options = options || {};
      let match2 = null;
      if (!options.rtl) {
        match2 = version3.match(options.includePrerelease ? re[t2.COERCEFULL] : re[t2.COERCE]);
      } else {
        const coerceRtlRegex = options.includePrerelease ? re[t2.COERCERTLFULL] : re[t2.COERCERTL];
        let next;
        while ((next = coerceRtlRegex.exec(version3)) && (!match2 || match2.index + match2[0].length !== version3.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 parse5(`${major}.${minor}.${patch}${prerelease}${build}`, options);
    };
    module2.exports = coerce2;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/internal/lrucache.js"(exports2, module2) {
    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.6.2/node_modules/semver/classes/range.js
var require_range = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/classes/range.js"(exports2, module2) {
    var Range = class _Range {
      constructor(range, options) {
        options = parseOptions2(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.format();
          return this;
        }
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        this.raw = range.trim().split(/\s+/).join(" ");
        this.set = this.raw.split("||").map((r2) => this.parseRange(r2.trim())).filter((c) => c.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((c) => !isNullSet(c[0]));
          if (this.set.length === 0) {
            this.set = [first];
          } else if (this.set.length > 1) {
            for (const c of this.set) {
              if (c.length === 1 && isAny(c[0])) {
                this.set = [c];
                break;
              }
            }
          }
        }
        this.format();
      }
      format() {
        this.range = this.set.map((comps) => comps.join(" ").trim()).join("||").trim();
        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 = cache.get(memoKey);
        if (cached) {
          return cached;
        }
        const loose = this.options.loose;
        const hr = loose ? re[t2.HYPHENRANGELOOSE] : re[t2.HYPHENRANGE];
        range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
        debug("hyphen replace", range);
        range = range.replace(re[t2.COMPARATORTRIM], comparatorTrimReplace);
        debug("comparator trim", range);
        range = range.replace(re[t2.TILDETRIM], tildeTrimReplace);
        debug("tilde trim", range);
        range = range.replace(re[t2.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[t2.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()];
        cache.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(version3) {
        if (!version3) {
          return false;
        }
        if (typeof version3 === "string") {
          try {
            version3 = new SemVer(version3, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i2 = 0; i2 < this.set.length; i2++) {
          if (testSet(this.set[i2], version3, this.options)) {
            return true;
          }
        }
        return false;
      }
    };
    module2.exports = Range;
    var LRU = require_lrucache();
    var cache = new LRU();
    var parseOptions2 = require_parse_options();
    var Comparator = require_comparator();
    var debug = require_debug();
    var SemVer = require_semver();
    var {
      safeRe: re,
      t: t2,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
    var isNullSet = (c) => c.value === "<0.0.0-0";
    var isAny = (c) => c.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((c) => replaceTilde(c, options)).join(" ");
    };
    var replaceTilde = (comp, options) => {
      const r2 = options.loose ? re[t2.TILDELOOSE] : re[t2.TILDE];
      return comp.replace(r2, (_2, M, m2, p, pr) => {
        debug("tilde", comp, _2, M, m2, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m2)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          ret = `>=${M}.${m2}.0 <${M}.${+m2 + 1}.0-0`;
        } else if (pr) {
          debug("replaceTilde pr", pr);
          ret = `>=${M}.${m2}.${p}-${pr} <${M}.${+m2 + 1}.0-0`;
        } else {
          ret = `>=${M}.${m2}.${p} <${M}.${+m2 + 1}.0-0`;
        }
        debug("tilde return", ret);
        return ret;
      });
    };
    var replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
    };
    var replaceCaret = (comp, options) => {
      debug("caret", comp, options);
      const r2 = options.loose ? re[t2.CARETLOOSE] : re[t2.CARET];
      const z2 = options.includePrerelease ? "-0" : "";
      return comp.replace(r2, (_2, M, m2, p, pr) => {
        debug("caret", comp, _2, M, m2, p, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m2)) {
          ret = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`;
        } else if (isX(p)) {
          if (M === "0") {
            ret = `>=${M}.${m2}.0${z2} <${M}.${+m2 + 1}.0-0`;
          } else {
            ret = `>=${M}.${m2}.0${z2} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          debug("replaceCaret pr", pr);
          if (M === "0") {
            if (m2 === "0") {
              ret = `>=${M}.${m2}.${p}-${pr} <${M}.${m2}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m2}.${p}-${pr} <${M}.${+m2 + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m2}.${p}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          debug("no pr");
          if (M === "0") {
            if (m2 === "0") {
              ret = `>=${M}.${m2}.${p}${z2} <${M}.${m2}.${+p + 1}-0`;
            } else {
              ret = `>=${M}.${m2}.${p}${z2} <${M}.${+m2 + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m2}.${p} <${+M + 1}.0.0-0`;
          }
        }
        debug("caret return", ret);
        return ret;
      });
    };
    var replaceXRanges = (comp, options) => {
      debug("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
    };
    var replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r2 = options.loose ? re[t2.XRANGELOOSE] : re[t2.XRANGE];
      return comp.replace(r2, (ret, gtlt, M, m2, p, pr) => {
        debug("xRange", comp, ret, gtlt, M, m2, p, pr);
        const xM = isX(M);
        const xm = xM || isX(m2);
        const xp = xm || isX(p);
        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) {
            m2 = 0;
          }
          p = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m2 = 0;
              p = 0;
            } else {
              m2 = +m2 + 1;
              p = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m2 = +m2 + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m2}.${p}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m2}.0${pr} <${M}.${+m2 + 1}.0-0`;
        }
        debug("xRange return", ret);
        return ret;
      });
    };
    var replaceStars = (comp, options) => {
      debug("replaceStars", comp, options);
      return comp.trim().replace(re[t2.STAR], "");
    };
    var replaceGTE0 = (comp, options) => {
      debug("replaceGTE0", comp, options);
      return comp.trim().replace(re[options.includePrerelease ? t2.GTE0PRE : t2.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, version3, options) => {
      for (let i2 = 0; i2 < set.length; i2++) {
        if (!set[i2].test(version3)) {
          return false;
        }
      }
      if (version3.prerelease.length && !options.includePrerelease) {
        for (let i2 = 0; i2 < set.length; i2++) {
          debug(set[i2].semver);
          if (set[i2].semver === Comparator.ANY) {
            continue;
          }
          if (set[i2].semver.prerelease.length > 0) {
            const allowed = set[i2].semver;
            if (allowed.major === version3.major && allowed.minor === version3.minor && allowed.patch === version3.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    };
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/classes/comparator.js"(exports2, module2) {
    var ANY = Symbol("SemVer ANY");
    var Comparator = class _Comparator {
      static get ANY() {
        return ANY;
      }
      constructor(comp, options) {
        options = parseOptions2(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 r2 = this.options.loose ? re[t2.COMPARATORLOOSE] : re[t2.COMPARATOR];
        const m2 = comp.match(r2);
        if (!m2) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m2[1] !== void 0 ? m2[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m2[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m2[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version3) {
        debug("Comparator.test", version3, this.options.loose);
        if (this.semver === ANY || version3 === ANY) {
          return true;
        }
        if (typeof version3 === "string") {
          try {
            version3 = new SemVer(version3, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version3, 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 = parseOptions2(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 parseOptions2 = require_parse_options();
    var { safeRe: re, t: t2 } = require_re();
    var cmp = require_cmp();
    var debug = require_debug();
    var SemVer = require_semver();
    var Range = require_range();
  }
});

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

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

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

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

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/ranges/min-version.js"(exports2, module2) {
    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 i2 = 0; i2 < range.set.length; ++i2) {
        const comparators = range.set[i2];
        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();
            case "":
            case ">=":
              if (!setMin || gt(compver, setMin)) {
                setMin = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            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.6.2/node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/ranges/valid.js"(exports2, module2) {
    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.6.2/node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/ranges/outside.js"(exports2, module2) {
    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 = (version3, range, hilo, options) => {
      version3 = new SemVer(version3, 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(version3, range, options)) {
        return false;
      }
      for (let i2 = 0; i2 < range.set.length; ++i2) {
        const comparators = range.set[i2];
        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(version3, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version3, low.semver)) {
          return false;
        }
      }
      return true;
    };
    module2.exports = outside;
  }
});

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

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

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

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/ranges/simplify.js"(exports2, module2) {
    var satisfies = require_satisfies();
    var compare = require_compare();
    module2.exports = (versions, range, options) => {
      const set = [];
      let first = null;
      let prev = null;
      const v = versions.sort((a, b) => compare(a, b, options));
      for (const version3 of v) {
        const included = satisfies(version3, range, options);
        if (included) {
          prev = version3;
          if (!first) {
            first = version3;
          }
        } 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 === v[0]) {
          ranges.push("*");
        } else if (!max) {
          ranges.push(`>=${min}`);
        } else if (min === v[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.6.2/node_modules/semver/ranges/subset.js
var require_subset = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/ranges/subset.js"(exports2, module2) {
    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 c of sub) {
        if (c.operator === ">" || c.operator === ">=") {
          gt = higherGT(gt, c, options);
        } else if (c.operator === "<" || c.operator === "<=") {
          lt = lowerLT(lt, c, options);
        } else {
          eqSet.add(c.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 c of dom) {
          if (!satisfies(eq, String(c), 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 c of dom) {
        hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
        hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
        if (gt) {
          if (needDomGTPre) {
            if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c.operator === ">" || c.operator === ">=") {
            higher = higherGT(gt, c, options);
            if (higher === c && higher !== gt) {
              return false;
            }
          } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) {
            return false;
          }
        }
        if (lt) {
          if (needDomLTPre) {
            if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c.operator === "<" || c.operator === "<=") {
            lower2 = lowerLT(lt, c, options);
            if (lower2 === c && lower2 !== lt) {
              return false;
            }
          } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) {
            return false;
          }
        }
        if (!c.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 = (a, b, options) => {
      if (!a) {
        return b;
      }
      const comp = compare(a.semver, b.semver, options);
      return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
    };
    var lowerLT = (a, b, options) => {
      if (!a) {
        return b;
      }
      const comp = compare(a.semver, b.semver, options);
      return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
    };
    module2.exports = subset;
  }
});

// ../node_modules/.pnpm/semver@7.6.2/node_modules/semver/index.js
var require_semver2 = __commonJS({
  "../node_modules/.pnpm/semver@7.6.2/node_modules/semver/index.js"(exports2, module2) {
    var internalRe = require_re();
    var constants = require_constants();
    var SemVer = require_semver();
    var identifiers = require_identifiers();
    var parse5 = require_parse2();
    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: parse5,
      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, ormVersionGt, assertStudioNodeVersion, checkPackage, assertPackages, requiredApiVersion, assertOrmCoreVersion, ormCoreVersions;
var init_utils5 = __esm({
  "src/cli/utils.ts"() {
    "use strict";
    import_semver = __toESM(require_semver2());
    init_views();
    ormVersionGt = async (version3) => {
      const { npmVersion } = await import("drizzle-orm/version");
      if (!import_semver.default.gte(npmVersion, version3)) {
        return false;
      }
      return true;
    };
    assertStudioNodeVersion = () => {
      if (import_semver.default.gte(process.version, "18.0.0"))
        return;
      err("Drizzle Studio requires NodeJS v18 or above");
      process.exit(1);
    };
    checkPackage = async (it) => {
      try {
        await import(it);
        return true;
      } catch (e2) {
        return false;
      }
    };
    assertPackages = async (...pkgs) => {
      try {
        for (let i2 = 0; i2 < pkgs.length; i2++) {
          const it = pkgs[i2];
          await import(it);
        }
      } catch (e2) {
        err(
          `please install required packages: ${pkgs.map((it) => `'${it}'`).join(" ")}`
        );
        process.exit(1);
      }
    };
    requiredApiVersion = 10;
    assertOrmCoreVersion = async () => {
      try {
        const { compatibilityVersion } = await import("drizzle-orm/version");
        await import("drizzle-orm/relations");
        if (compatibilityVersion && compatibilityVersion === requiredApiVersion) {
          return;
        }
        if (!compatibilityVersion || compatibilityVersion < requiredApiVersion) {
          console.log(
            "This version of drizzle-kit requires newer version of drizzle-orm\nPlease update drizzle-orm package to the latest version \u{1F44D}"
          );
        } else {
          console.log(
            "This version of drizzle-kit is outdated\nPlease update drizzle-kit package to the latest version \u{1F44D}"
          );
        }
      } catch (e2) {
        console.log("Please install latest version of drizzle-orm");
      }
      process.exit(1);
    };
    ormCoreVersions = async () => {
      try {
        const { compatibilityVersion, npmVersion } = await import("drizzle-orm/version");
        return { compatibilityVersion, npmVersion };
      } catch (e2) {
        return {};
      }
    };
  }
});

// ../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 i2 = 1; i2 < meta.length; i2++) {
    if (meta[i2] === "base64") {
      base64 = true;
    } else if (meta[i2]) {
      typeFull += `;${meta[i2]}`;
      if (meta[i2].indexOf("charset=") === 0) {
        charset = meta[i2].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_dist = __esm({
  "../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js"() {
    dist_default = dataUriToBuffer;
  }
});

// ../node_modules/.pnpm/web-streams-polyfill@3.2.1/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js
var require_ponyfill_es2018 = __commonJS({
  "../node_modules/.pnpm/web-streams-polyfill@3.2.1/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports2, module2) {
    (function(global2, factory) {
      typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {}));
    })(exports2, function(exports3) {
      "use strict";
      const SymbolPolyfill = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol : (description) => `Symbol(${description})`;
      function noop2() {
        return void 0;
      }
      function getGlobals() {
        if (typeof self !== "undefined") {
          return self;
        } else if (typeof window !== "undefined") {
          return window;
        } else if (typeof global !== "undefined") {
          return global;
        }
        return void 0;
      }
      const globals = getGlobals();
      function typeIsObject(x2) {
        return typeof x2 === "object" && x2 !== null || typeof x2 === "function";
      }
      const rethrowAssertionErrorRejection = noop2;
      const originalPromise = Promise;
      const originalPromiseThen = Promise.prototype.then;
      const originalPromiseResolve = Promise.resolve.bind(originalPromise);
      const originalPromiseReject = Promise.reject.bind(originalPromise);
      function newPromise(executor) {
        return new originalPromise(executor);
      }
      function promiseResolvedWith(value) {
        return originalPromiseResolve(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);
      }
      const queueMicrotask = (() => {
        const globalQueueMicrotask = globals && globals.queueMicrotask;
        if (typeof globalQueueMicrotask === "function") {
          return globalQueueMicrotask;
        }
        const resolvedPromise = promiseResolvedWith(void 0);
        return (fn) => PerformPromiseThen(resolvedPromise, fn);
      })();
      function reflectCall(F2, V, args) {
        if (typeof F2 !== "function") {
          throw new TypeError("Argument is not a function");
        }
        return Function.prototype.apply.call(F2, V, args);
      }
      function promiseCall(F2, V, args) {
        try {
          return promiseResolvedWith(reflectCall(F2, V, args));
        } catch (value) {
          return promiseRejectedWith(value);
        }
      }
      const QUEUE_MAX_ARRAY_SIZE = 16384;
      class SimpleQueue {
        constructor() {
          this._cursor = 0;
          this._size = 0;
          this._front = {
            _elements: [],
            _next: void 0
          };
          this._back = this._front;
          this._cursor = 0;
          this._size = 0;
        }
        get length() {
          return this._size;
        }
        // For exception safety, this method is structured in order:
        // 1. Read state
        // 2. Calculate required state mutations
        // 3. Perform state mutations
        push(element) {
          const oldBack = this._back;
          let newBack = oldBack;
          if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
            newBack = {
              _elements: [],
              _next: void 0
            };
          }
          oldBack._elements.push(element);
          if (newBack !== oldBack) {
            this._back = newBack;
            oldBack._next = newBack;
          }
          ++this._size;
        }
        // Like push(), shift() follows the read -> calculate -> mutate pattern for
        // exception safety.
        shift() {
          const oldFront = this._front;
          let newFront = oldFront;
          const oldCursor = this._cursor;
          let newCursor = oldCursor + 1;
          const elements = oldFront._elements;
          const element = elements[oldCursor];
          if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
            newFront = oldFront._next;
            newCursor = 0;
          }
          --this._size;
          this._cursor = newCursor;
          if (oldFront !== newFront) {
            this._front = newFront;
          }
          elements[oldCursor] = void 0;
          return element;
        }
        // The tricky thing about forEach() is that it can be called
        // re-entrantly. The queue may be mutated inside the callback. It is easy to
        // see that push() within the callback has no negative effects since the end
        // of the queue is checked for on every iteration. If shift() is called
        // repeatedly within the callback then the next iteration may return an
        // element that has been removed. In this case the callback will be called
        // with undefined values until we either "catch up" with elements that still
        // exist or reach the back of the queue.
        forEach(callback) {
          let i2 = this._cursor;
          let node = this._front;
          let elements = node._elements;
          while (i2 !== elements.length || node._next !== void 0) {
            if (i2 === elements.length) {
              node = node._next;
              elements = node._elements;
              i2 = 0;
              if (elements.length === 0) {
                break;
              }
            }
            callback(elements[i2]);
            ++i2;
          }
        }
        // Return the element that would be returned if shift() was called now,
        // without modifying the queue.
        peek() {
          const front = this._front;
          const cursor = this._cursor;
          return front._elements[cursor];
        }
      }
      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) {
        if (reader._ownerReadableStream._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`));
        }
        reader._ownerReadableStream._reader = void 0;
        reader._ownerReadableStream = void 0;
      }
      function readerLockException(name) {
        return new TypeError("Cannot " + name + " a stream using a released reader");
      }
      function defaultReaderClosedPromiseInitialize(reader) {
        reader._closedPromise = newPromise((resolve2, reject) => {
          reader._closedPromise_resolve = resolve2;
          reader._closedPromise_reject = reject;
        });
      }
      function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
        defaultReaderClosedPromiseInitialize(reader);
        defaultReaderClosedPromiseReject(reader, reason);
      }
      function defaultReaderClosedPromiseInitializeAsResolved(reader) {
        defaultReaderClosedPromiseInitialize(reader);
        defaultReaderClosedPromiseResolve(reader);
      }
      function defaultReaderClosedPromiseReject(reader, reason) {
        if (reader._closedPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(reader._closedPromise);
        reader._closedPromise_reject(reason);
        reader._closedPromise_resolve = void 0;
        reader._closedPromise_reject = void 0;
      }
      function defaultReaderClosedPromiseResetToRejected(reader, reason) {
        defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
      }
      function defaultReaderClosedPromiseResolve(reader) {
        if (reader._closedPromise_resolve === void 0) {
          return;
        }
        reader._closedPromise_resolve(void 0);
        reader._closedPromise_resolve = void 0;
        reader._closedPromise_reject = void 0;
      }
      const AbortSteps = SymbolPolyfill("[[AbortSteps]]");
      const ErrorSteps = SymbolPolyfill("[[ErrorSteps]]");
      const CancelSteps = SymbolPolyfill("[[CancelSteps]]");
      const PullSteps = SymbolPolyfill("[[PullSteps]]");
      const NumberIsFinite = Number.isFinite || function(x2) {
        return typeof x2 === "number" && isFinite(x2);
      };
      const MathTrunc = Math.trunc || function(v) {
        return v < 0 ? Math.ceil(v) : Math.floor(v);
      };
      function isDictionary(x2) {
        return typeof x2 === "object" || typeof x2 === "function";
      }
      function assertDictionary(obj, context) {
        if (obj !== void 0 && !isDictionary(obj)) {
          throw new TypeError(`${context} is not an object.`);
        }
      }
      function assertFunction(x2, context) {
        if (typeof x2 !== "function") {
          throw new TypeError(`${context} is not a function.`);
        }
      }
      function isObject(x2) {
        return typeof x2 === "object" && x2 !== null || typeof x2 === "function";
      }
      function assertObject(x2, context) {
        if (!isObject(x2)) {
          throw new TypeError(`${context} is not an object.`);
        }
      }
      function assertRequiredArgument(x2, position, context) {
        if (x2 === void 0) {
          throw new TypeError(`Parameter ${position} is required in '${context}'.`);
        }
      }
      function assertRequiredField(x2, field, context) {
        if (x2 === void 0) {
          throw new TypeError(`${field} is required in '${context}'.`);
        }
      }
      function convertUnrestrictedDouble(value) {
        return Number(value);
      }
      function censorNegativeZero(x2) {
        return x2 === 0 ? 0 : x2;
      }
      function integerPart(x2) {
        return censorNegativeZero(MathTrunc(x2));
      }
      function convertUnsignedLongLongWithEnforceRange(value, context) {
        const lowerBound = 0;
        const upperBound = Number.MAX_SAFE_INTEGER;
        let x2 = Number(value);
        x2 = censorNegativeZero(x2);
        if (!NumberIsFinite(x2)) {
          throw new TypeError(`${context} is not a finite number`);
        }
        x2 = integerPart(x2);
        if (x2 < lowerBound || x2 > upperBound) {
          throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
        }
        if (!NumberIsFinite(x2) || x2 === 0) {
          return 0;
        }
        return x2;
      }
      function assertReadableStream(x2, context) {
        if (!IsReadableStream(x2)) {
          throw new TypeError(`${context} is not a ReadableStream.`);
        }
      }
      function AcquireReadableStreamDefaultReader(stream) {
        return new ReadableStreamDefaultReader(stream);
      }
      function ReadableStreamAddReadRequest(stream, readRequest) {
        stream._reader._readRequests.push(readRequest);
      }
      function ReadableStreamFulfillReadRequest(stream, chunk, done) {
        const reader = stream._reader;
        const readRequest = reader._readRequests.shift();
        if (done) {
          readRequest._closeSteps();
        } else {
          readRequest._chunkSteps(chunk);
        }
      }
      function ReadableStreamGetNumReadRequests(stream) {
        return stream._reader._readRequests.length;
      }
      function ReadableStreamHasDefaultReader(stream) {
        const reader = stream._reader;
        if (reader === void 0) {
          return false;
        }
        if (!IsReadableStreamDefaultReader(reader)) {
          return false;
        }
        return true;
      }
      class ReadableStreamDefaultReader {
        constructor(stream) {
          assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader");
          assertReadableStream(stream, "First parameter");
          if (IsReadableStreamLocked(stream)) {
            throw new TypeError("This stream has already been locked for exclusive reading by another reader");
          }
          ReadableStreamReaderGenericInitialize(this, stream);
          this._readRequests = new SimpleQueue();
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed,
         * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
         */
        cancel(reason = void 0) {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("cancel"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("cancel"));
          }
          return ReadableStreamReaderGenericCancel(this, reason);
        }
        /**
         * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
         *
         * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
         */
        read() {
          if (!IsReadableStreamDefaultReader(this)) {
            return promiseRejectedWith(defaultReaderBrandCheckException("read"));
          }
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("read from"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve2, reject) => {
            resolvePromise = resolve2;
            rejectPromise = reject;
          });
          const readRequest = {
            _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
            _closeSteps: () => resolvePromise({ value: void 0, done: true }),
            _errorSteps: (e2) => rejectPromise(e2)
          };
          ReadableStreamDefaultReaderRead(this, readRequest);
          return 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;
          }
          if (this._readRequests.length > 0) {
            throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");
          }
          ReadableStreamReaderGenericRelease(this);
        }
      }
      Object.defineProperties(ReadableStreamDefaultReader.prototype, {
        cancel: { enumerable: true },
        read: { enumerable: true },
        releaseLock: { enumerable: true },
        closed: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
          value: "ReadableStreamDefaultReader",
          configurable: true
        });
      }
      function IsReadableStreamDefaultReader(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_readRequests")) {
          return false;
        }
        return x2 instanceof ReadableStreamDefaultReader;
      }
      function ReadableStreamDefaultReaderRead(reader, readRequest) {
        const stream = reader._ownerReadableStream;
        stream._disturbed = true;
        if (stream._state === "closed") {
          readRequest._closeSteps();
        } else if (stream._state === "errored") {
          readRequest._errorSteps(stream._storedError);
        } else {
          stream._readableStreamController[PullSteps](readRequest);
        }
      }
      function 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;
          if (reader._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("iterate"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve2, reject) => {
            resolvePromise = resolve2;
            rejectPromise = reject;
          });
          const readRequest = {
            _chunkSteps: (chunk) => {
              this._ongoingPromise = void 0;
              queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
            },
            _closeSteps: () => {
              this._ongoingPromise = void 0;
              this._isFinished = true;
              ReadableStreamReaderGenericRelease(reader);
              resolvePromise({ value: void 0, done: true });
            },
            _errorSteps: (reason) => {
              this._ongoingPromise = void 0;
              this._isFinished = true;
              ReadableStreamReaderGenericRelease(reader);
              rejectPromise(reason);
            }
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
          return promise;
        }
        _returnSteps(value) {
          if (this._isFinished) {
            return Promise.resolve({ value, done: true });
          }
          this._isFinished = true;
          const reader = this._reader;
          if (reader._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("finish iterating"));
          }
          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);
        }
      };
      if (AsyncIteratorPrototype !== void 0) {
        Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
      }
      function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
        const reader = AcquireReadableStreamDefaultReader(stream);
        const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
        const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
        iterator._asyncIteratorImpl = impl;
        return iterator;
      }
      function IsReadableStreamAsyncIterator(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_asyncIteratorImpl")) {
          return false;
        }
        try {
          return x2._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl;
        } catch (_a) {
          return false;
        }
      }
      function streamAsyncIteratorBrandCheckException(name) {
        return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
      }
      const NumberIsNaN = Number.isNaN || function(x2) {
        return x2 !== x2;
      };
      function CreateArrayFromList(elements) {
        return elements.slice();
      }
      function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
        new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
      }
      function TransferArrayBuffer(O) {
        return O;
      }
      function IsDetachedBuffer(O) {
        return false;
      }
      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 IsNonNegativeNumber(v) {
        if (typeof v !== "number") {
          return false;
        }
        if (NumberIsNaN(v)) {
          return false;
        }
        if (v < 0) {
          return false;
        }
        return true;
      }
      function CloneAsUint8Array(O) {
        const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
        return new Uint8Array(buffer);
      }
      function DequeueValue(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;
      }
      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))
            ;
          ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
        }
        respondWithNewView(view4) {
          if (!IsReadableStreamBYOBRequest(this)) {
            throw byobRequestBrandCheckException("respondWithNewView");
          }
          assertRequiredArgument(view4, 1, "respondWithNewView");
          if (!ArrayBuffer.isView(view4)) {
            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(view4.buffer))
            ;
          ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view4);
        }
      }
      Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
        respond: { enumerable: true },
        respondWithNewView: { enumerable: true },
        view: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
          value: "ReadableStreamBYOBRequest",
          configurable: true
        });
      }
      class ReadableByteStreamController {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the current BYOB pull request, or `null` if there isn't one.
         */
        get byobRequest() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("byobRequest");
          }
          return ReadableByteStreamControllerGetBYOBRequest(this);
        }
        /**
         * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
         * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
         */
        get desiredSize() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("desiredSize");
          }
          return ReadableByteStreamControllerGetDesiredSize(this);
        }
        /**
         * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
         * the stream, but once those are read, the stream will become closed.
         */
        close() {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("close");
          }
          if (this._closeRequested) {
            throw new TypeError("The stream has already been closed; do not close it again!");
          }
          const state = this._controlledReadableByteStream._state;
          if (state !== "readable") {
            throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
          }
          ReadableByteStreamControllerClose(this);
        }
        enqueue(chunk) {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("enqueue");
          }
          assertRequiredArgument(chunk, 1, "enqueue");
          if (!ArrayBuffer.isView(chunk)) {
            throw new TypeError("chunk must be an array buffer view");
          }
          if (chunk.byteLength === 0) {
            throw new TypeError("chunk must have non-zero byteLength");
          }
          if (chunk.buffer.byteLength === 0) {
            throw new TypeError(`chunk's buffer must have non-zero byteLength`);
          }
          if (this._closeRequested) {
            throw new TypeError("stream is closed or draining");
          }
          const state = this._controlledReadableByteStream._state;
          if (state !== "readable") {
            throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
          }
          ReadableByteStreamControllerEnqueue(this, chunk);
        }
        /**
         * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
         */
        error(e2 = void 0) {
          if (!IsReadableByteStreamController(this)) {
            throw byteStreamControllerBrandCheckException("error");
          }
          ReadableByteStreamControllerError(this, e2);
        }
        /** @internal */
        [CancelSteps](reason) {
          ReadableByteStreamControllerClearPendingPullIntos(this);
          ResetQueue(this);
          const result = this._cancelAlgorithm(reason);
          ReadableByteStreamControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [PullSteps](readRequest) {
          const stream = this._controlledReadableByteStream;
          if (this._queueTotalSize > 0) {
            const entry = this._queue.shift();
            this._queueTotalSize -= entry.byteLength;
            ReadableByteStreamControllerHandleQueueDrain(this);
            const view4 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
            readRequest._chunkSteps(view4);
            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,
              elementSize: 1,
              viewConstructor: Uint8Array,
              readerType: "default"
            };
            this._pendingPullIntos.push(pullIntoDescriptor);
          }
          ReadableStreamAddReadRequest(stream, readRequest);
          ReadableByteStreamControllerCallPullIfNeeded(this);
        }
      }
      Object.defineProperties(ReadableByteStreamController.prototype, {
        close: { enumerable: true },
        enqueue: { enumerable: true },
        error: { enumerable: true },
        byobRequest: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
          value: "ReadableByteStreamController",
          configurable: true
        });
      }
      function IsReadableByteStreamController(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableByteStream")) {
          return false;
        }
        return x2 instanceof ReadableByteStreamController;
      }
      function IsReadableStreamBYOBRequest(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_associatedReadableByteStreamController")) {
          return false;
        }
        return x2 instanceof ReadableStreamBYOBRequest;
      }
      function ReadableByteStreamControllerCallPullIfNeeded(controller) {
        const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
        if (!shouldPull) {
          return;
        }
        if (controller._pulling) {
          controller._pullAgain = true;
          return;
        }
        controller._pulling = true;
        const pullPromise = controller._pullAlgorithm();
        uponPromise(pullPromise, () => {
          controller._pulling = false;
          if (controller._pullAgain) {
            controller._pullAgain = false;
            ReadableByteStreamControllerCallPullIfNeeded(controller);
          }
        }, (e2) => {
          ReadableByteStreamControllerError(controller, e2);
        });
      }
      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 ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
        const elementSize = pullIntoDescriptor.elementSize;
        const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
        const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
        const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
        const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
        let totalBytesToCopyRemaining = maxBytesToCopy;
        let ready = false;
        if (maxAlignedBytes > currentAlignedBytes) {
          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 ReadableByteStreamControllerPullInto(controller, view4, readIntoRequest) {
        const stream = controller._controlledReadableByteStream;
        let elementSize = 1;
        if (view4.constructor !== DataView) {
          elementSize = view4.constructor.BYTES_PER_ELEMENT;
        }
        const ctor = view4.constructor;
        const buffer = TransferArrayBuffer(view4.buffer);
        const pullIntoDescriptor = {
          buffer,
          bufferByteLength: buffer.byteLength,
          byteOffset: view4.byteOffset,
          byteLength: view4.byteLength,
          bytesFilled: 0,
          elementSize,
          viewConstructor: ctor,
          readerType: "byob"
        };
        if (controller._pendingPullIntos.length > 0) {
          controller._pendingPullIntos.push(pullIntoDescriptor);
          ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
          return;
        }
        if (stream._state === "closed") {
          const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
          readIntoRequest._closeSteps(emptyView);
          return;
        }
        if (controller._queueTotalSize > 0) {
          if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
            const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
            ReadableByteStreamControllerHandleQueueDrain(controller);
            readIntoRequest._chunkSteps(filledView);
            return;
          }
          if (controller._closeRequested) {
            const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e2);
            readIntoRequest._errorSteps(e2);
            return;
          }
        }
        controller._pendingPullIntos.push(pullIntoDescriptor);
        ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
        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.bytesFilled < pullIntoDescriptor.elementSize) {
          return;
        }
        ReadableByteStreamControllerShiftPendingPullInto(controller);
        const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
        if (remainderSize > 0) {
          const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
          const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
        }
        pullIntoDescriptor.bytesFilled -= remainderSize;
        ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
        ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
      }
      function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        ReadableByteStreamControllerInvalidateBYOBRequest(controller);
        const state = controller._controlledReadableByteStream._state;
        if (state === "closed") {
          ReadableByteStreamControllerRespondInClosedState(controller);
        } 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 > 0) {
            const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer");
            ReadableByteStreamControllerError(controller, e2);
            throw e2;
          }
        }
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamClose(stream);
      }
      function ReadableByteStreamControllerEnqueue(controller, chunk) {
        const stream = controller._controlledReadableByteStream;
        if (controller._closeRequested || stream._state !== "readable") {
          return;
        }
        const buffer = chunk.buffer;
        const byteOffset = chunk.byteOffset;
        const byteLength = chunk.byteLength;
        const transferredBuffer = TransferArrayBuffer(buffer);
        if (controller._pendingPullIntos.length > 0) {
          const firstPendingPullInto = controller._pendingPullIntos.peek();
          if (IsDetachedBuffer(firstPendingPullInto.buffer))
            ;
          firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
        }
        ReadableByteStreamControllerInvalidateBYOBRequest(controller);
        if (ReadableStreamHasDefaultReader(stream)) {
          if (ReadableStreamGetNumReadRequests(stream) === 0) {
            ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          } else {
            if (controller._pendingPullIntos.length > 0) {
              ReadableByteStreamControllerShiftPendingPullInto(controller);
            }
            const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
            ReadableStreamFulfillReadRequest(stream, transferredView, false);
          }
        } else if (ReadableStreamHasBYOBReader(stream)) {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
        } else {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
        }
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      function ReadableByteStreamControllerError(controller, e2) {
        const stream = controller._controlledReadableByteStream;
        if (stream._state !== "readable") {
          return;
        }
        ReadableByteStreamControllerClearPendingPullIntos(controller);
        ResetQueue(controller);
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamError(stream, e2);
      }
      function ReadableByteStreamControllerGetBYOBRequest(controller) {
        if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
          const firstDescriptor = controller._pendingPullIntos.peek();
          const view4 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
          const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
          SetUpReadableStreamBYOBRequest(byobRequest, controller, view4);
          controller._byobRequest = byobRequest;
        }
        return controller._byobRequest;
      }
      function ReadableByteStreamControllerGetDesiredSize(controller) {
        const state = controller._controlledReadableByteStream._state;
        if (state === "errored") {
          return null;
        }
        if (state === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function ReadableByteStreamControllerRespond(controller, bytesWritten) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state = controller._controlledReadableByteStream._state;
        if (state === "closed") {
          if (bytesWritten !== 0) {
            throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");
          }
        } else {
          if (bytesWritten === 0) {
            throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");
          }
          if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
            throw new RangeError("bytesWritten out of range");
          }
        }
        firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
        ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
      }
      function ReadableByteStreamControllerRespondWithNewView(controller, view4) {
        const firstDescriptor = controller._pendingPullIntos.peek();
        const state = controller._controlledReadableByteStream._state;
        if (state === "closed") {
          if (view4.byteLength !== 0) {
            throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
          }
        } else {
          if (view4.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 !== view4.byteOffset) {
          throw new RangeError("The region specified by view does not match byobRequest");
        }
        if (firstDescriptor.bufferByteLength !== view4.buffer.byteLength) {
          throw new RangeError("The buffer of view has different capacity than byobRequest");
        }
        if (firstDescriptor.bytesFilled + view4.byteLength > firstDescriptor.byteLength) {
          throw new RangeError("The region specified by view is larger than byobRequest");
        }
        const viewByteLength = view4.byteLength;
        firstDescriptor.buffer = TransferArrayBuffer(view4.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);
        }, (r2) => {
          ReadableByteStreamControllerError(controller, r2);
        });
      }
      function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
        const controller = Object.create(ReadableByteStreamController.prototype);
        let startAlgorithm = () => void 0;
        let pullAlgorithm = () => promiseResolvedWith(void 0);
        let cancelAlgorithm = () => promiseResolvedWith(void 0);
        if (underlyingByteSource.start !== void 0) {
          startAlgorithm = () => underlyingByteSource.start(controller);
        }
        if (underlyingByteSource.pull !== void 0) {
          pullAlgorithm = () => underlyingByteSource.pull(controller);
        }
        if (underlyingByteSource.cancel !== void 0) {
          cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason);
        }
        const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
        if (autoAllocateChunkSize === 0) {
          throw new TypeError("autoAllocateChunkSize must be greater than 0");
        }
        SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
      }
      function SetUpReadableStreamBYOBRequest(request, controller, view4) {
        request._associatedReadableByteStreamController = controller;
        request._view = view4;
      }
      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 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);
        }
        /**
         * Attempts to reads bytes into view, and returns a promise resolved with the result.
         *
         * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
         */
        read(view4) {
          if (!IsReadableStreamBYOBReader(this)) {
            return promiseRejectedWith(byobReaderBrandCheckException("read"));
          }
          if (!ArrayBuffer.isView(view4)) {
            return promiseRejectedWith(new TypeError("view must be an array buffer view"));
          }
          if (view4.byteLength === 0) {
            return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
          }
          if (view4.buffer.byteLength === 0) {
            return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
          }
          if (IsDetachedBuffer(view4.buffer))
            ;
          if (this._ownerReadableStream === void 0) {
            return promiseRejectedWith(readerLockException("read from"));
          }
          let resolvePromise;
          let rejectPromise;
          const promise = newPromise((resolve2, reject) => {
            resolvePromise = resolve2;
            rejectPromise = reject;
          });
          const readIntoRequest = {
            _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
            _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }),
            _errorSteps: (e2) => rejectPromise(e2)
          };
          ReadableStreamBYOBReaderRead(this, view4, 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;
          }
          if (this._readIntoRequests.length > 0) {
            throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");
          }
          ReadableStreamReaderGenericRelease(this);
        }
      }
      Object.defineProperties(ReadableStreamBYOBReader.prototype, {
        cancel: { enumerable: true },
        read: { enumerable: true },
        releaseLock: { enumerable: true },
        closed: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
          value: "ReadableStreamBYOBReader",
          configurable: true
        });
      }
      function IsReadableStreamBYOBReader(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_readIntoRequests")) {
          return false;
        }
        return x2 instanceof ReadableStreamBYOBReader;
      }
      function ReadableStreamBYOBReaderRead(reader, view4, readIntoRequest) {
        const stream = reader._ownerReadableStream;
        stream._disturbed = true;
        if (stream._state === "errored") {
          readIntoRequest._errorSteps(stream._storedError);
        } else {
          ReadableByteStreamControllerPullInto(stream._readableStreamController, view4, readIntoRequest);
        }
      }
      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(x2, context) {
        if (!IsWritableStream(x2)) {
          throw new TypeError(`${context} is not a WritableStream.`);
        }
      }
      function isAbortSignal2(value) {
        if (typeof value !== "object" || value === null) {
          return false;
        }
        try {
          return typeof value.aborted === "boolean";
        } catch (_a) {
          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 }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
          value: "WritableStream",
          configurable: true
        });
      }
      function AcquireWritableStreamDefaultWriter(stream) {
        return new WritableStreamDefaultWriter(stream);
      }
      function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream = Object.create(WritableStream.prototype);
        InitializeWritableStream(stream);
        const controller = Object.create(WritableStreamDefaultController.prototype);
        SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
        return stream;
      }
      function InitializeWritableStream(stream) {
        stream._state = "writable";
        stream._storedError = void 0;
        stream._writer = void 0;
        stream._writableStreamController = void 0;
        stream._writeRequests = new SimpleQueue();
        stream._inFlightWriteRequest = void 0;
        stream._closeRequest = void 0;
        stream._inFlightCloseRequest = void 0;
        stream._pendingAbortRequest = void 0;
        stream._backpressure = false;
      }
      function IsWritableStream(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_writableStreamController")) {
          return false;
        }
        return x2 instanceof WritableStream;
      }
      function IsWritableStreamLocked(stream) {
        if (stream._writer === void 0) {
          return false;
        }
        return true;
      }
      function WritableStreamAbort(stream, reason) {
        var _a;
        if (stream._state === "closed" || stream._state === "errored") {
          return promiseResolvedWith(void 0);
        }
        stream._writableStreamController._abortReason = reason;
        (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
        const state = stream._state;
        if (state === "closed" || state === "errored") {
          return promiseResolvedWith(void 0);
        }
        if (stream._pendingAbortRequest !== void 0) {
          return stream._pendingAbortRequest._promise;
        }
        let wasAlreadyErroring = false;
        if (state === "erroring") {
          wasAlreadyErroring = true;
          reason = void 0;
        }
        const promise = newPromise((resolve2, reject) => {
          stream._pendingAbortRequest = {
            _promise: void 0,
            _resolve: resolve2,
            _reject: reject,
            _reason: reason,
            _wasAlreadyErroring: wasAlreadyErroring
          };
        });
        stream._pendingAbortRequest._promise = promise;
        if (!wasAlreadyErroring) {
          WritableStreamStartErroring(stream, reason);
        }
        return promise;
      }
      function WritableStreamClose(stream) {
        const state = stream._state;
        if (state === "closed" || state === "errored") {
          return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
        }
        const promise = newPromise((resolve2, reject) => {
          const closeRequest = {
            _resolve: resolve2,
            _reject: reject
          };
          stream._closeRequest = closeRequest;
        });
        const writer = stream._writer;
        if (writer !== void 0 && stream._backpressure && state === "writable") {
          defaultWriterReadyPromiseResolve(writer);
        }
        WritableStreamDefaultControllerClose(stream._writableStreamController);
        return promise;
      }
      function WritableStreamAddWriteRequest(stream) {
        const promise = newPromise((resolve2, reject) => {
          const writeRequest = {
            _resolve: resolve2,
            _reject: reject
          };
          stream._writeRequests.push(writeRequest);
        });
        return promise;
      }
      function WritableStreamDealWithRejection(stream, error2) {
        const state = stream._state;
        if (state === "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);
        }, (reason) => {
          abortRequest._reject(reason);
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
        });
      }
      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 state = stream._state;
        if (state === "erroring") {
          stream._storedError = void 0;
          if (stream._pendingAbortRequest !== void 0) {
            stream._pendingAbortRequest._resolve();
            stream._pendingAbortRequest = void 0;
          }
        }
        stream._state = "closed";
        const writer = stream._writer;
        if (writer !== void 0) {
          defaultWriterClosedPromiseResolve(writer);
        }
      }
      function WritableStreamFinishInFlightCloseWithError(stream, 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 state = stream._state;
          if (state === "writable") {
            if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
              defaultWriterReadyPromiseInitialize(this);
            } else {
              defaultWriterReadyPromiseInitializeAsResolved(this);
            }
            defaultWriterClosedPromiseInitialize(this);
          } else if (state === "erroring") {
            defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
            defaultWriterClosedPromiseInitialize(this);
          } else if (state === "closed") {
            defaultWriterReadyPromiseInitializeAsResolved(this);
            defaultWriterClosedPromiseInitializeAsResolved(this);
          } else {
            const storedError = stream._storedError;
            defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
            defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
          }
        }
        /**
         * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
         * the writer’s lock is released before the stream finishes closing.
         */
        get closed() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("closed"));
          }
          return this._closedPromise;
        }
        /**
         * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
         * A producer can use this information to determine the right amount of data to write.
         *
         * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
         * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
         * the writer’s lock is released.
         */
        get desiredSize() {
          if (!IsWritableStreamDefaultWriter(this)) {
            throw defaultWriterBrandCheckException("desiredSize");
          }
          if (this._ownerWritableStream === void 0) {
            throw defaultWriterLockException("desiredSize");
          }
          return WritableStreamDefaultWriterGetDesiredSize(this);
        }
        /**
         * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
         * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
         * back to zero or below, the getter will return a new promise that stays pending until the next transition.
         *
         * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
         * rejected.
         */
        get ready() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("ready"));
          }
          return this._readyPromise;
        }
        /**
         * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
         */
        abort(reason = void 0) {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("abort"));
          }
          if (this._ownerWritableStream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("abort"));
          }
          return WritableStreamDefaultWriterAbort(this, reason);
        }
        /**
         * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
         */
        close() {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("close"));
          }
          const stream = this._ownerWritableStream;
          if (stream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("close"));
          }
          if (WritableStreamCloseQueuedOrInFlight(stream)) {
            return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
          }
          return WritableStreamDefaultWriterClose(this);
        }
        /**
         * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
         * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
         * now on; otherwise, the writer will appear closed.
         *
         * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
         * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
         * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
         * other producers from writing in an interleaved manner.
         */
        releaseLock() {
          if (!IsWritableStreamDefaultWriter(this)) {
            throw defaultWriterBrandCheckException("releaseLock");
          }
          const stream = this._ownerWritableStream;
          if (stream === void 0) {
            return;
          }
          WritableStreamDefaultWriterRelease(this);
        }
        write(chunk = void 0) {
          if (!IsWritableStreamDefaultWriter(this)) {
            return promiseRejectedWith(defaultWriterBrandCheckException("write"));
          }
          if (this._ownerWritableStream === void 0) {
            return promiseRejectedWith(defaultWriterLockException("write to"));
          }
          return WritableStreamDefaultWriterWrite(this, chunk);
        }
      }
      Object.defineProperties(WritableStreamDefaultWriter.prototype, {
        abort: { enumerable: true },
        close: { enumerable: true },
        releaseLock: { enumerable: true },
        write: { enumerable: true },
        closed: { enumerable: true },
        desiredSize: { enumerable: true },
        ready: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
          value: "WritableStreamDefaultWriter",
          configurable: true
        });
      }
      function IsWritableStreamDefaultWriter(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_ownerWritableStream")) {
          return false;
        }
        return x2 instanceof WritableStreamDefaultWriter;
      }
      function WritableStreamDefaultWriterAbort(writer, reason) {
        const stream = writer._ownerWritableStream;
        return WritableStreamAbort(stream, reason);
      }
      function WritableStreamDefaultWriterClose(writer) {
        const stream = writer._ownerWritableStream;
        return WritableStreamClose(stream);
      }
      function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
        const stream = writer._ownerWritableStream;
        const state = stream._state;
        if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (state === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        return WritableStreamDefaultWriterClose(writer);
      }
      function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, 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 state = stream._state;
        if (state === "errored" || state === "erroring") {
          return null;
        }
        if (state === "closed") {
          return 0;
        }
        return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
      }
      function WritableStreamDefaultWriterRelease(writer) {
        const stream = writer._ownerWritableStream;
        const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
        WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
        WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
        stream._writer = void 0;
        writer._ownerWritableStream = void 0;
      }
      function WritableStreamDefaultWriterWrite(writer, chunk) {
        const stream = writer._ownerWritableStream;
        const controller = stream._writableStreamController;
        const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
        if (stream !== writer._ownerWritableStream) {
          return promiseRejectedWith(defaultWriterLockException("write to"));
        }
        const state = stream._state;
        if (state === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") {
          return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to"));
        }
        if (state === "erroring") {
          return promiseRejectedWith(stream._storedError);
        }
        const 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(e2 = void 0) {
          if (!IsWritableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$2("error");
          }
          const state = this._controlledWritableStream._state;
          if (state !== "writable") {
            return;
          }
          WritableStreamDefaultControllerError(this, e2);
        }
        /** @internal */
        [AbortSteps](reason) {
          const result = this._abortAlgorithm(reason);
          WritableStreamDefaultControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [ErrorSteps]() {
          ResetQueue(this);
        }
      }
      Object.defineProperties(WritableStreamDefaultController.prototype, {
        abortReason: { enumerable: true },
        signal: { enumerable: true },
        error: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
          value: "WritableStreamDefaultController",
          configurable: true
        });
      }
      function IsWritableStreamDefaultController(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_controlledWritableStream")) {
          return false;
        }
        return x2 instanceof WritableStreamDefaultController;
      }
      function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledWritableStream = stream;
        stream._writableStreamController = controller;
        controller._queue = void 0;
        controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._abortReason = void 0;
        controller._abortController = createAbortController();
        controller._started = false;
        controller._strategySizeAlgorithm = sizeAlgorithm;
        controller._strategyHWM = highWaterMark;
        controller._writeAlgorithm = writeAlgorithm;
        controller._closeAlgorithm = closeAlgorithm;
        controller._abortAlgorithm = abortAlgorithm;
        const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
        WritableStreamUpdateBackpressure(stream, backpressure);
        const startResult = startAlgorithm();
        const startPromise = promiseResolvedWith(startResult);
        uponPromise(startPromise, () => {
          controller._started = true;
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
        }, (r2) => {
          controller._started = true;
          WritableStreamDealWithRejection(stream, r2);
        });
      }
      function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
        const controller = Object.create(WritableStreamDefaultController.prototype);
        let startAlgorithm = () => void 0;
        let writeAlgorithm = () => promiseResolvedWith(void 0);
        let closeAlgorithm = () => promiseResolvedWith(void 0);
        let abortAlgorithm = () => promiseResolvedWith(void 0);
        if (underlyingSink.start !== void 0) {
          startAlgorithm = () => underlyingSink.start(controller);
        }
        if (underlyingSink.write !== void 0) {
          writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller);
        }
        if (underlyingSink.close !== void 0) {
          closeAlgorithm = () => underlyingSink.close();
        }
        if (underlyingSink.abort !== void 0) {
          abortAlgorithm = (reason) => underlyingSink.abort(reason);
        }
        SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
      }
      function WritableStreamDefaultControllerClearAlgorithms(controller) {
        controller._writeAlgorithm = void 0;
        controller._closeAlgorithm = void 0;
        controller._abortAlgorithm = void 0;
        controller._strategySizeAlgorithm = void 0;
      }
      function WritableStreamDefaultControllerClose(controller) {
        EnqueueValueWithSize(controller, closeSentinel, 0);
        WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
      }
      function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
        try {
          return controller._strategySizeAlgorithm(chunk);
        } catch (chunkSizeE) {
          WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
          return 1;
        }
      }
      function WritableStreamDefaultControllerGetDesiredSize(controller) {
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
        try {
          EnqueueValueWithSize(controller, chunk, chunkSize);
        } catch (enqueueE) {
          WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
          return;
        }
        const stream = controller._controlledWritableStream;
        if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") {
          const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
          WritableStreamUpdateBackpressure(stream, backpressure);
        }
        WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
      }
      function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
        const stream = controller._controlledWritableStream;
        if (!controller._started) {
          return;
        }
        if (stream._inFlightWriteRequest !== void 0) {
          return;
        }
        const state = stream._state;
        if (state === "erroring") {
          WritableStreamFinishErroring(stream);
          return;
        }
        if (controller._queue.length === 0) {
          return;
        }
        const value = PeekQueueValue(controller);
        if (value === closeSentinel) {
          WritableStreamDefaultControllerProcessClose(controller);
        } else {
          WritableStreamDefaultControllerProcessWrite(controller, value);
        }
      }
      function WritableStreamDefaultControllerErrorIfNeeded(controller, 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);
        }, (reason) => {
          WritableStreamFinishInFlightCloseWithError(stream, reason);
        });
      }
      function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
        const stream = controller._controlledWritableStream;
        WritableStreamMarkFirstWriteRequestInFlight(stream);
        const sinkWritePromise = controller._writeAlgorithm(chunk);
        uponPromise(sinkWritePromise, () => {
          WritableStreamFinishInFlightWrite(stream);
          const state = stream._state;
          DequeueValue(controller);
          if (!WritableStreamCloseQueuedOrInFlight(stream) && state === "writable") {
            const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
            WritableStreamUpdateBackpressure(stream, backpressure);
          }
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
        }, (reason) => {
          if (stream._state === "writable") {
            WritableStreamDefaultControllerClearAlgorithms(controller);
          }
          WritableStreamFinishInFlightWriteWithError(stream, reason);
        });
      }
      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((resolve2, reject) => {
          writer._closedPromise_resolve = resolve2;
          writer._closedPromise_reject = reject;
          writer._closedPromiseState = "pending";
        });
      }
      function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
        defaultWriterClosedPromiseInitialize(writer);
        defaultWriterClosedPromiseReject(writer, reason);
      }
      function defaultWriterClosedPromiseInitializeAsResolved(writer) {
        defaultWriterClosedPromiseInitialize(writer);
        defaultWriterClosedPromiseResolve(writer);
      }
      function defaultWriterClosedPromiseReject(writer, reason) {
        if (writer._closedPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(writer._closedPromise);
        writer._closedPromise_reject(reason);
        writer._closedPromise_resolve = void 0;
        writer._closedPromise_reject = void 0;
        writer._closedPromiseState = "rejected";
      }
      function defaultWriterClosedPromiseResetToRejected(writer, reason) {
        defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
      }
      function defaultWriterClosedPromiseResolve(writer) {
        if (writer._closedPromise_resolve === void 0) {
          return;
        }
        writer._closedPromise_resolve(void 0);
        writer._closedPromise_resolve = void 0;
        writer._closedPromise_reject = void 0;
        writer._closedPromiseState = "resolved";
      }
      function defaultWriterReadyPromiseInitialize(writer) {
        writer._readyPromise = newPromise((resolve2, reject) => {
          writer._readyPromise_resolve = resolve2;
          writer._readyPromise_reject = reject;
        });
        writer._readyPromiseState = "pending";
      }
      function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
        defaultWriterReadyPromiseInitialize(writer);
        defaultWriterReadyPromiseReject(writer, reason);
      }
      function defaultWriterReadyPromiseInitializeAsResolved(writer) {
        defaultWriterReadyPromiseInitialize(writer);
        defaultWriterReadyPromiseResolve(writer);
      }
      function defaultWriterReadyPromiseReject(writer, reason) {
        if (writer._readyPromise_reject === void 0) {
          return;
        }
        setPromiseIsHandledToTrue(writer._readyPromise);
        writer._readyPromise_reject(reason);
        writer._readyPromise_resolve = void 0;
        writer._readyPromise_reject = void 0;
        writer._readyPromiseState = "rejected";
      }
      function defaultWriterReadyPromiseReset(writer) {
        defaultWriterReadyPromiseInitialize(writer);
      }
      function defaultWriterReadyPromiseResetToRejected(writer, reason) {
        defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
      }
      function defaultWriterReadyPromiseResolve(writer) {
        if (writer._readyPromise_resolve === void 0) {
          return;
        }
        writer._readyPromise_resolve(void 0);
        writer._readyPromise_resolve = void 0;
        writer._readyPromise_reject = void 0;
        writer._readyPromiseState = "fulfilled";
      }
      const NativeDOMException = typeof DOMException !== "undefined" ? DOMException : void 0;
      function isDOMExceptionConstructor(ctor) {
        if (!(typeof ctor === "function" || typeof ctor === "object")) {
          return false;
        }
        try {
          new ctor();
          return true;
        } catch (_a) {
          return false;
        }
      }
      function createDOMExceptionPolyfill() {
        const ctor = function DOMException3(message, name) {
          this.message = message || "";
          this.name = name || "Error";
          if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
          }
        };
        ctor.prototype = Object.create(Error.prototype);
        Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true });
        return ctor;
      }
      const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
      function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
        const reader = AcquireReadableStreamDefaultReader(source);
        const writer = AcquireWritableStreamDefaultWriter(dest);
        source._disturbed = true;
        let shuttingDown = false;
        let currentWrite = promiseResolvedWith(void 0);
        return newPromise((resolve2, reject) => {
          let abortAlgorithm;
          if (signal !== void 0) {
            abortAlgorithm = () => {
              const error2 = new DOMException$1("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);
            }
          });
          isOrBecomesErrored(dest, writer._closedPromise, (storedError) => {
            if (!preventCancel) {
              shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
            } else {
              shutdown(true, storedError);
            }
          });
          isOrBecomesClosed(source, reader._closedPromise, () => {
            if (!preventClose) {
              shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
            } else {
              shutdown();
            }
          });
          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));
            }
          }
          function shutdown(isError2, error2) {
            if (shuttingDown) {
              return;
            }
            shuttingDown = true;
            if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
              uponFulfillment(waitForWritesToFinish(), () => finalize(isError2, error2));
            } else {
              finalize(isError2, error2);
            }
          }
          function finalize(isError2, error2) {
            WritableStreamDefaultWriterRelease(writer);
            ReadableStreamReaderGenericRelease(reader);
            if (signal !== void 0) {
              signal.removeEventListener("abort", abortAlgorithm);
            }
            if (isError2) {
              reject(error2);
            } else {
              resolve2(void 0);
            }
          }
        });
      }
      class ReadableStreamDefaultController {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
         * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
         */
        get desiredSize() {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("desiredSize");
          }
          return ReadableStreamDefaultControllerGetDesiredSize(this);
        }
        /**
         * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
         * the stream, but once those are read, the stream will become closed.
         */
        close() {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("close");
          }
          if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
            throw new TypeError("The stream is not in a state that permits close");
          }
          ReadableStreamDefaultControllerClose(this);
        }
        enqueue(chunk = void 0) {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("enqueue");
          }
          if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
            throw new TypeError("The stream is not in a state that permits enqueue");
          }
          return ReadableStreamDefaultControllerEnqueue(this, chunk);
        }
        /**
         * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
         */
        error(e2 = void 0) {
          if (!IsReadableStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException$1("error");
          }
          ReadableStreamDefaultControllerError(this, e2);
        }
        /** @internal */
        [CancelSteps](reason) {
          ResetQueue(this);
          const result = this._cancelAlgorithm(reason);
          ReadableStreamDefaultControllerClearAlgorithms(this);
          return result;
        }
        /** @internal */
        [PullSteps](readRequest) {
          const stream = this._controlledReadableStream;
          if (this._queue.length > 0) {
            const chunk = DequeueValue(this);
            if (this._closeRequested && this._queue.length === 0) {
              ReadableStreamDefaultControllerClearAlgorithms(this);
              ReadableStreamClose(stream);
            } else {
              ReadableStreamDefaultControllerCallPullIfNeeded(this);
            }
            readRequest._chunkSteps(chunk);
          } else {
            ReadableStreamAddReadRequest(stream, readRequest);
            ReadableStreamDefaultControllerCallPullIfNeeded(this);
          }
        }
      }
      Object.defineProperties(ReadableStreamDefaultController.prototype, {
        close: { enumerable: true },
        enqueue: { enumerable: true },
        error: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
          value: "ReadableStreamDefaultController",
          configurable: true
        });
      }
      function IsReadableStreamDefaultController(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableStream")) {
          return false;
        }
        return x2 instanceof ReadableStreamDefaultController;
      }
      function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
        const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
        if (!shouldPull) {
          return;
        }
        if (controller._pulling) {
          controller._pullAgain = true;
          return;
        }
        controller._pulling = true;
        const pullPromise = controller._pullAlgorithm();
        uponPromise(pullPromise, () => {
          controller._pulling = false;
          if (controller._pullAgain) {
            controller._pullAgain = false;
            ReadableStreamDefaultControllerCallPullIfNeeded(controller);
          }
        }, (e2) => {
          ReadableStreamDefaultControllerError(controller, e2);
        });
      }
      function ReadableStreamDefaultControllerShouldCallPull(controller) {
        const stream = controller._controlledReadableStream;
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return false;
        }
        if (!controller._started) {
          return false;
        }
        if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
          return true;
        }
        const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
        if (desiredSize > 0) {
          return true;
        }
        return false;
      }
      function ReadableStreamDefaultControllerClearAlgorithms(controller) {
        controller._pullAlgorithm = void 0;
        controller._cancelAlgorithm = void 0;
        controller._strategySizeAlgorithm = void 0;
      }
      function ReadableStreamDefaultControllerClose(controller) {
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return;
        }
        const stream = controller._controlledReadableStream;
        controller._closeRequested = true;
        if (controller._queue.length === 0) {
          ReadableStreamDefaultControllerClearAlgorithms(controller);
          ReadableStreamClose(stream);
        }
      }
      function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return;
        }
        const stream = controller._controlledReadableStream;
        if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
          ReadableStreamFulfillReadRequest(stream, chunk, false);
        } else {
          let chunkSize;
          try {
            chunkSize = controller._strategySizeAlgorithm(chunk);
          } catch (chunkSizeE) {
            ReadableStreamDefaultControllerError(controller, chunkSizeE);
            throw chunkSizeE;
          }
          try {
            EnqueueValueWithSize(controller, chunk, chunkSize);
          } catch (enqueueE) {
            ReadableStreamDefaultControllerError(controller, enqueueE);
            throw enqueueE;
          }
        }
        ReadableStreamDefaultControllerCallPullIfNeeded(controller);
      }
      function ReadableStreamDefaultControllerError(controller, e2) {
        const stream = controller._controlledReadableStream;
        if (stream._state !== "readable") {
          return;
        }
        ResetQueue(controller);
        ReadableStreamDefaultControllerClearAlgorithms(controller);
        ReadableStreamError(stream, e2);
      }
      function ReadableStreamDefaultControllerGetDesiredSize(controller) {
        const state = controller._controlledReadableStream._state;
        if (state === "errored") {
          return null;
        }
        if (state === "closed") {
          return 0;
        }
        return controller._strategyHWM - controller._queueTotalSize;
      }
      function ReadableStreamDefaultControllerHasBackpressure(controller) {
        if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
          return false;
        }
        return true;
      }
      function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
        const state = controller._controlledReadableStream._state;
        if (!controller._closeRequested && state === "readable") {
          return true;
        }
        return false;
      }
      function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledReadableStream = stream;
        controller._queue = void 0;
        controller._queueTotalSize = void 0;
        ResetQueue(controller);
        controller._started = false;
        controller._closeRequested = false;
        controller._pullAgain = false;
        controller._pulling = false;
        controller._strategySizeAlgorithm = sizeAlgorithm;
        controller._strategyHWM = highWaterMark;
        controller._pullAlgorithm = pullAlgorithm;
        controller._cancelAlgorithm = cancelAlgorithm;
        stream._readableStreamController = controller;
        const startResult = startAlgorithm();
        uponPromise(promiseResolvedWith(startResult), () => {
          controller._started = true;
          ReadableStreamDefaultControllerCallPullIfNeeded(controller);
        }, (r2) => {
          ReadableStreamDefaultControllerError(controller, r2);
        });
      }
      function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
        const controller = Object.create(ReadableStreamDefaultController.prototype);
        let startAlgorithm = () => void 0;
        let pullAlgorithm = () => promiseResolvedWith(void 0);
        let cancelAlgorithm = () => promiseResolvedWith(void 0);
        if (underlyingSource.start !== void 0) {
          startAlgorithm = () => underlyingSource.start(controller);
        }
        if (underlyingSource.pull !== void 0) {
          pullAlgorithm = () => underlyingSource.pull(controller);
        }
        if (underlyingSource.cancel !== void 0) {
          cancelAlgorithm = (reason) => underlyingSource.cancel(reason);
        }
        SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
      }
      function defaultControllerBrandCheckException$1(name) {
        return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
      }
      function ReadableStreamTee(stream, cloneForBranch2) {
        if (IsReadableByteStreamController(stream._readableStreamController)) {
          return ReadableByteStreamTee(stream);
        }
        return ReadableStreamDefaultTee(stream);
      }
      function ReadableStreamDefaultTee(stream, cloneForBranch2) {
        const reader = AcquireReadableStreamDefaultReader(stream);
        let reading = false;
        let readAgain = false;
        let canceled1 = false;
        let canceled2 = false;
        let reason1;
        let reason2;
        let branch1;
        let branch2;
        let resolveCancelPromise;
        const cancelPromise = newPromise((resolve2) => {
          resolveCancelPromise = resolve2;
        });
        function pullAlgorithm() {
          if (reading) {
            readAgain = true;
            return promiseResolvedWith(void 0);
          }
          reading = true;
          const readRequest = {
            _chunkSteps: (chunk) => {
              queueMicrotask(() => {
                readAgain = false;
                const chunk1 = chunk;
                const chunk2 = chunk;
                if (!canceled1) {
                  ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
                }
                if (!canceled2) {
                  ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
                }
                reading = false;
                if (readAgain) {
                  pullAlgorithm();
                }
              });
            },
            _closeSteps: () => {
              reading = false;
              if (!canceled1) {
                ReadableStreamDefaultControllerClose(branch1._readableStreamController);
              }
              if (!canceled2) {
                ReadableStreamDefaultControllerClose(branch2._readableStreamController);
              }
              if (!canceled1 || !canceled2) {
                resolveCancelPromise(void 0);
              }
            },
            _errorSteps: () => {
              reading = false;
            }
          };
          ReadableStreamDefaultReaderRead(reader, readRequest);
          return promiseResolvedWith(void 0);
        }
        function cancel1Algorithm(reason) {
          canceled1 = true;
          reason1 = reason;
          if (canceled2) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        function cancel2Algorithm(reason) {
          canceled2 = true;
          reason2 = reason;
          if (canceled1) {
            const compositeReason = CreateArrayFromList([reason1, reason2]);
            const cancelResult = ReadableStreamCancel(stream, compositeReason);
            resolveCancelPromise(cancelResult);
          }
          return cancelPromise;
        }
        function startAlgorithm() {
        }
        branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
        branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
        uponRejection(reader._closedPromise, (r2) => {
          ReadableStreamDefaultControllerError(branch1._readableStreamController, r2);
          ReadableStreamDefaultControllerError(branch2._readableStreamController, r2);
          if (!canceled1 || !canceled2) {
            resolveCancelPromise(void 0);
          }
        });
        return [branch1, branch2];
      }
      function ReadableByteStreamTee(stream) {
        let reader = AcquireReadableStreamDefaultReader(stream);
        let reading = false;
        let readAgainForBranch1 = false;
        let readAgainForBranch2 = false;
        let canceled1 = false;
        let canceled2 = false;
        let reason1;
        let reason2;
        let branch1;
        let branch2;
        let resolveCancelPromise;
        const cancelPromise = newPromise((resolve2) => {
          resolveCancelPromise = resolve2;
        });
        function forwardReaderError(thisReader) {
          uponRejection(thisReader._closedPromise, (r2) => {
            if (thisReader !== reader) {
              return;
            }
            ReadableByteStreamControllerError(branch1._readableStreamController, r2);
            ReadableByteStreamControllerError(branch2._readableStreamController, r2);
            if (!canceled1 || !canceled2) {
              resolveCancelPromise(void 0);
            }
          });
        }
        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(view4, 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, view4, 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 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 pull2 = 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: pull2 === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull2, 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 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 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 (e2) {
            return promiseRejectedWith(e2);
          }
          if (IsReadableStreamLocked(this)) {
            return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));
          }
          if (IsWritableStreamLocked(destination)) {
            return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));
          }
          return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
        }
        /**
         * Tees this readable stream, returning a two-element array containing the two resulting branches as
         * new {@link ReadableStream} instances.
         *
         * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
         * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
         * propagated to the stream's underlying source.
         *
         * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
         * this could allow interference between the two branches.
         */
        tee() {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("tee");
          }
          const branches = ReadableStreamTee(this);
          return CreateArrayFromList(branches);
        }
        values(rawOptions = void 0) {
          if (!IsReadableStream(this)) {
            throw streamBrandCheckException$1("values");
          }
          const options = convertIteratorOptions(rawOptions, "First parameter");
          return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
        }
      }
      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 }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.toStringTag, {
          value: "ReadableStream",
          configurable: true
        });
      }
      if (typeof SymbolPolyfill.asyncIterator === "symbol") {
        Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.asyncIterator, {
          value: ReadableStream2.prototype.values,
          writable: true,
          configurable: true
        });
      }
      function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream = Object.create(ReadableStream2.prototype);
        InitializeReadableStream(stream);
        const controller = Object.create(ReadableStreamDefaultController.prototype);
        SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
        return stream;
      }
      function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
        const stream = Object.create(ReadableStream2.prototype);
        InitializeReadableStream(stream);
        const controller = Object.create(ReadableByteStreamController.prototype);
        SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0);
        return stream;
      }
      function InitializeReadableStream(stream) {
        stream._state = "readable";
        stream._reader = void 0;
        stream._storedError = void 0;
        stream._disturbed = false;
      }
      function IsReadableStream(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_readableStreamController")) {
          return false;
        }
        return x2 instanceof ReadableStream2;
      }
      function IsReadableStreamLocked(stream) {
        if (stream._reader === void 0) {
          return false;
        }
        return true;
      }
      function ReadableStreamCancel(stream, reason) {
        stream._disturbed = true;
        if (stream._state === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (stream._state === "errored") {
          return promiseRejectedWith(stream._storedError);
        }
        ReadableStreamClose(stream);
        const reader = stream._reader;
        if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) {
          reader._readIntoRequests.forEach((readIntoRequest) => {
            readIntoRequest._closeSteps(void 0);
          });
          reader._readIntoRequests = new SimpleQueue();
        }
        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)) {
          reader._readRequests.forEach((readRequest) => {
            readRequest._closeSteps();
          });
          reader._readRequests = new SimpleQueue();
        }
      }
      function ReadableStreamError(stream, e2) {
        stream._state = "errored";
        stream._storedError = e2;
        const reader = stream._reader;
        if (reader === void 0) {
          return;
        }
        defaultReaderClosedPromiseReject(reader, e2);
        if (IsReadableStreamDefaultReader(reader)) {
          reader._readRequests.forEach((readRequest) => {
            readRequest._errorSteps(e2);
          });
          reader._readRequests = new SimpleQueue();
        } else {
          reader._readIntoRequests.forEach((readIntoRequest) => {
            readIntoRequest._errorSteps(e2);
          });
          reader._readIntoRequests = new SimpleQueue();
        }
      }
      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;
      };
      try {
        Object.defineProperty(byteLengthSizeFunction, "name", {
          value: "size",
          configurable: true
        });
      } catch (_a) {
      }
      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 SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
          value: "ByteLengthQueuingStrategy",
          configurable: true
        });
      }
      function byteLengthBrandCheckException(name) {
        return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
      }
      function IsByteLengthQueuingStrategy(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_byteLengthQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x2 instanceof ByteLengthQueuingStrategy;
      }
      const countSizeFunction = () => {
        return 1;
      };
      try {
        Object.defineProperty(countSizeFunction, "name", {
          value: "size",
          configurable: true
        });
      } catch (_a) {
      }
      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 SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
          value: "CountQueuingStrategy",
          configurable: true
        });
      }
      function countBrandCheckException(name) {
        return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
      }
      function IsCountQueuingStrategy(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_countQueuingStrategyHighWaterMark")) {
          return false;
        }
        return x2 instanceof CountQueuingStrategy;
      }
      function convertTransformer(original, context) {
        assertDictionary(original, context);
        const flush = original === null || original === void 0 ? void 0 : original.flush;
        const readableType = original === null || original === void 0 ? void 0 : original.readableType;
        const start = original === null || original === void 0 ? void 0 : original.start;
        const transform = original === null || original === void 0 ? void 0 : original.transform;
        const writableType = original === null || original === void 0 ? void 0 : original.writableType;
        return {
          flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
          readableType,
          start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
          transform: 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]);
      }
      class TransformStream {
        constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
          if (rawTransformer === void 0) {
            rawTransformer = null;
          }
          const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter");
          const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter");
          const transformer = convertTransformer(rawTransformer, "First parameter");
          if (transformer.readableType !== void 0) {
            throw new RangeError("Invalid readableType specified");
          }
          if (transformer.writableType !== void 0) {
            throw new RangeError("Invalid writableType specified");
          }
          const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
          const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
          const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
          const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
          let startPromise_resolve;
          const startPromise = newPromise((resolve2) => {
            startPromise_resolve = resolve2;
          });
          InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
          SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
          if (transformer.start !== void 0) {
            startPromise_resolve(transformer.start(this._transformStreamController));
          } else {
            startPromise_resolve(void 0);
          }
        }
        /**
         * The readable side of the transform stream.
         */
        get readable() {
          if (!IsTransformStream(this)) {
            throw streamBrandCheckException("readable");
          }
          return this._readable;
        }
        /**
         * The writable side of the transform stream.
         */
        get writable() {
          if (!IsTransformStream(this)) {
            throw streamBrandCheckException("writable");
          }
          return this._writable;
        }
      }
      Object.defineProperties(TransformStream.prototype, {
        readable: { enumerable: true },
        writable: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(TransformStream.prototype, SymbolPolyfill.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) {
          TransformStreamErrorWritableAndUnblockWrite(stream, reason);
          return promiseResolvedWith(void 0);
        }
        stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
        stream._backpressure = void 0;
        stream._backpressureChangePromise = void 0;
        stream._backpressureChangePromise_resolve = void 0;
        TransformStreamSetBackpressure(stream, true);
        stream._transformStreamController = void 0;
      }
      function IsTransformStream(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) {
          return false;
        }
        return x2 instanceof TransformStream;
      }
      function TransformStreamError(stream, e2) {
        ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e2);
        TransformStreamErrorWritableAndUnblockWrite(stream, e2);
      }
      function TransformStreamErrorWritableAndUnblockWrite(stream, e2) {
        TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
        WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e2);
        if (stream._backpressure) {
          TransformStreamSetBackpressure(stream, false);
        }
      }
      function TransformStreamSetBackpressure(stream, backpressure) {
        if (stream._backpressureChangePromise !== void 0) {
          stream._backpressureChangePromise_resolve();
        }
        stream._backpressureChangePromise = newPromise((resolve2) => {
          stream._backpressureChangePromise_resolve = resolve2;
        });
        stream._backpressure = backpressure;
      }
      class TransformStreamDefaultController {
        constructor() {
          throw new TypeError("Illegal constructor");
        }
        /**
         * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
         */
        get desiredSize() {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("desiredSize");
          }
          const readableController = this._controlledTransformStream._readable._readableStreamController;
          return ReadableStreamDefaultControllerGetDesiredSize(readableController);
        }
        enqueue(chunk = void 0) {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("enqueue");
          }
          TransformStreamDefaultControllerEnqueue(this, chunk);
        }
        /**
         * Errors both the readable side and the writable side of the controlled transform stream, making all future
         * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
         */
        error(reason = void 0) {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("error");
          }
          TransformStreamDefaultControllerError(this, reason);
        }
        /**
         * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
         * transformer only needs to consume a portion of the chunks written to the writable side.
         */
        terminate() {
          if (!IsTransformStreamDefaultController(this)) {
            throw defaultControllerBrandCheckException("terminate");
          }
          TransformStreamDefaultControllerTerminate(this);
        }
      }
      Object.defineProperties(TransformStreamDefaultController.prototype, {
        enqueue: { enumerable: true },
        error: { enumerable: true },
        terminate: { enumerable: true },
        desiredSize: { enumerable: true }
      });
      if (typeof SymbolPolyfill.toStringTag === "symbol") {
        Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
          value: "TransformStreamDefaultController",
          configurable: true
        });
      }
      function IsTransformStreamDefaultController(x2) {
        if (!typeIsObject(x2)) {
          return false;
        }
        if (!Object.prototype.hasOwnProperty.call(x2, "_controlledTransformStream")) {
          return false;
        }
        return x2 instanceof TransformStreamDefaultController;
      }
      function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
        controller._controlledTransformStream = stream;
        stream._transformStreamController = controller;
        controller._transformAlgorithm = transformAlgorithm;
        controller._flushAlgorithm = flushAlgorithm;
      }
      function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
        const controller = Object.create(TransformStreamDefaultController.prototype);
        let transformAlgorithm = (chunk) => {
          try {
            TransformStreamDefaultControllerEnqueue(controller, chunk);
            return promiseResolvedWith(void 0);
          } catch (transformResultE) {
            return promiseRejectedWith(transformResultE);
          }
        };
        let flushAlgorithm = () => promiseResolvedWith(void 0);
        if (transformer.transform !== void 0) {
          transformAlgorithm = (chunk) => transformer.transform(chunk, controller);
        }
        if (transformer.flush !== void 0) {
          flushAlgorithm = () => transformer.flush(controller);
        }
        SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
      }
      function TransformStreamDefaultControllerClearAlgorithms(controller) {
        controller._transformAlgorithm = void 0;
        controller._flushAlgorithm = void 0;
      }
      function TransformStreamDefaultControllerEnqueue(controller, chunk) {
        const stream = controller._controlledTransformStream;
        const readableController = stream._readable._readableStreamController;
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
          throw new TypeError("Readable side is not in a state that permits enqueue");
        }
        try {
          ReadableStreamDefaultControllerEnqueue(readableController, chunk);
        } catch (e2) {
          TransformStreamErrorWritableAndUnblockWrite(stream, e2);
          throw stream._readable._storedError;
        }
        const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
        if (backpressure !== stream._backpressure) {
          TransformStreamSetBackpressure(stream, true);
        }
      }
      function TransformStreamDefaultControllerError(controller, e2) {
        TransformStreamError(controller._controlledTransformStream, e2);
      }
      function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
        const transformPromise = controller._transformAlgorithm(chunk);
        return transformPromiseWith(transformPromise, void 0, (r2) => {
          TransformStreamError(controller._controlledTransformStream, r2);
          throw r2;
        });
      }
      function TransformStreamDefaultControllerTerminate(controller) {
        const stream = controller._controlledTransformStream;
        const readableController = stream._readable._readableStreamController;
        ReadableStreamDefaultControllerClose(readableController);
        const 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 state = writable._state;
            if (state === "erroring") {
              throw writable._storedError;
            }
            return TransformStreamDefaultControllerPerformTransform(controller, chunk);
          });
        }
        return TransformStreamDefaultControllerPerformTransform(controller, chunk);
      }
      function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
        TransformStreamError(stream, reason);
        return promiseResolvedWith(void 0);
      }
      function TransformStreamDefaultSinkCloseAlgorithm(stream) {
        const readable = stream._readable;
        const controller = stream._transformStreamController;
        const flushPromise = controller._flushAlgorithm();
        TransformStreamDefaultControllerClearAlgorithms(controller);
        return transformPromiseWith(flushPromise, () => {
          if (readable._state === "errored") {
            throw readable._storedError;
          }
          ReadableStreamDefaultControllerClose(readable._readableStreamController);
        }, (r2) => {
          TransformStreamError(stream, r2);
          throw readable._storedError;
        });
      }
      function TransformStreamDefaultSourcePullAlgorithm(stream) {
        TransformStreamSetBackpressure(stream, false);
        return stream._backpressureChangePromise;
      }
      function defaultControllerBrandCheckException(name) {
        return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
      }
      function streamBrandCheckException(name) {
        return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
      }
      exports3.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
      exports3.CountQueuingStrategy = CountQueuingStrategy;
      exports3.ReadableByteStreamController = ReadableByteStreamController;
      exports3.ReadableStream = ReadableStream2;
      exports3.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
      exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
      exports3.ReadableStreamDefaultController = ReadableStreamDefaultController;
      exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
      exports3.TransformStream = TransformStream;
      exports3.TransformStreamDefaultController = TransformStreamDefaultController;
      exports3.WritableStream = WritableStream;
      exports3.WritableStreamDefaultController = WritableStreamDefaultController;
      exports3.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
      Object.defineProperty(exports3, "__esModule", { value: true });
    });
  }
});

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

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

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

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

// ../node_modules/.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((c) => typeof c === "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_body = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js"() {
    import_node_stream = __toESM(require("node:stream"), 1);
    import_node_util = require("node:util");
    import_node_buffer = require("node:buffer");
    init_fetch_blob();
    init_esm_min();
    init_fetch_error();
    init_base();
    init_is();
    pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline);
    INTERNALS = 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 p2;
      let { body } = instance[INTERNALS];
      if (instance.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") {
        p1 = new import_node_stream.PassThrough({ highWaterMark });
        p2 = new import_node_stream.PassThrough({ highWaterMark });
        body.pipe(p1);
        body.pipe(p2);
        instance[INTERNALS].stream = p1;
        body = p2;
      }
      return body;
    };
    getNonSpecFormDataBoundary = (0, import_node_util.deprecate)(
      (body) => body.getBoundary(),
      "form-data doesn't follow the spec and requires special treatment. Use alternative package",
      "https://github.com/node-fetch/node-fetch/issues/1167"
    );
    extractContentType = (body, request) => {
      if (body === null) {
        return null;
      }
      if (typeof body === "string") {
        return "text/plain;charset=UTF-8";
      }
      if (isURLSearchParameters(body)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      }
      if (isBlob(body)) {
        return body.type || null;
      }
      if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
        return null;
      }
      if (body instanceof FormData) {
        return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
      }
      if (body && typeof body.getBoundary === "function") {
        return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
      }
      if (body instanceof import_node_stream.default) {
        return null;
      }
      return "text/plain;charset=UTF-8";
    };
    getTotalBytes = (request) => {
      const { body } = request[INTERNALS];
      if (body === null) {
        return 0;
      }
      if (isBlob(body)) {
        return body.size;
      }
      if (import_node_buffer.Buffer.isBuffer(body)) {
        return body.length;
      }
      if (body && typeof body.getLengthSync === "function") {
        return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
      }
      return null;
    };
    writeToStream = async (dest, { body }) => {
      if (body === null) {
        dest.end();
      } else {
        await pipeline(body, dest);
      }
    };
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
function fromRawHeaders(headers = []) {
  return new Headers2(
    headers.reduce((result, value, index5, array2) => {
      if (index5 % 2 === 0) {
        result.push(array2.slice(index5, index5 + 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"() {
    import_node_util2 = require("node:util");
    import_node_http = __toESM(require("node:http"), 1);
    validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => {
      if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
        const 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, p, receiver) {
            switch (p) {
              case "append":
              case "set":
                return (name, value) => {
                  validateHeaderName(name);
                  validateHeaderValue(name, String(value));
                  return URLSearchParams.prototype[p].call(
                    target,
                    String(name).toLowerCase(),
                    String(value)
                  );
                };
              case "delete":
              case "has":
              case "getAll":
                return (name) => {
                  validateHeaderName(name);
                  return URLSearchParams.prototype[p].call(
                    target,
                    String(name).toLowerCase()
                  );
                };
              case "keys":
                return () => {
                  target.sort();
                  return new Set(URLSearchParams.prototype.keys.call(target)).keys();
                };
              default:
                return Reflect.get(target, p, receiver);
            }
          }
        });
      }
      get [Symbol.toStringTag]() {
        return this.constructor.name;
      }
      toString() {
        return Object.prototype.toString.call(this);
      }
      get(name) {
        const values = this.getAll(name);
        if (values.length === 0) {
          return null;
        }
        let value = values.join(", ");
        if (/^content-encoding$/i.test(name)) {
          value = value.toLowerCase();
        }
        return value;
      }
      forEach(callback, thisArg = void 0) {
        for (const name of this.keys()) {
          Reflect.apply(callback, thisArg, [this.get(name), name, this]);
        }
      }
      *values() {
        for (const name of this.keys()) {
          yield this.get(name);
        }
      }
      /**
       * @type {() => IterableIterator<[string, string]>}
       */
      *entries() {
        for (const name of this.keys()) {
          yield [name, this.get(name)];
        }
      }
      [Symbol.iterator]() {
        return this.entries();
      }
      /**
       * Node-fetch non-spec method
       * returning all headers and their values as array
       * @returns {Record<string, string[]>}
       */
      raw() {
        return [...this.keys()].reduce((result, key) => {
          result[key] = this.getAll(key);
          return result;
        }, {});
      }
      /**
       * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
       */
      [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"() {
    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, Response2;
var init_response = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js"() {
    init_headers();
    init_body();
    init_is_redirect();
    INTERNALS2 = Symbol("Response internals");
    Response2 = class _Response2 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 _Response2(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 _Response2(null, {
          headers: {
            location: new URL(url).toString()
          },
          status
        });
      }
      static error() {
        const response = new _Response2(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 _Response2(body, {
          ...init2,
          headers
        });
      }
      get [Symbol.toStringTag]() {
        return "Response";
      }
    };
    Object.defineProperties(Response2.prototype, {
      type: { enumerable: true },
      url: { enumerable: true },
      status: { enumerable: true },
      ok: { enumerable: true },
      redirected: { enumerable: true },
      statusText: { enumerable: true },
      headers: { enumerable: true },
      clone: { enumerable: true }
    });
  }
});

// ../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"() {
    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(request, { referrerURLCallback, referrerOriginCallback } = {}) {
  if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
    return null;
  }
  const policy4 = request.referrerPolicy;
  if (request.referrer === "about:client") {
    return "no-referrer";
  }
  const referrerSource = request.referrer;
  let referrerURL = stripURLForUseAsAReferrer(referrerSource);
  let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
  if (referrerURL.toString().length > 4096) {
    referrerURL = referrerOrigin;
  }
  if (referrerURLCallback) {
    referrerURL = referrerURLCallback(referrerURL);
  }
  if (referrerOriginCallback) {
    referrerOrigin = referrerOriginCallback(referrerOrigin);
  }
  const currentURL = new URL(request.url);
  switch (policy4) {
    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: ${policy4}`);
  }
}
function parseReferrerPolicyFromHeader(headers) {
  const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
  let policy4 = "";
  for (const token of policyTokens) {
    if (token && ReferrerPolicy.has(token)) {
      policy4 = token;
    }
  }
  return policy4;
}
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"() {
    import_node_net = require("node:net");
    ReferrerPolicy = /* @__PURE__ */ new Set([
      "",
      "no-referrer",
      "no-referrer-when-downgrade",
      "same-origin",
      "origin",
      "strict-origin",
      "origin-when-cross-origin",
      "strict-origin-when-cross-origin",
      "unsafe-url"
    ]);
    DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
  }
});

// ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
var import_node_url, import_node_util3, INTERNALS3, isRequest, doBadDataWarn, Request2, getNodeRequestOptions;
var init_request = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js"() {
    import_node_url = require("node:url");
    import_node_util3 = require("node:util");
    init_headers();
    init_body();
    init_is();
    init_get_search();
    init_referrer();
    INTERNALS3 = 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)"
    );
    Request2 = 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(Request2.prototype, {
      method: { enumerable: true },
      url: { enumerable: true },
      headers: { enumerable: true },
      redirect: { enumerable: true },
      clone: { enumerable: true },
      signal: { enumerable: true },
      referrer: { enumerable: true },
      referrerPolicy: { enumerable: true }
    });
    getNodeRequestOptions = (request) => {
      const { parsedURL } = request[INTERNALS3];
      const headers = new Headers2(request[INTERNALS3].headers);
      if (!headers.has("Accept")) {
        headers.set("Accept", "*/*");
      }
      let contentLengthValue = null;
      if (request.body === null && /^(post|put)$/i.test(request.method)) {
        contentLengthValue = "0";
      }
      if (request.body !== null) {
        const totalBytes = getTotalBytes(request);
        if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
          contentLengthValue = String(totalBytes);
        }
      }
      if (contentLengthValue) {
        headers.set("Content-Length", contentLengthValue);
      }
      if (request.referrerPolicy === "") {
        request.referrerPolicy = DEFAULT_REFERRER_POLICY;
      }
      if (request.referrer && request.referrer !== "no-referrer") {
        request[INTERNALS3].referrer = determineRequestsReferrer(request);
      } else {
        request[INTERNALS3].referrer = "no-referrer";
      }
      if (request[INTERNALS3].referrer instanceof URL) {
        headers.set("Referer", request.referrer);
      }
      if (!headers.has("User-Agent")) {
        headers.set("User-Agent", "node-fetch");
      }
      if (request.compress && !headers.has("Accept-Encoding")) {
        headers.set("Accept-Encoding", "gzip, deflate, br");
      }
      let { agent } = request;
      if (typeof agent === "function") {
        agent = agent(parsedURL);
      }
      const search = getSearch(parsedURL);
      const options = {
        // Overwrite search to retain trailing ? (issue #776)
        path: parsedURL.pathname + search,
        // The following options are not expressed in the URL
        method: request.method,
        headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
        insecureHTTPParser: request.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"() {
    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((resolve2, reject) => {
    const request = new Request2(url, options_);
    const { parsedURL, options } = getNodeRequestOptions(request);
    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(request.url);
      const response2 = new Response2(data, { headers: { "Content-Type": data.typeFull } });
      resolve2(response2);
      return;
    }
    const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request;
    const { signal } = request;
    let response = null;
    const abort = () => {
      const error2 = new AbortError("The operation was aborted.");
      reject(error2);
      if (request.body && request.body instanceof import_node_stream2.default.Readable) {
        request.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 ${request.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", (s2) => {
        let endedWithEventsCount;
        s2.prependListener("end", () => {
          endedWithEventsCount = s2._eventsCount;
        });
        s2.prependListener("close", (hadError) => {
          if (response && endedWithEventsCount < s2._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, request.url);
        } catch {
          if (request.redirect !== "manual") {
            reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
            finalize();
            return;
          }
        }
        switch (request.redirect) {
          case "error":
            reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
            finalize();
            return;
          case "manual":
            break;
          case "follow": {
            if (locationURL === null) {
              break;
            }
            if (request.counter >= request.follow) {
              reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
              finalize();
              return;
            }
            const requestOptions = {
              headers: new Headers2(request.headers),
              follow: request.follow,
              counter: request.counter + 1,
              agent: request.agent,
              compress: request.compress,
              method: request.method,
              body: clone(request),
              signal: request.signal,
              size: request.size,
              referrer: request.referrer,
              referrerPolicy: request.referrerPolicy
            };
            if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
              for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                requestOptions.headers.delete(name);
              }
            }
            if (response_.statusCode !== 303 && request.body && options_.body instanceof import_node_stream2.default.Readable) {
              reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
              finalize();
              return;
            }
            if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request.method === "POST") {
              requestOptions.method = "GET";
              requestOptions.body = void 0;
              requestOptions.headers.delete("content-length");
            }
            const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
            if (responseReferrerPolicy) {
              requestOptions.referrerPolicy = responseReferrerPolicy;
            }
            resolve2(fetch2(new Request2(locationURL, requestOptions)));
            finalize();
            return;
          }
          default:
            return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));
        }
      }
      if (signal) {
        response_.once("end", () => {
          signal.removeEventListener("abort", abortAndFinalize);
        });
      }
      let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => {
        if (error2) {
          reject(error2);
        }
      });
      if (process.version < "v12.10") {
        response_.on("aborted", abortAndFinalize);
      }
      const responseOptions = {
        url: request.url,
        status: response_.statusCode,
        statusText: response_.statusMessage,
        headers,
        size: request.size,
        counter: request.counter,
        highWaterMark: request.highWaterMark
      };
      const codings = headers.get("Content-Encoding");
      if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
        response = new Response2(body, responseOptions);
        resolve2(response);
        return;
      }
      const zlibOptions = {
        flush: import_node_zlib.default.Z_SYNC_FLUSH,
        finishFlush: import_node_zlib.default.Z_SYNC_FLUSH
      };
      if (codings === "gzip" || codings === "x-gzip") {
        body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response2(body, responseOptions);
        resolve2(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 Response2(body, responseOptions);
          resolve2(response);
        });
        raw2.once("end", () => {
          if (!response) {
            response = new Response2(body, responseOptions);
            resolve2(response);
          }
        });
        return;
      }
      if (codings === "br") {
        body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error2) => {
          if (error2) {
            reject(error2);
          }
        });
        response = new Response2(body, responseOptions);
        resolve2(response);
        return;
      }
      response = new Response2(body, responseOptions);
      resolve2(response);
    });
    writeToStream(request_, request).catch(reject);
  });
}
function fixResponseChunkedTransferBadEnding(request, errorCallback) {
  const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n");
  let isChunkedTransfer = false;
  let properLastChunkReceived = false;
  let previousChunk;
  request.on("response", (response) => {
    const { headers } = response;
    isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
  });
  request.on("socket", (socket) => {
    const onSocketClose = () => {
      if (isChunkedTransfer && !properLastChunkReceived) {
        const 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);
    request.on("close", () => {
      socket.removeListener("close", onSocketClose);
      socket.removeListener("data", onData);
    });
  });
}
var import_node_http2, import_node_https, import_node_zlib, import_node_stream2, import_node_buffer2, supportedSchemas;
var init_src = __esm({
  "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js"() {
    import_node_http2 = __toESM(require("node:http"), 1);
    import_node_https = __toESM(require("node:https"), 1);
    import_node_zlib = __toESM(require("node:zlib"), 1);
    import_node_stream2 = __toESM(require("node:stream"), 1);
    import_node_buffer2 = require("node:buffer");
    init_dist();
    init_body();
    init_response();
    init_headers();
    init_request();
    init_fetch_error();
    init_abort_error();
    init_is_redirect();
    init_esm_min();
    init_is();
    init_referrer();
    init_from();
    supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/stream.js
var require_stream = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/stream.js"(exports2, module2) {
    "use strict";
    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.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/constants.js
var require_constants2 = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/constants.js"(exports2, module2) {
    "use strict";
    module2.exports = {
      BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
      EMPTY_BUFFER: Buffer.alloc(0),
      GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
      kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
      kListener: Symbol("kListener"),
      kStatusCode: Symbol("status-code"),
      kWebSocket: Symbol("websocket"),
      NOOP: () => {
      }
    };
  }
});

// ../node_modules/.pnpm/node-gyp-build@4.8.1/node_modules/node-gyp-build/node-gyp-build.js
var require_node_gyp_build = __commonJS({
  "../node_modules/.pnpm/node-gyp-build@4.8.1/node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
    var fs7 = require("fs");
    var path4 = 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 platform = process.env.npm_config_platform || os3.platform();
    var libc = process.env.LIBC || (isAlpine(platform) ? "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 = path4.resolve(dir || ".");
      try {
        var name = runtimeRequire(path4.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
        if (process.env[name + "_PREBUILD"])
          dir = process.env[name + "_PREBUILD"];
      } catch (err2) {
      }
      if (!prebuildsOnly) {
        var release = getFirst(path4.join(dir, "build/Release"), matchBuild);
        if (release)
          return release;
        var debug = getFirst(path4.join(dir, "build/Debug"), matchBuild);
        if (debug)
          return debug;
      }
      var prebuild = resolve2(dir);
      if (prebuild)
        return prebuild;
      var nearby = resolve2(path4.dirname(process.execPath));
      if (nearby)
        return nearby;
      var target = [
        "platform=" + platform,
        "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 resolve2(dir2) {
        var tuples = readdirSync2(path4.join(dir2, "prebuilds")).map(parseTuple);
        var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
        if (!tuple)
          return;
        var prebuilds = path4.join(dir2, "prebuilds", tuple.name);
        var parsed = readdirSync2(prebuilds).map(parseTags);
        var candidates = parsed.filter(matchTags(runtime, abi));
        var winner = candidates.sort(compareTags(runtime))[0];
        if (winner)
          return path4.join(prebuilds, winner.file);
      }
    };
    function readdirSync2(dir) {
      try {
        return fs7.readdirSync(dir);
      } catch (err2) {
        return [];
      }
    }
    function getFirst(dir, filter2) {
      var files = readdirSync2(dir).filter(filter2);
      return files[0] && path4.join(dir, files[0]);
    }
    function matchBuild(name) {
      return /\.node$/.test(name);
    }
    function parseTuple(name) {
      var arr = name.split("-");
      if (arr.length !== 2)
        return;
      var platform2 = arr[0];
      var architectures = arr[1].split("+");
      if (!platform2)
        return;
      if (!architectures.length)
        return;
      if (!architectures.every(Boolean))
        return;
      return { name, platform: platform2, architectures };
    }
    function matchTuple(platform2, arch2) {
      return function(tuple) {
        if (tuple == null)
          return false;
        if (tuple.platform !== platform2)
          return false;
        return tuple.architectures.includes(arch2);
      };
    }
    function compareTuples(a, b) {
      return a.architectures.length - b.architectures.length;
    }
    function parseTags(file) {
      var arr = file.split(".");
      var extension = arr.pop();
      var tags = { file, specificity: 0 };
      if (extension !== "node")
        return;
      for (var i2 = 0; i2 < arr.length; i2++) {
        var tag = arr[i2];
        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(a, b) {
        if (a.runtime !== b.runtime) {
          return a.runtime === runtime2 ? -1 : 1;
        } else if (a.abi !== b.abi) {
          return a.abi ? -1 : 1;
        } else if (a.specificity !== b.specificity) {
          return a.specificity > b.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(platform2) {
      return platform2 === "linux" && fs7.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.1/node_modules/node-gyp-build/index.js
var require_node_gyp_build2 = __commonJS({
  "../node_modules/.pnpm/node-gyp-build@4.8.1/node_modules/node-gyp-build/index.js"(exports2, module2) {
    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 i2 = 0; i2 < length; i2++) {
        output[offset + i2] = source[i2] ^ mask2[i2 & 3];
      }
    };
    var unmask = (buffer, mask2) => {
      const length = buffer.length;
      for (var i2 = 0; i2 < length; i2++) {
        buffer[i2] ^= mask2[i2 & 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 (e2) {
      module2.exports = require_fallback();
    }
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/buffer-util.js
var require_buffer_util = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/buffer-util.js"(exports2, module2) {
    "use strict";
    var { EMPTY_BUFFER } = require_constants2();
    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 i2 = 0; i2 < list.length; i2++) {
        const buf = list[i2];
        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 i2 = 0; i2 < length; i2++) {
        output[offset + i2] = source[i2] ^ mask[i2 & 3];
      }
    }
    function _unmask(buffer, mask) {
      for (let i2 = 0; i2 < buffer.length; i2++) {
        buffer[i2] ^= mask[i2 & 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 (e2) {
      }
    }
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/limiter.js
var require_limiter = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/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.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/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_constants2();
    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;
      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 i2 = 0;
      while (i2 < len) {
        if ((buf[i2] & 128) === 0) {
          i2++;
        } else if ((buf[i2] & 224) === 192) {
          if (i2 + 1 === len || (buf[i2 + 1] & 192) !== 128 || (buf[i2] & 254) === 192) {
            return false;
          }
          i2 += 2;
        } else if ((buf[i2] & 240) === 224) {
          if (i2 + 2 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || buf[i2] === 224 && (buf[i2 + 1] & 224) === 128 || // overlong
          buf[i2] === 237 && (buf[i2 + 1] & 224) === 160) {
            return false;
          }
          i2 += 3;
        } else if ((buf[i2] & 248) === 240) {
          if (i2 + 3 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || (buf[i2 + 3] & 192) !== 128 || buf[i2] === 240 && (buf[i2 + 1] & 240) === 128 || // overlong
          buf[i2] === 244 && buf[i2 + 1] > 143 || buf[i2] > 244) {
            return false;
          }
          i2 += 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 (e2) {
      module2.exports = require_fallback2();
    }
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/validation.js
var require_validation = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/validation.js"(exports2, module2) {
    "use strict";
    var { isUtf8 } = require("buffer");
    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 i2 = 0;
      while (i2 < len) {
        if ((buf[i2] & 128) === 0) {
          i2++;
        } else if ((buf[i2] & 224) === 192) {
          if (i2 + 1 === len || (buf[i2 + 1] & 192) !== 128 || (buf[i2] & 254) === 192) {
            return false;
          }
          i2 += 2;
        } else if ((buf[i2] & 240) === 224) {
          if (i2 + 2 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || buf[i2] === 224 && (buf[i2 + 1] & 224) === 128 || // Overlong
          buf[i2] === 237 && (buf[i2 + 1] & 224) === 160) {
            return false;
          }
          i2 += 3;
        } else if ((buf[i2] & 248) === 240) {
          if (i2 + 3 >= len || (buf[i2 + 1] & 192) !== 128 || (buf[i2 + 2] & 192) !== 128 || (buf[i2 + 3] & 192) !== 128 || buf[i2] === 240 && (buf[i2 + 1] & 240) === 128 || // Overlong
          buf[i2] === 244 && buf[i2 + 1] > 143 || buf[i2] > 244) {
            return false;
          }
          i2 += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    module2.exports = {
      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 (e2) {
      }
    }
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/receiver.js
var require_receiver = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/receiver.js"(exports2, module2) {
    "use strict";
    var { Writable } = require("stream");
    var PerMessageDeflate = require_permessage_deflate();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      kStatusCode,
      kWebSocket
    } = require_constants2();
    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 Writable {
      /**
       * 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(n) {
        this._bufferedBytes -= n;
        if (n === this._buffers[0].length)
          return this._buffers.shift();
        if (n < this._buffers[0].length) {
          const buf = this._buffers[0];
          this._buffers[0] = new FastBuffer(
            buf.buffer,
            buf.byteOffset + n,
            buf.length - n
          );
          return new FastBuffer(buf.buffer, buf.byteOffset, n);
        }
        const dst = Buffer.allocUnsafe(n);
        do {
          const buf = this._buffers[0];
          const offset = dst.length - n;
          if (n >= buf.length) {
            dst.set(this._buffers.shift(), offset);
          } else {
            dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
            this._buffers[0] = new FastBuffer(
              buf.buffer,
              buf.byteOffset + n,
              buf.length - n
            );
          }
          n -= buf.length;
        } while (n > 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 {
            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.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/sender.js
var require_sender = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/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 } = require_constants2();
    var { isValidStatusCode } = require_validation();
    var { mask: applyMask, toBuffer } = require_buffer_util();
    var kByteLength = Symbol("kByteLength");
    var maskBuffer = Buffer.alloc(4);
    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._deflating = false;
        this._queue = [];
      }
      /**
       * 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 merge = false;
        let offset = 2;
        let skipMasking = false;
        if (options.mask) {
          mask = options.maskBuffer || maskBuffer;
          if (options.generateMask) {
            options.generateMask(mask);
          } else {
            randomFillSync(mask, 0, 4);
          }
          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;
          merge = 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(merge ? 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 (merge) {
          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._deflating) {
          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 {
          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 (this._deflating) {
          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 {
          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 (this._deflating) {
          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 {
          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;
        if (perMessageDeflate) {
          const opts = {
            [kByteLength]: byteLength,
            fin: options.fin,
            generateMask: this._generateMask,
            mask: options.mask,
            maskBuffer: this._maskBuffer,
            opcode,
            readOnly,
            rsv1
          };
          if (this._deflating) {
            this.enqueue([this.dispatch, data, this._compress, opts, cb]);
          } else {
            this.dispatch(data, this._compress, opts, cb);
          }
        } else {
          this.sendFrame(
            _Sender.frame(data, {
              [kByteLength]: byteLength,
              fin: options.fin,
              generateMask: this._generateMask,
              mask: options.mask,
              maskBuffer: this._maskBuffer,
              opcode,
              readOnly,
              rsv1: false
            }),
            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._deflating = true;
        perMessageDeflate.compress(data, options.fin, (_2, buf) => {
          if (this._socket.destroyed) {
            const err2 = new Error(
              "The socket was closed while data was being compressed"
            );
            if (typeof cb === "function")
              cb(err2);
            for (let i2 = 0; i2 < this._queue.length; i2++) {
              const params = this._queue[i2];
              const callback = params[params.length - 1];
              if (typeof callback === "function")
                callback(err2);
            }
            return;
          }
          this._bufferedBytes -= options[kByteLength];
          this._deflating = false;
          options.readOnly = false;
          this.sendFrame(_Sender.frame(buf, options), cb);
          this.dequeue();
        });
      }
      /**
       * Executes queued send operations.
       *
       * @private
       */
      dequeue() {
        while (!this._deflating && 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[]} 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;
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/event-target.js
var require_event_target = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/event-target.js"(exports2, module2) {
    "use strict";
    var { kForOnEventAttribute, kListener } = require_constants2();
    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.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/extension.js
var require_extension = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/extension.js"(exports2, module2) {
    "use strict";
    var { tokenChars } = require_validation();
    function push2(dest, name, elem) {
      if (dest[name] === void 0)
        dest[name] = [elem];
      else
        dest[name].push(elem);
    }
    function parse5(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 i2 = 0;
      for (; i2 < header.length; i2++) {
        code = header.charCodeAt(i2);
        if (extensionName === void 0) {
          if (end === -1 && tokenChars[code] === 1) {
            if (start === -1)
              start = i2;
          } else if (i2 !== 0 && (code === 32 || code === 9)) {
            if (end === -1 && start !== -1)
              end = i2;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i2}`);
            }
            if (end === -1)
              end = i2;
            const name = header.slice(start, end);
            if (code === 44) {
              push2(offers, name, params);
              params = /* @__PURE__ */ Object.create(null);
            } else {
              extensionName = name;
            }
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i2}`);
          }
        } else if (paramName === void 0) {
          if (end === -1 && tokenChars[code] === 1) {
            if (start === -1)
              start = i2;
          } else if (code === 32 || code === 9) {
            if (end === -1 && start !== -1)
              end = i2;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i2}`);
            }
            if (end === -1)
              end = i2;
            push2(params, header.slice(start, end), true);
            if (code === 44) {
              push2(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, i2);
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i2}`);
          }
        } else {
          if (isEscaping) {
            if (tokenChars[code] !== 1) {
              throw new SyntaxError(`Unexpected character at index ${i2}`);
            }
            if (start === -1)
              start = i2;
            else if (!mustUnescape)
              mustUnescape = true;
            isEscaping = false;
          } else if (inQuotes) {
            if (tokenChars[code] === 1) {
              if (start === -1)
                start = i2;
            } else if (code === 34 && start !== -1) {
              inQuotes = false;
              end = i2;
            } else if (code === 92) {
              isEscaping = true;
            } else {
              throw new SyntaxError(`Unexpected character at index ${i2}`);
            }
          } else if (code === 34 && header.charCodeAt(i2 - 1) === 61) {
            inQuotes = true;
          } else if (end === -1 && tokenChars[code] === 1) {
            if (start === -1)
              start = i2;
          } else if (start !== -1 && (code === 32 || code === 9)) {
            if (end === -1)
              end = i2;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i2}`);
            }
            if (end === -1)
              end = i2;
            let value = header.slice(start, end);
            if (mustUnescape) {
              value = value.replace(/\\/g, "");
              mustUnescape = false;
            }
            push2(params, paramName, value);
            if (code === 44) {
              push2(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            paramName = void 0;
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i2}`);
          }
        }
      }
      if (start === -1 || inQuotes || code === 32 || code === 9) {
        throw new SyntaxError("Unexpected end of input");
      }
      if (end === -1)
        end = i2;
      const token = header.slice(start, end);
      if (extensionName === void 0) {
        push2(offers, token, params);
      } else {
        if (paramName === void 0) {
          push2(params, token, true);
        } else if (mustUnescape) {
          push2(params, paramName, token.replace(/\\/g, ""));
        } else {
          push2(params, paramName, token);
        }
        push2(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((k) => {
              let values = params[k];
              if (!Array.isArray(values))
                values = [values];
              return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
            })
          ).join("; ");
        }).join(", ");
      }).join(", ");
    }
    module2.exports = { format, parse: parse5 };
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket.js
var require_websocket = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/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: createHash2 } = require("crypto");
    var { Duplex, Readable: Readable2 } = require("stream");
    var { URL: URL3 } = require("url");
    var PerMessageDeflate = require_permessage_deflate();
    var Receiver2 = require_receiver();
    var Sender2 = require_sender();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      GUID,
      kForOnEventAttribute,
      kListener,
      kStatusCode,
      kWebSocket,
      NOOP
    } = require_constants2();
    var {
      EventTarget: { addEventListener: addEventListener2, removeEventListener }
    } = require_event_target();
    var { format, parse: parse5 } = 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._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;
        }
      }
      /**
       * This deviates from the WHATWG interface since ws doesn't support the
       * required default "blob" type (instead we define a custom "nodebuffer"
       * type).
       *
       * @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
        });
        this._sender = new Sender2(socket, this._extensions, options.generateMask);
        this._receiver = receiver;
        this._socket = socket;
        receiver[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);
        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();
          }
        });
        this._closeTimer = setTimeout(
          this._socket.destroy.bind(this._socket),
          closeTimeout
        );
      }
      /**
       * 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 URL3) {
        parsedUrl = address;
      } else {
        try {
          parsedUrl = new URL3(address);
        } catch (e2) {
          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 request = 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 = request(opts);
        if (websocket._redirects) {
          websocket.emit("redirect", websocket.url, req);
        }
      } else {
        req = websocket._req = request(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 URL3(location, address);
          } catch (e2) {
            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;
        if (res.headers.upgrade.toLowerCase() !== "websocket") {
          abortHandshake(websocket, socket, "Invalid Upgrade header");
          return;
        }
        const digest = createHash2("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 = parse5(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.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 = 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]);
      }
      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 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.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/subprotocol.js
var require_subprotocol = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
    "use strict";
    var { tokenChars } = require_validation();
    function parse5(header) {
      const protocols = /* @__PURE__ */ new Set();
      let start = -1;
      let end = -1;
      let i2 = 0;
      for (i2; i2 < header.length; i2++) {
        const code = header.charCodeAt(i2);
        if (end === -1 && tokenChars[code] === 1) {
          if (start === -1)
            start = i2;
        } else if (i2 !== 0 && (code === 32 || code === 9)) {
          if (end === -1 && start !== -1)
            end = i2;
        } else if (code === 44) {
          if (start === -1) {
            throw new SyntaxError(`Unexpected character at index ${i2}`);
          }
          if (end === -1)
            end = i2;
          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 ${i2}`);
        }
      }
      if (start === -1 || end !== -1) {
        throw new SyntaxError("Unexpected end of input");
      }
      const protocol = header.slice(start, i2);
      if (protocols.has(protocol)) {
        throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
      }
      protocols.add(protocol);
      return protocols;
    }
    module2.exports = { parse: parse5 };
  }
});

// ../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket-server.js
var require_websocket_server = __commonJS({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/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: createHash2 } = require("crypto");
    var extension = require_extension();
    var PerMessageDeflate = require_permessage_deflate();
    var subprotocol = require_subprotocol();
    var WebSocket2 = require_websocket();
    var { GUID, kWebSocket } = require_constants2();
    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 index5 = req.url.indexOf("?");
          const pathname = index5 !== -1 ? req.url.slice(0, index5) : 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 version3 = +req.headers["sec-websocket-version"];
        if (req.method !== "GET") {
          const message = "Invalid HTTP method";
          abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
          return;
        }
        if (req.headers.upgrade.toLowerCase() !== "websocket") {
          const message = "Invalid Upgrade header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (!key || !keyRegex.test(key)) {
          const message = "Missing or invalid Sec-WebSocket-Key header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (version3 !== 8 && version3 !== 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[`${version3 === 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 = createHash2("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, map) {
      for (const event of Object.keys(map))
        server.on(event, map[event]);
      return function removeListeners() {
        for (const event of Object.keys(map)) {
          server.removeListener(event, map[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((h2) => `${h2}: ${headers[h2]}`).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.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/wrapper.mjs
var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
var init_wrapper = __esm({
  "../node_modules/.pnpm/ws@8.17.0_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/wrapper.mjs"() {
    import_stream = __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/@smithy+types@3.0.0/node_modules/@smithy/types/dist-cjs/index.js
var require_dist_cjs = __commonJS({
  "../node_modules/.pnpm/@smithy+types@3.0.0/node_modules/@smithy/types/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AlgorithmId: () => AlgorithmId,
      EndpointURLScheme: () => EndpointURLScheme,
      FieldPosition: () => FieldPosition,
      HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation,
      HttpAuthLocation: () => HttpAuthLocation,
      IniSectionType: () => IniSectionType,
      RequestHandlerProtocol: () => RequestHandlerProtocol,
      SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY,
      getDefaultClientConfiguration: () => getDefaultClientConfiguration,
      resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => {
      HttpAuthLocation2["HEADER"] = "header";
      HttpAuthLocation2["QUERY"] = "query";
      return HttpAuthLocation2;
    })(HttpAuthLocation || {});
    var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => {
      HttpApiKeyAuthLocation2["HEADER"] = "header";
      HttpApiKeyAuthLocation2["QUERY"] = "query";
      return HttpApiKeyAuthLocation2;
    })(HttpApiKeyAuthLocation || {});
    var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => {
      EndpointURLScheme2["HTTP"] = "http";
      EndpointURLScheme2["HTTPS"] = "https";
      return EndpointURLScheme2;
    })(EndpointURLScheme || {});
    var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => {
      AlgorithmId2["MD5"] = "md5";
      AlgorithmId2["CRC32"] = "crc32";
      AlgorithmId2["CRC32C"] = "crc32c";
      AlgorithmId2["SHA1"] = "sha1";
      AlgorithmId2["SHA256"] = "sha256";
      return AlgorithmId2;
    })(AlgorithmId || {});
    var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const checksumAlgorithms = [];
      if (runtimeConfig.sha256 !== void 0) {
        checksumAlgorithms.push({
          algorithmId: () => "sha256",
          checksumConstructor: () => runtimeConfig.sha256
        });
      }
      if (runtimeConfig.md5 != void 0) {
        checksumAlgorithms.push({
          algorithmId: () => "md5",
          checksumConstructor: () => runtimeConfig.md5
        });
      }
      return {
        _checksumAlgorithms: checksumAlgorithms,
        addChecksumAlgorithm(algo) {
          this._checksumAlgorithms.push(algo);
        },
        checksumAlgorithms() {
          return this._checksumAlgorithms;
        }
      };
    }, "getChecksumConfiguration");
    var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => {
      const runtimeConfig = {};
      clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
        runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
      });
      return runtimeConfig;
    }, "resolveChecksumRuntimeConfig");
    var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      return {
        ...getChecksumConfiguration(runtimeConfig)
      };
    }, "getDefaultClientConfiguration");
    var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => {
      return {
        ...resolveChecksumRuntimeConfig(config)
      };
    }, "resolveDefaultRuntimeConfig");
    var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => {
      FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
      FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
      return FieldPosition2;
    })(FieldPosition || {});
    var SMITHY_CONTEXT_KEY = "__smithy_context";
    var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => {
      IniSectionType2["PROFILE"] = "profile";
      IniSectionType2["SSO_SESSION"] = "sso-session";
      IniSectionType2["SERVICES"] = "services";
      return IniSectionType2;
    })(IniSectionType || {});
    var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => {
      RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
      RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
      RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
      return RequestHandlerProtocol2;
    })(RequestHandlerProtocol || {});
  }
});

// ../node_modules/.pnpm/@smithy+protocol-http@4.0.0/node_modules/@smithy/protocol-http/dist-cjs/index.js
var require_dist_cjs2 = __commonJS({
  "../node_modules/.pnpm/@smithy+protocol-http@4.0.0/node_modules/@smithy/protocol-http/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Field: () => Field,
      Fields: () => Fields,
      HttpRequest: () => HttpRequest,
      HttpResponse: () => HttpResponse,
      getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration,
      isValidHostname: () => isValidHostname,
      resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      let httpHandler = runtimeConfig.httpHandler;
      return {
        setHttpHandler(handler) {
          httpHandler = handler;
        },
        httpHandler() {
          return httpHandler;
        },
        updateHttpClientConfig(key, value) {
          httpHandler.updateHttpClientConfig(key, value);
        },
        httpHandlerConfigs() {
          return httpHandler.httpHandlerConfigs();
        }
      };
    }, "getHttpHandlerExtensionConfiguration");
    var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => {
      return {
        httpHandler: httpHandlerExtensionConfiguration.httpHandler()
      };
    }, "resolveHttpHandlerRuntimeConfig");
    var import_types = require_dist_cjs();
    var _Field = class _Field {
      constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) {
        this.name = name;
        this.kind = kind;
        this.values = values;
      }
      /**
       * Appends a value to the field.
       *
       * @param value The value to append.
       */
      add(value) {
        this.values.push(value);
      }
      /**
       * Overwrite existing field values.
       *
       * @param values The new field values.
       */
      set(values) {
        this.values = values;
      }
      /**
       * Remove all matching entries from list.
       *
       * @param value Value to remove.
       */
      remove(value) {
        this.values = this.values.filter((v) => v !== value);
      }
      /**
       * Get comma-delimited string.
       *
       * @returns String representation of {@link Field}.
       */
      toString() {
        return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", ");
      }
      /**
       * Get string values as a list
       *
       * @returns Values in {@link Field} as a list.
       */
      get() {
        return this.values;
      }
    };
    __name(_Field, "Field");
    var Field = _Field;
    var _Fields = class _Fields {
      constructor({ fields = [], encoding = "utf-8" }) {
        this.entries = {};
        fields.forEach(this.setField.bind(this));
        this.encoding = encoding;
      }
      /**
       * Set entry for a {@link Field} name. The `name`
       * attribute will be used to key the collection.
       *
       * @param field The {@link Field} to set.
       */
      setField(field) {
        this.entries[field.name.toLowerCase()] = field;
      }
      /**
       *  Retrieve {@link Field} entry by name.
       *
       * @param name The name of the {@link Field} entry
       *  to retrieve
       * @returns The {@link Field} if it exists.
       */
      getField(name) {
        return this.entries[name.toLowerCase()];
      }
      /**
       * Delete entry from collection.
       *
       * @param name Name of the entry to delete.
       */
      removeField(name) {
        delete this.entries[name.toLowerCase()];
      }
      /**
       * Helper function for retrieving specific types of fields.
       * Used to grab all headers or all trailers.
       *
       * @param kind {@link FieldPosition} of entries to retrieve.
       * @returns The {@link Field} entries with the specified
       *  {@link FieldPosition}.
       */
      getByType(kind) {
        return Object.values(this.entries).filter((field) => field.kind === kind);
      }
    };
    __name(_Fields, "Fields");
    var Fields = _Fields;
    var _HttpRequest = class _HttpRequest2 {
      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 isInstance(request) {
        if (!request)
          return false;
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        const cloned = new _HttpRequest2({
          ...this,
          headers: { ...this.headers }
        });
        if (cloned.query)
          cloned.query = cloneQuery(cloned.query);
        return cloned;
      }
    };
    __name(_HttpRequest, "HttpRequest");
    var HttpRequest = _HttpRequest;
    function cloneQuery(query) {
      return Object.keys(query).reduce((carry, paramName) => {
        const param = query[paramName];
        return {
          ...carry,
          [paramName]: Array.isArray(param) ? [...param] : param
        };
      }, {});
    }
    __name(cloneQuery, "cloneQuery");
    var _HttpResponse = class _HttpResponse {
      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";
      }
    };
    __name(_HttpResponse, "HttpResponse");
    var HttpResponse = _HttpResponse;
    function isValidHostname(hostname) {
      const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
      return hostPattern.test(hostname);
    }
    __name(isValidHostname, "isValidHostname");
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.577.0/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js
var require_dist_cjs3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.577.0/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      getHostHeaderPlugin: () => getHostHeaderPlugin,
      hostHeaderMiddleware: () => hostHeaderMiddleware,
      hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions,
      resolveHostHeaderConfig: () => resolveHostHeaderConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http = require_dist_cjs2();
    function resolveHostHeaderConfig(input) {
      return input;
    }
    __name(resolveHostHeaderConfig, "resolveHostHeaderConfig");
    var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
      if (!import_protocol_http.HttpRequest.isInstance(args.request))
        return next(args);
      const { request } = args;
      const { handlerProtocol = "" } = options.requestHandler.metadata || {};
      if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) {
        delete request.headers["host"];
        request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : "");
      } else if (!request.headers["host"]) {
        let host = request.hostname;
        if (request.port != null)
          host += `:${request.port}`;
        request.headers["host"] = host;
      }
      return next(args);
    }, "hostHeaderMiddleware");
    var hostHeaderMiddlewareOptions = {
      name: "hostHeaderMiddleware",
      step: "build",
      priority: "low",
      tags: ["HOST"],
      override: true
    };
    var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
      }
    }), "getHostHeaderPlugin");
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.577.0/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js
var require_dist_cjs4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.577.0/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      getLoggerPlugin: () => getLoggerPlugin,
      loggerMiddleware: () => loggerMiddleware,
      loggerMiddlewareOptions: () => loggerMiddlewareOptions
    });
    module2.exports = __toCommonJS2(src_exports);
    var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => {
      var _a, _b;
      try {
        const response = await next(args);
        const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
        const { $metadata, ...outputWithoutMetadata } = response.output;
        (_a = logger == null ? void 0 : logger.info) == null ? void 0 : _a.call(logger, {
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          output: outputFilterSensitiveLog(outputWithoutMetadata),
          metadata: $metadata
        });
        return response;
      } catch (error2) {
        const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        (_b = logger == null ? void 0 : logger.error) == null ? void 0 : _b.call(logger, {
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          error: error2,
          metadata: error2.$metadata
        });
        throw error2;
      }
    }, "loggerMiddleware");
    var loggerMiddlewareOptions = {
      name: "loggerMiddleware",
      tags: ["LOGGER"],
      step: "initialize",
      override: true
    };
    var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
      }
    }), "getLoggerPlugin");
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.577.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js
var require_dist_cjs5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.577.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions,
      getRecursionDetectionPlugin: () => getRecursionDetectionPlugin,
      recursionDetectionMiddleware: () => recursionDetectionMiddleware
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http = require_dist_cjs2();
    var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
    var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
    var ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
    var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
      const { request } = args;
      if (!import_protocol_http.HttpRequest.isInstance(request) || options.runtime !== "node" || request.headers.hasOwnProperty(TRACE_ID_HEADER_NAME)) {
        return next(args);
      }
      const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
      const traceId = process.env[ENV_TRACE_ID];
      const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString");
      if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
        request.headers[TRACE_ID_HEADER_NAME] = traceId;
      }
      return next({
        ...args,
        request
      });
    }, "recursionDetectionMiddleware");
    var addRecursionDetectionMiddlewareOptions = {
      step: "build",
      tags: ["RECURSION_DETECTION"],
      name: "recursionDetectionMiddleware",
      override: true,
      priority: "low"
    };
    var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
      }
    }), "getRecursionDetectionPlugin");
  }
});

// ../node_modules/.pnpm/@smithy+util-endpoints@2.0.0/node_modules/@smithy/util-endpoints/dist-cjs/index.js
var require_dist_cjs6 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-endpoints@2.0.0/node_modules/@smithy/util-endpoints/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      EndpointError: () => EndpointError2,
      customEndpointFunctions: () => customEndpointFunctions,
      isIpAddress: () => isIpAddress2,
      isValidHostLabel: () => isValidHostLabel,
      resolveEndpoint: () => resolveEndpoint2
    });
    module2.exports = __toCommonJS2(src_exports);
    var 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}$`
    );
    var isIpAddress2 = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress");
    var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
    var isValidHostLabel = /* @__PURE__ */ __name((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;
    }, "isValidHostLabel");
    var customEndpointFunctions = {};
    var debugId = "endpoints";
    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);
    }
    __name(toDebugString, "toDebugString");
    var _EndpointError = class _EndpointError extends Error {
      constructor(message) {
        super(message);
        this.name = "EndpointError";
      }
    };
    __name(_EndpointError, "EndpointError");
    var EndpointError2 = _EndpointError;
    var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals");
    var getAttrPathList = /* @__PURE__ */ __name((path4) => {
      const parts = path4.split(".");
      const pathList = [];
      for (const part of parts) {
        const squareBracketIndex = part.indexOf("[");
        if (squareBracketIndex !== -1) {
          if (part.indexOf("]") !== part.length - 1) {
            throw new EndpointError2(`Path: '${path4}' does not end with ']'`);
          }
          const arrayIndex = part.slice(squareBracketIndex + 1, -1);
          if (Number.isNaN(parseInt(arrayIndex))) {
            throw new EndpointError2(`Invalid array index: '${arrayIndex}' in path: '${path4}'`);
          }
          if (squareBracketIndex !== 0) {
            pathList.push(part.slice(0, squareBracketIndex));
          }
          pathList.push(arrayIndex);
        } else {
          pathList.push(part);
        }
      }
      return pathList;
    }, "getAttrPathList");
    var getAttr = /* @__PURE__ */ __name((value, path4) => getAttrPathList(path4).reduce((acc, index5) => {
      if (typeof acc !== "object") {
        throw new EndpointError2(`Index '${index5}' in '${path4}' not found in '${JSON.stringify(value)}'`);
      } else if (Array.isArray(acc)) {
        return acc[parseInt(index5)];
      }
      return acc[index5];
    }, value), "getAttr");
    var isSet2 = /* @__PURE__ */ __name((value) => value != null, "isSet");
    var not = /* @__PURE__ */ __name((value) => !value, "not");
    var import_types3 = require_dist_cjs();
    var DEFAULT_PORTS = {
      [import_types3.EndpointURLScheme.HTTP]: 80,
      [import_types3.EndpointURLScheme.HTTPS]: 443
    };
    var parseURL = /* @__PURE__ */ __name((value) => {
      const whatwgURL = (() => {
        try {
          if (value instanceof URL) {
            return value;
          }
          if (typeof value === "object" && "hostname" in value) {
            const { hostname: hostname2, port, protocol: protocol2 = "", path: path4 = "", query = {} } = value;
            const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path4}`);
            url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).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(import_types3.EndpointURLScheme).includes(scheme)) {
        return null;
      }
      const isIp = isIpAddress2(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
      };
    }, "parseURL");
    var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals");
    var substring = /* @__PURE__ */ __name((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);
    }, "substring");
    var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode");
    var endpointFunctions = {
      booleanEquals,
      getAttr,
      isSet: isSet2,
      isValidHostLabel,
      not,
      parseURL,
      stringEquals,
      substring,
      uriEncode
    };
    var evaluateTemplate = /* @__PURE__ */ __name((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("");
    }, "evaluateTemplate");
    var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => {
      const referenceRecord = {
        ...options.endpointParams,
        ...options.referenceRecord
      };
      return referenceRecord[ref];
    }, "getReferenceValue");
    var evaluateExpression = /* @__PURE__ */ __name((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 EndpointError2(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
    }, "evaluateExpression");
    var callFunction = /* @__PURE__ */ __name(({ 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);
    }, "callFunction");
    var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => {
      var _a, _b;
      if (assign && assign in options.referenceRecord) {
        throw new EndpointError2(`'${assign}' is already defined in Reference Record.`);
      }
      const value = callFunction(fnArgs, options);
      (_b = (_a = options.logger) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, `${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
      return {
        result: value === "" ? true : !!value,
        ...assign != null && { toAssign: { name: assign, value } }
      };
    }, "evaluateCondition");
    var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => {
      var _a, _b;
      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;
          (_b = (_a = options.logger) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, `${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
        }
      }
      return { result: true, referenceRecord: conditionsReferenceRecord };
    }, "evaluateConditions");
    var getEndpointHeaders = /* @__PURE__ */ __name((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 EndpointError2(`Header '${headerKey}' value '${processedExpr}' is not a string`);
          }
          return processedExpr;
        })
      }),
      {}
    ), "getEndpointHeaders");
    var getEndpointProperty = /* @__PURE__ */ __name((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 EndpointError2(`Unexpected endpoint property: ${property}`);
          }
          return getEndpointProperties(property, options);
        case "boolean":
          return property;
        default:
          throw new EndpointError2(`Unexpected endpoint property type: ${typeof property}`);
      }
    }, "getEndpointProperty");
    var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce(
      (acc, [propertyKey, propertyVal]) => ({
        ...acc,
        [propertyKey]: getEndpointProperty(propertyVal, options)
      }),
      {}
    ), "getEndpointProperties");
    var getEndpointUrl = /* @__PURE__ */ __name((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 EndpointError2(`Endpoint URL must be a string, got ${typeof expression}`);
    }, "getEndpointUrl");
    var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => {
      var _a, _b;
      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;
      (_b = (_a = options.logger) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, `${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)
      };
    }, "evaluateEndpointRule");
    var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => {
      const { conditions, error: error2 } = errorRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      throw new EndpointError2(
        evaluateExpression(error2, "Error", {
          ...options,
          referenceRecord: { ...options.referenceRecord, ...referenceRecord }
        })
      );
    }, "evaluateErrorRule");
    var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => {
      const { conditions, rules } = treeRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      return evaluateRules(rules, {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      });
    }, "evaluateTreeRule");
    var evaluateRules = /* @__PURE__ */ __name((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 EndpointError2(`Unknown endpoint rule: ${rule}`);
        }
      }
      throw new EndpointError2(`Rules evaluation failed`);
    }, "evaluateRules");
    var resolveEndpoint2 = /* @__PURE__ */ __name((ruleSetObject, options) => {
      var _a, _b, _c, _d, _e;
      const { endpointParams, logger } = options;
      const { parameters, rules } = ruleSetObject;
      (_b = (_a = options.logger) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, `${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
      const paramsWithDefault = Object.entries(parameters).filter(([, v]) => v.default != null).map(([k, v]) => [k, v.default]);
      if (paramsWithDefault.length > 0) {
        for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
          endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
        }
      }
      const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k);
      for (const requiredParam of requiredParams) {
        if (endpointParams[requiredParam] == null) {
          throw new EndpointError2(`Missing required parameter: '${requiredParam}'`);
        }
      }
      const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} });
      if ((_c = options.endpointParams) == null ? void 0 : _c.Endpoint) {
        try {
          const givenEndpoint = new URL(options.endpointParams.Endpoint);
          const { protocol, port } = givenEndpoint;
          endpoint.url.protocol = protocol;
          endpoint.url.port = port;
        } catch (e2) {
        }
      }
      (_e = (_d = options.logger) == null ? void 0 : _d.debug) == null ? void 0 : _e.call(_d, `${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
      return endpoint;
    }, "resolveEndpoint");
  }
});

// ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.583.0/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js
var require_dist_cjs7 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.583.0/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      ConditionObject: () => import_util_endpoints.ConditionObject,
      DeprecatedObject: () => import_util_endpoints.DeprecatedObject,
      EndpointError: () => import_util_endpoints.EndpointError,
      EndpointObject: () => import_util_endpoints.EndpointObject,
      EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders,
      EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties,
      EndpointParams: () => import_util_endpoints.EndpointParams,
      EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions,
      EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject,
      ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject,
      EvaluateOptions: () => import_util_endpoints.EvaluateOptions,
      Expression: () => import_util_endpoints.Expression,
      FunctionArgv: () => import_util_endpoints.FunctionArgv,
      FunctionObject: () => import_util_endpoints.FunctionObject,
      FunctionReturn: () => import_util_endpoints.FunctionReturn,
      ParameterObject: () => import_util_endpoints.ParameterObject,
      ReferenceObject: () => import_util_endpoints.ReferenceObject,
      ReferenceRecord: () => import_util_endpoints.ReferenceRecord,
      RuleSetObject: () => import_util_endpoints.RuleSetObject,
      RuleSetRules: () => import_util_endpoints.RuleSetRules,
      TreeRuleObject: () => import_util_endpoints.TreeRuleObject,
      awsEndpointFunctions: () => awsEndpointFunctions,
      getUserAgentPrefix: () => getUserAgentPrefix,
      isIpAddress: () => import_util_endpoints.isIpAddress,
      partition: () => partition,
      resolveEndpoint: () => import_util_endpoints.resolveEndpoint,
      setPartitionInfo: () => setPartitionInfo,
      useDefaultPartitionInfo: () => useDefaultPartitionInfo
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_endpoints = require_dist_cjs6();
    var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => {
      if (allowSubDomains) {
        for (const label of value.split(".")) {
          if (!isVirtualHostableS3Bucket(label)) {
            return false;
          }
        }
        return true;
      }
      if (!(0, import_util_endpoints.isValidHostLabel)(value)) {
        return false;
      }
      if (value.length < 3 || value.length > 63) {
        return false;
      }
      if (value !== value.toLowerCase()) {
        return false;
      }
      if ((0, import_util_endpoints.isIpAddress)(value)) {
        return false;
      }
      return true;
    }, "isVirtualHostableS3Bucket");
    var parseArn = /* @__PURE__ */ __name((value) => {
      const segments = value.split(":");
      if (segments.length < 6)
        return null;
      const [arn, partition2, service, region, accountId, ...resourceId] = segments;
      if (arn !== "arn" || partition2 === "" || service === "" || resourceId[0] === "")
        return null;
      return {
        partition: partition2,
        service,
        region,
        accountId,
        resourceId: resourceId[0].includes("/") ? resourceId[0].split("/") : resourceId
      };
    }, "parseArn");
    var 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)\\-\\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)"
          },
          "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)"
          },
          "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: {
          "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: {}
      }],
      version: "1.1"
    };
    var selectedPartitionsInfo = partitions_default;
    var selectedUserAgentPrefix = "";
    var partition = /* @__PURE__ */ __name((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
      };
    }, "partition");
    var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => {
      selectedPartitionsInfo = partitionsInfo;
      selectedUserAgentPrefix = userAgentPrefix;
    }, "setPartitionInfo");
    var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => {
      setPartitionInfo(partitions_default, "");
    }, "useDefaultPartitionInfo");
    var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix");
    var awsEndpointFunctions = {
      isVirtualHostableS3Bucket,
      parseArn,
      partition
    };
    import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.583.0/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js
var require_dist_cjs8 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.583.0/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions,
      getUserAgentPlugin: () => getUserAgentPlugin,
      resolveUserAgentConfig: () => resolveUserAgentConfig,
      userAgentMiddleware: () => userAgentMiddleware
    });
    module2.exports = __toCommonJS2(src_exports);
    function resolveUserAgentConfig(input) {
      return {
        ...input,
        customUserAgent: typeof input.customUserAgent === "string" ? [[input.customUserAgent]] : input.customUserAgent
      };
    }
    __name(resolveUserAgentConfig, "resolveUserAgentConfig");
    var import_util_endpoints = require_dist_cjs7();
    var import_protocol_http = require_dist_cjs2();
    var USER_AGENT = "user-agent";
    var X_AMZ_USER_AGENT = "x-amz-user-agent";
    var SPACE2 = " ";
    var UA_NAME_SEPARATOR = "/";
    var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
    var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
    var UA_ESCAPE_CHAR = "-";
    var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => {
      var _a, _b;
      const { request } = args;
      if (!import_protocol_http.HttpRequest.isInstance(request))
        return next(args);
      const { headers } = request;
      const userAgent = ((_a = context == null ? void 0 : context.userAgent) == null ? void 0 : _a.map(escapeUserAgent)) || [];
      const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
      const customUserAgent = ((_b = options == null ? void 0 : options.customUserAgent) == null ? void 0 : _b.map(escapeUserAgent)) || [];
      const prefix2 = (0, import_util_endpoints.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
      });
    }, "userAgentMiddleware");
    var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => {
      var _a;
      const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
      const version3 = (_a = userAgentPair[1]) == null ? void 0 : _a.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, version3].filter((item) => item && item.length > 0).reduce((acc, item, index5) => {
        switch (index5) {
          case 0:
            return item;
          case 1:
            return `${acc}/${item}`;
          default:
            return `${acc}#${item}`;
        }
      }, "");
    }, "escapeUserAgent");
    var getUserAgentMiddlewareOptions = {
      name: "getUserAgentMiddleware",
      step: "build",
      priority: "low",
      tags: ["SET_USER_AGENT", "USER_AGENT"],
      override: true
    };
    var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({
      applyToStack: (clientStack) => {
        clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
      }
    }), "getUserAgentPlugin");
  }
});

// ../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-cjs/index.js
var require_dist_cjs9 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-config-provider@3.0.0/node_modules/@smithy/util-config-provider/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      SelectorType: () => SelectorType,
      booleanSelector: () => booleanSelector,
      numberSelector: () => numberSelector
    });
    module2.exports = __toCommonJS2(src_exports);
    var booleanSelector = /* @__PURE__ */ __name((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]}.`);
    }, "booleanSelector");
    var numberSelector = /* @__PURE__ */ __name((obj, key, type) => {
      if (!(key in obj))
        return void 0;
      const numberValue = parseInt(obj[key], 10);
      if (Number.isNaN(numberValue)) {
        throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`);
      }
      return numberValue;
    }, "numberSelector");
    var SelectorType = /* @__PURE__ */ ((SelectorType2) => {
      SelectorType2["ENV"] = "env";
      SelectorType2["CONFIG"] = "shared config entry";
      return SelectorType2;
    })(SelectorType || {});
  }
});

// ../node_modules/.pnpm/@smithy+util-middleware@3.0.0/node_modules/@smithy/util-middleware/dist-cjs/index.js
var require_dist_cjs10 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-middleware@3.0.0/node_modules/@smithy/util-middleware/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      getSmithyContext: () => getSmithyContext2,
      normalizeProvider: () => normalizeProvider
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_types = require_dist_cjs();
    var getSmithyContext2 = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext");
    var normalizeProvider = /* @__PURE__ */ __name((input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    }, "normalizeProvider");
  }
});

// ../node_modules/.pnpm/@smithy+config-resolver@3.0.0/node_modules/@smithy/config-resolver/dist-cjs/index.js
var require_dist_cjs11 = __commonJS({
  "../node_modules/.pnpm/@smithy+config-resolver@3.0.0/node_modules/@smithy/config-resolver/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT,
      CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT,
      DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT,
      DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT,
      ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT,
      ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT,
      NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS,
      NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS,
      NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,
      NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,
      REGION_ENV_NAME: () => REGION_ENV_NAME,
      REGION_INI_NAME: () => REGION_INI_NAME,
      getRegionInfo: () => getRegionInfo,
      resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig,
      resolveEndpointsConfig: () => resolveEndpointsConfig,
      resolveRegionConfig: () => resolveRegionConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_config_provider = require_dist_cjs9();
    var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
    var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
    var DEFAULT_USE_DUALSTACK_ENDPOINT = false;
    var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => (0, import_util_config_provider.booleanSelector)(env3, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV),
      configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG),
      default: false
    };
    var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
    var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
    var DEFAULT_USE_FIPS_ENDPOINT = false;
    var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => (0, import_util_config_provider.booleanSelector)(env3, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV),
      configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG),
      default: false
    };
    var import_util_middleware = require_dist_cjs10();
    var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => {
      const { endpoint, urlParser } = input;
      return {
        ...input,
        tls: input.tls ?? true,
        endpoint: (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint),
        isCustomEndpoint: true,
        useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false)
      };
    }, "resolveCustomEndpointsConfig");
    var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => {
      const { tls = true } = input;
      const region = await input.region();
      const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/);
      if (!dnsHostRegex.test(region)) {
        throw new Error("Invalid region in client config");
      }
      const useDualstackEndpoint = await input.useDualstackEndpoint();
      const useFipsEndpoint = await input.useFipsEndpoint();
      const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {};
      if (!hostname) {
        throw new Error("Cannot resolve hostname from client config");
      }
      return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`);
    }, "getEndpointFromRegion");
    var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => {
      const useDualstackEndpoint = (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false);
      const { endpoint, useFipsEndpoint, urlParser } = input;
      return {
        ...input,
        tls: input.tls ?? true,
        endpoint: endpoint ? (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }),
        isCustomEndpoint: !!endpoint,
        useDualstackEndpoint
      };
    }, "resolveEndpointsConfig");
    var REGION_ENV_NAME = "AWS_REGION";
    var REGION_INI_NAME = "region";
    var NODE_REGION_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => env3[REGION_ENV_NAME],
      configFileSelector: (profile) => profile[REGION_INI_NAME],
      default: () => {
        throw new Error("Region is missing");
      }
    };
    var NODE_REGION_CONFIG_FILE_OPTIONS = {
      preferredFile: "credentials"
    };
    var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion");
    var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion");
    var resolveRegionConfig = /* @__PURE__ */ __name((input) => {
      const { region, useFipsEndpoint } = input;
      if (!region) {
        throw new Error("Region is missing");
      }
      return {
        ...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();
        }
      };
    }, "resolveRegionConfig");
    var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => {
      var _a;
      return (_a = variants.find(
        ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack")
      )) == null ? void 0 : _a.hostname;
    }, "getHostnameFromVariants");
    var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname");
    var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition");
    var getResolvedSigningRegion = /* @__PURE__ */ __name((hostname, { signingRegion, regionRegex, useFipsEndpoint }) => {
      if (signingRegion) {
        return signingRegion;
      } else if (useFipsEndpoint) {
        const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\.");
        const regionRegexmatchArray = hostname.match(regionRegexJs);
        if (regionRegexmatchArray) {
          return regionRegexmatchArray[0].slice(1, -1);
        }
      }
    }, "getResolvedSigningRegion");
    var getRegionInfo = /* @__PURE__ */ __name((region, {
      useFipsEndpoint = false,
      useDualstackEndpoint = false,
      signingService,
      regionHash,
      partitionHash
    }) => {
      var _a, _b, _c, _d, _e;
      const partition = getResolvedPartition(region, { partitionHash });
      const resolvedRegion = region in regionHash ? region : ((_a = partitionHash[partition]) == null ? void 0 : _a.endpoint) ?? region;
      const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint };
      const regionHostname = getHostnameFromVariants((_b = regionHash[resolvedRegion]) == null ? void 0 : _b.variants, hostnameOptions);
      const partitionHostname = getHostnameFromVariants((_c = partitionHash[partition]) == null ? void 0 : _c.variants, hostnameOptions);
      const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname });
      if (hostname === void 0) {
        throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`);
      }
      const signingRegion = getResolvedSigningRegion(hostname, {
        signingRegion: (_d = regionHash[resolvedRegion]) == null ? void 0 : _d.signingRegion,
        regionRegex: partitionHash[partition].regionRegex,
        useFipsEndpoint
      });
      return {
        partition,
        signingService,
        hostname,
        ...signingRegion && { signingRegion },
        ...((_e = regionHash[resolvedRegion]) == null ? void 0 : _e.signingService) && {
          signingService: regionHash[resolvedRegion].signingService
        }
      };
    }, "getRegionInfo");
  }
});

// ../node_modules/.pnpm/@smithy+property-provider@3.0.0/node_modules/@smithy/property-provider/dist-cjs/index.js
var require_dist_cjs12 = __commonJS({
  "../node_modules/.pnpm/@smithy+property-provider@3.0.0/node_modules/@smithy/property-provider/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      CredentialsProviderError: () => CredentialsProviderError,
      ProviderError: () => ProviderError,
      TokenProviderError: () => TokenProviderError,
      chain: () => chain,
      fromStatic: () => fromStatic,
      memoize: () => memoize
    });
    module2.exports = __toCommonJS2(src_exports);
    var _ProviderError = class _ProviderError2 extends Error {
      constructor(message, tryNextLink = true) {
        super(message);
        this.tryNextLink = tryNextLink;
        this.name = "ProviderError";
        Object.setPrototypeOf(this, _ProviderError2.prototype);
      }
      static from(error2, tryNextLink = true) {
        return Object.assign(new this(error2.message, tryNextLink), error2);
      }
    };
    __name(_ProviderError, "ProviderError");
    var ProviderError = _ProviderError;
    var _CredentialsProviderError = class _CredentialsProviderError2 extends ProviderError {
      constructor(message, tryNextLink = true) {
        super(message, tryNextLink);
        this.tryNextLink = tryNextLink;
        this.name = "CredentialsProviderError";
        Object.setPrototypeOf(this, _CredentialsProviderError2.prototype);
      }
    };
    __name(_CredentialsProviderError, "CredentialsProviderError");
    var CredentialsProviderError = _CredentialsProviderError;
    var _TokenProviderError = class _TokenProviderError2 extends ProviderError {
      constructor(message, tryNextLink = true) {
        super(message, tryNextLink);
        this.tryNextLink = tryNextLink;
        this.name = "TokenProviderError";
        Object.setPrototypeOf(this, _TokenProviderError2.prototype);
      }
    };
    __name(_TokenProviderError, "TokenProviderError");
    var TokenProviderError = _TokenProviderError;
    var chain = /* @__PURE__ */ __name((...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 == null ? void 0 : err2.tryNextLink) {
            continue;
          }
          throw err2;
        }
      }
      throw lastProviderError;
    }, "chain");
    var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic");
    var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => {
      let resolved;
      let pending;
      let hasResult;
      let isConstant = false;
      const coalesceProvider = /* @__PURE__ */ __name(async () => {
        if (!pending) {
          pending = provider();
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      }, "coalesceProvider");
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
            resolved = await coalesceProvider();
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || (options == null ? void 0 : 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;
      };
    }, "memoize");
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js
var require_getHomeDir = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getHomeDir = void 0;
    var os_1 = require("os");
    var path_1 = require("path");
    var homeDirCache = {};
    var getHomeDirCacheKey = () => {
      if (process && process.geteuid) {
        return `${process.geteuid()}`;
      }
      return "DEFAULT";
    };
    var getHomeDir2 = () => {
      const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.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, os_1.homedir)();
      return homeDirCache[homeDirCacheKey];
    };
    exports2.getHomeDir = getHomeDir2;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js
var require_getSSOTokenFilepath = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSSOTokenFilepath = void 0;
    var crypto_1 = require("crypto");
    var path_1 = require("path");
    var getHomeDir_1 = require_getHomeDir();
    var getSSOTokenFilepath2 = (id) => {
      const hasher = (0, crypto_1.createHash)("sha1");
      const cacheName = hasher.update(id).digest("hex");
      return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`);
    };
    exports2.getSSOTokenFilepath = getSSOTokenFilepath2;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js
var require_getSSOTokenFromFile = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSSOTokenFromFile = void 0;
    var fs_1 = require("fs");
    var getSSOTokenFilepath_1 = require_getSSOTokenFilepath();
    var { readFile: readFile2 } = fs_1.promises;
    var getSSOTokenFromFile2 = async (id) => {
      const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id);
      const ssoTokenText = await readFile2(ssoTokenFilepath, "utf8");
      return JSON.parse(ssoTokenText);
    };
    exports2.getSSOTokenFromFile = getSSOTokenFromFile2;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/slurpFile.js
var require_slurpFile = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/slurpFile.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.slurpFile = void 0;
    var fs_1 = require("fs");
    var { readFile: readFile2 } = fs_1.promises;
    var filePromisesHash = {};
    var slurpFile = (path4, options) => {
      if (!filePromisesHash[path4] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) {
        filePromisesHash[path4] = readFile2(path4, "utf8");
      }
      return filePromisesHash[path4];
    };
    exports2.slurpFile = slurpFile;
  }
});

// ../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js
var require_dist_cjs13 = __commonJS({
  "../node_modules/.pnpm/@smithy+shared-ini-file-loader@3.0.0/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR,
      DEFAULT_PROFILE: () => DEFAULT_PROFILE,
      ENV_PROFILE: () => ENV_PROFILE,
      getProfileName: () => getProfileName,
      loadSharedConfigFiles: () => loadSharedConfigFiles,
      loadSsoSessionData: () => loadSsoSessionData,
      parseKnownFiles: () => parseKnownFiles
    });
    module2.exports = __toCommonJS2(src_exports);
    __reExport(src_exports, require_getHomeDir(), module2.exports);
    var ENV_PROFILE = "AWS_PROFILE";
    var DEFAULT_PROFILE = "default";
    var getProfileName = /* @__PURE__ */ __name((init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName");
    __reExport(src_exports, require_getSSOTokenFilepath(), module2.exports);
    __reExport(src_exports, require_getSSOTokenFromFile(), module2.exports);
    var import_types = require_dist_cjs();
    var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => {
      const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
      if (indexOfSeparator === -1) {
        return false;
      }
      return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator));
    }).reduce(
      (acc, [key, value]) => {
        const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
        const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;
        acc[updatedKey] = value;
        return acc;
      },
      {
        // Populate default profile, if present.
        ...data.default && { default: data.default }
      }
    ), "getConfigData");
    var import_path8 = require("path");
    var import_getHomeDir = require_getHomeDir();
    var ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
    var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path8.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath");
    var import_getHomeDir2 = require_getHomeDir();
    var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
    var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path8.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath");
    var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
    var profileNameBlockList = ["__proto__", "profile __proto__"];
    var parseIni = /* @__PURE__ */ __name((iniData) => {
      const map = {};
      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(import_types.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;
              }
              map[currentSection] = map[currentSection] || {};
              const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;
              map[currentSection][key] = value;
            }
          }
        }
      }
      return map;
    }, "parseIni");
    var import_slurpFile = require_slurpFile();
    var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError");
    var CONFIG_PREFIX_SEPARATOR = ".";
    var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init2 = {}) => {
      const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2;
      const parsedFiles = await Promise.all([
        (0, import_slurpFile.slurpFile)(configFilepath, {
          ignoreCache: init2.ignoreCache
        }).then(parseIni).then(getConfigData).catch(swallowError),
        (0, import_slurpFile.slurpFile)(filepath, {
          ignoreCache: init2.ignoreCache
        }).then(parseIni).catch(swallowError)
      ]);
      return {
        configFile: parsedFiles[0],
        credentialsFile: parsedFiles[1]
      };
    }, "loadSharedConfigFiles");
    var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData");
    var import_slurpFile2 = require_slurpFile();
    var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError");
    var loadSsoSessionData = /* @__PURE__ */ __name(async (init2 = {}) => (0, import_slurpFile2.slurpFile)(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData");
    var mergeConfigFiles = /* @__PURE__ */ __name((...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;
    }, "mergeConfigFiles");
    var parseKnownFiles = /* @__PURE__ */ __name(async (init2) => {
      const parsedFiles = await loadSharedConfigFiles(init2);
      return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
    }, "parseKnownFiles");
  }
});

// ../node_modules/.pnpm/@smithy+node-config-provider@3.0.0/node_modules/@smithy/node-config-provider/dist-cjs/index.js
var require_dist_cjs14 = __commonJS({
  "../node_modules/.pnpm/@smithy+node-config-provider@3.0.0/node_modules/@smithy/node-config-provider/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      loadConfig: () => loadConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_property_provider = require_dist_cjs12();
    var fromEnv = /* @__PURE__ */ __name((envVarSelector) => async () => {
      try {
        const config = envVarSelector(process.env);
        if (config === void 0) {
          throw new Error();
        }
        return config;
      } catch (e2) {
        throw new import_property_provider.CredentialsProviderError(
          e2.message || `Cannot load config from environment variables with getter: ${envVarSelector}`
        );
      }
    }, "fromEnv");
    var import_shared_ini_file_loader = require_dist_cjs13();
    var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init2 } = {}) => async () => {
      const profile = (0, import_shared_ini_file_loader.getProfileName)(init2);
      const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.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 (e2) {
        throw new import_property_provider.CredentialsProviderError(
          e2.message || `Cannot load config for profile ${profile} in SDK configuration files with getter: ${configSelector}`
        );
      }
    }, "fromSharedConfigFiles");
    var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction");
    var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic");
    var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => (0, import_property_provider.memoize)(
      (0, import_property_provider.chain)(
        fromEnv(environmentVariableSelector),
        fromSharedConfigFiles(configFileSelector, configuration),
        fromStatic(defaultValue)
      )
    ), "loadConfig");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@3.0.0/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js
var require_getEndpointUrlConfig = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@3.0.0/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getEndpointUrlConfig = void 0;
    var shared_ini_file_loader_1 = require_dist_cjs13();
    var ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
    var CONFIG_ENDPOINT_URL = "endpoint_url";
    var getEndpointUrlConfig = (serviceId) => ({
      environmentVariableSelector: (env3) => {
        const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase());
        const serviceEndpointUrl = env3[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")];
        if (serviceEndpointUrl)
          return serviceEndpointUrl;
        const endpointUrl = env3[ENV_ENDPOINT_URL];
        if (endpointUrl)
          return endpointUrl;
        return void 0;
      },
      configFileSelector: (profile, config) => {
        if (config && profile.services) {
          const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
          if (servicesSection) {
            const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase());
            const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
            if (endpointUrl2)
              return endpointUrl2;
          }
        }
        const endpointUrl = profile[CONFIG_ENDPOINT_URL];
        if (endpointUrl)
          return endpointUrl;
        return void 0;
      },
      default: void 0
    });
    exports2.getEndpointUrlConfig = getEndpointUrlConfig;
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@3.0.0/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js
var require_getEndpointFromConfig = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@3.0.0/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getEndpointFromConfig = void 0;
    var node_config_provider_1 = require_dist_cjs14();
    var getEndpointUrlConfig_1 = require_getEndpointUrlConfig();
    var getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId))();
    exports2.getEndpointFromConfig = getEndpointFromConfig;
  }
});

// ../node_modules/.pnpm/@smithy+querystring-parser@3.0.0/node_modules/@smithy/querystring-parser/dist-cjs/index.js
var require_dist_cjs15 = __commonJS({
  "../node_modules/.pnpm/@smithy+querystring-parser@3.0.0/node_modules/@smithy/querystring-parser/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      parseQueryString: () => parseQueryString
    });
    module2.exports = __toCommonJS2(src_exports);
    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;
    }
    __name(parseQueryString, "parseQueryString");
  }
});

// ../node_modules/.pnpm/@smithy+url-parser@3.0.0/node_modules/@smithy/url-parser/dist-cjs/index.js
var require_dist_cjs16 = __commonJS({
  "../node_modules/.pnpm/@smithy+url-parser@3.0.0/node_modules/@smithy/url-parser/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      parseUrl: () => parseUrl
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_querystring_parser = require_dist_cjs15();
    var parseUrl = /* @__PURE__ */ __name((url) => {
      if (typeof url === "string") {
        return parseUrl(new URL(url));
      }
      const { hostname, pathname, port, protocol, search } = url;
      let query;
      if (search) {
        query = (0, import_querystring_parser.parseQueryString)(search);
      }
      return {
        hostname,
        port: port ? parseInt(port) : void 0,
        protocol,
        path: pathname,
        query
      };
    }, "parseUrl");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-serde@3.0.0/node_modules/@smithy/middleware-serde/dist-cjs/index.js
var require_dist_cjs17 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-serde@3.0.0/node_modules/@smithy/middleware-serde/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      deserializerMiddleware: () => deserializerMiddleware,
      deserializerMiddlewareOption: () => deserializerMiddlewareOption,
      getSerdePlugin: () => getSerdePlugin,
      serializerMiddleware: () => serializerMiddleware,
      serializerMiddlewareOption: () => serializerMiddlewareOption
    });
    module2.exports = __toCommonJS2(src_exports);
    var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next) => 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.`;
          error2.message += "\n  " + hint;
          if (typeof error2.$responseBodyText !== "undefined") {
            if (error2.$response) {
              error2.$response.body = error2.$responseBodyText;
            }
          }
        }
        throw error2;
      }
    }, "deserializerMiddleware");
    var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => {
      var _a;
      const endpoint = ((_a = context.endpointV2) == null ? void 0 : _a.url) && options.urlParser ? async () => options.urlParser(context.endpointV2.url) : options.endpoint;
      if (!endpoint) {
        throw new Error("No valid endpoint provider available.");
      }
      const request = await serializer(args.input, { ...options, endpoint });
      return next({
        ...args,
        request
      });
    }, "serializerMiddleware");
    var deserializerMiddlewareOption = {
      name: "deserializerMiddleware",
      step: "deserialize",
      tags: ["DESERIALIZER"],
      override: true
    };
    var serializerMiddlewareOption = {
      name: "serializerMiddleware",
      step: "serialize",
      tags: ["SERIALIZER"],
      override: true
    };
    function getSerdePlugin(config, serializer, deserializer) {
      return {
        applyToStack: (commandStack) => {
          commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
          commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);
        }
      };
    }
    __name(getSerdePlugin, "getSerdePlugin");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-endpoint@3.0.0/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js
var require_dist_cjs18 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-endpoint@3.0.0/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      endpointMiddleware: () => endpointMiddleware,
      endpointMiddlewareOptions: () => endpointMiddlewareOptions,
      getEndpointFromInstructions: () => getEndpointFromInstructions,
      getEndpointPlugin: () => getEndpointPlugin,
      resolveEndpointConfig: () => resolveEndpointConfig,
      resolveParams: () => resolveParams,
      toEndpointV1: () => toEndpointV1
    });
    module2.exports = __toCommonJS2(src_exports);
    var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => {
      const bucket = (endpointParams == null ? void 0 : 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;
    }, "resolveParamsForS3");
    var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
    var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
    var DOTS_PATTERN = /\.\./;
    var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName");
    var isArnBucketName = /* @__PURE__ */ __name((bucketName) => {
      const [arn, partition, service, , , bucket] = bucketName.split(":");
      const isArn = arn === "arn" && bucketName.split(":").length >= 6;
      const isValidArn = Boolean(isArn && partition && service && bucket);
      if (isArn && !isValidArn) {
        throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
      }
      return isValidArn;
    }, "isArnBucketName");
    var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => {
      const configProvider = /* @__PURE__ */ __name(async () => {
        const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
        if (typeof configValue === "function") {
          return configValue();
        }
        return configValue;
      }, "configProvider");
      if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
        return async () => {
          const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
          const configValue = (credentials2 == null ? void 0 : credentials2.credentialScope) ?? (credentials2 == null ? void 0 : credentials2.CredentialScope);
          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: path4 } = endpoint;
              return `${protocol}//${hostname}${port ? ":" + port : ""}${path4}`;
            }
          }
          return endpoint;
        };
      }
      return configProvider;
    }, "createConfigValueProvider");
    var import_getEndpointFromConfig = require_getEndpointFromConfig();
    var import_url_parser = require_dist_cjs16();
    var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => {
      if (typeof endpoint === "object") {
        if ("url" in endpoint) {
          return (0, import_url_parser.parseUrl)(endpoint.url);
        }
        return endpoint;
      }
      return (0, import_url_parser.parseUrl)(endpoint);
    }, "toEndpointV1");
    var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => {
      if (!clientConfig.endpoint) {
        const endpointFromConfig = await (0, import_getEndpointFromConfig.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;
    }, "getEndpointFromInstructions");
    var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => {
      var _a;
      const endpointParams = {};
      const instructions = ((_a = instructionsSupplier == null ? void 0 : instructionsSupplier.getEndpointParameterInstructions) == null ? void 0 : _a.call(instructionsSupplier)) || {};
      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;
          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;
    }, "resolveParams");
    var import_util_middleware = require_dist_cjs10();
    var endpointMiddleware = /* @__PURE__ */ __name(({
      config,
      instructions
    }) => {
      return (next, context) => async (args) => {
        var _a, _b, _c;
        const endpoint = await getEndpointFromInstructions(
          args.input,
          {
            getEndpointParameterInstructions() {
              return instructions;
            }
          },
          { ...config },
          context
        );
        context.endpointV2 = endpoint;
        context.authSchemes = (_a = endpoint.properties) == null ? void 0 : _a.authSchemes;
        const authScheme = (_b = context.authSchemes) == null ? void 0 : _b[0];
        if (authScheme) {
          context["signing_region"] = authScheme.signingRegion;
          context["signing_service"] = authScheme.signingName;
          const smithyContext = (0, import_util_middleware.getSmithyContext)(context);
          const httpAuthOption = (_c = smithyContext == null ? void 0 : smithyContext.selectedHttpAuthScheme) == null ? void 0 : _c.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
        });
      };
    }, "endpointMiddleware");
    var import_middleware_serde = require_dist_cjs17();
    var endpointMiddlewareOptions = {
      step: "serialize",
      tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
      name: "endpointV2Middleware",
      override: true,
      relation: "before",
      toMiddleware: import_middleware_serde.serializerMiddlewareOption.name
    };
    var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(
          endpointMiddleware({
            config,
            instructions
          }),
          endpointMiddlewareOptions
        );
      }
    }), "getEndpointPlugin");
    var resolveEndpointConfig = /* @__PURE__ */ __name((input) => {
      const tls = input.tls ?? true;
      const { endpoint } = input;
      const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0;
      const isCustomEndpoint = !!endpoint;
      return {
        ...input,
        endpoint: customEndpointProvider,
        tls,
        isCustomEndpoint,
        useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false),
        useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(input.useFipsEndpoint ?? false)
      };
    }, "resolveEndpointConfig");
  }
});

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

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js
var regex_default;
var init_regex = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js"() {
    regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js
function validate(uuid) {
  return typeof uuid === "string" && regex_default.test(uuid);
}
var validate_default;
var init_validate = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js"() {
    init_regex();
    validate_default = validate;
  }
});

// ../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]];
}
function stringify(arr, offset = 0) {
  const uuid = unsafeStringify(arr, offset);
  if (!validate_default(uuid)) {
    throw TypeError("Stringified UUID is invalid");
  }
  return uuid;
}
var byteToHex, stringify_default;
var init_stringify = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js"() {
    init_validate();
    byteToHex = [];
    for (let i2 = 0; i2 < 256; ++i2) {
      byteToHex.push((i2 + 256).toString(16).slice(1));
    }
    stringify_default = stringify;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v1.js
function v1(options, buf, offset) {
  let i2 = buf && offset || 0;
  const b = buf || new Array(16);
  options = options || {};
  let node = options.node || _nodeId;
  let clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq;
  if (node == null || clockseq == null) {
    const seedBytes = options.random || (options.rng || rng)();
    if (node == null) {
      node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
    }
    if (clockseq == null) {
      clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
    }
  }
  let msecs = options.msecs !== void 0 ? options.msecs : Date.now();
  let nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1;
  const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
  if (dt < 0 && options.clockseq === void 0) {
    clockseq = clockseq + 1 & 16383;
  }
  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) {
    nsecs = 0;
  }
  if (nsecs >= 1e4) {
    throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  }
  _lastMSecs = msecs;
  _lastNSecs = nsecs;
  _clockseq = clockseq;
  msecs += 122192928e5;
  const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
  b[i2++] = tl >>> 24 & 255;
  b[i2++] = tl >>> 16 & 255;
  b[i2++] = tl >>> 8 & 255;
  b[i2++] = tl & 255;
  const tmh = msecs / 4294967296 * 1e4 & 268435455;
  b[i2++] = tmh >>> 8 & 255;
  b[i2++] = tmh & 255;
  b[i2++] = tmh >>> 24 & 15 | 16;
  b[i2++] = tmh >>> 16 & 255;
  b[i2++] = clockseq >>> 8 | 128;
  b[i2++] = clockseq & 255;
  for (let n = 0; n < 6; ++n) {
    b[i2 + n] = node[n];
  }
  return buf || unsafeStringify(b);
}
var _nodeId, _clockseq, _lastMSecs, _lastNSecs, v1_default;
var init_v1 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v1.js"() {
    init_rng();
    init_stringify();
    _lastMSecs = 0;
    _lastNSecs = 0;
    v1_default = v1;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/parse.js
function parse2(uuid) {
  if (!validate_default(uuid)) {
    throw TypeError("Invalid UUID");
  }
  let v;
  const arr = new Uint8Array(16);
  arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  arr[1] = v >>> 16 & 255;
  arr[2] = v >>> 8 & 255;
  arr[3] = v & 255;
  arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  arr[5] = v & 255;
  arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  arr[7] = v & 255;
  arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  arr[9] = v & 255;
  arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
  arr[11] = v / 4294967296 & 255;
  arr[12] = v >>> 24 & 255;
  arr[13] = v >>> 16 & 255;
  arr[14] = v >>> 8 & 255;
  arr[15] = v & 255;
  return arr;
}
var parse_default;
var init_parse = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/parse.js"() {
    init_validate();
    parse_default = parse2;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v35.js
function stringToBytes(str) {
  str = unescape(encodeURIComponent(str));
  const bytes = [];
  for (let i2 = 0; i2 < str.length; ++i2) {
    bytes.push(str.charCodeAt(i2));
  }
  return bytes;
}
function v35(name, version3, hashfunc) {
  function generateUUID(value, namespace, buf, offset) {
    var _namespace;
    if (typeof value === "string") {
      value = stringToBytes(value);
    }
    if (typeof namespace === "string") {
      namespace = parse_default(namespace);
    }
    if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
      throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
    }
    let bytes = new Uint8Array(16 + value.length);
    bytes.set(namespace);
    bytes.set(value, namespace.length);
    bytes = hashfunc(bytes);
    bytes[6] = bytes[6] & 15 | version3;
    bytes[8] = bytes[8] & 63 | 128;
    if (buf) {
      offset = offset || 0;
      for (let i2 = 0; i2 < 16; ++i2) {
        buf[offset + i2] = bytes[i2];
      }
      return buf;
    }
    return unsafeStringify(bytes);
  }
  try {
    generateUUID.name = name;
  } catch (err2) {
  }
  generateUUID.DNS = DNS;
  generateUUID.URL = URL2;
  return generateUUID;
}
var DNS, URL2;
var init_v35 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v35.js"() {
    init_stringify();
    init_parse();
    DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
    URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/md5.js
function md5(bytes) {
  if (Array.isArray(bytes)) {
    bytes = Buffer.from(bytes);
  } else if (typeof bytes === "string") {
    bytes = Buffer.from(bytes, "utf8");
  }
  return import_crypto3.default.createHash("md5").update(bytes).digest();
}
var import_crypto3, md5_default;
var init_md5 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/md5.js"() {
    import_crypto3 = __toESM(require("crypto"));
    md5_default = md5;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v3.js
var v3, v3_default;
var init_v3 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v3.js"() {
    init_v35();
    init_md5();
    v3 = v35("v3", 48, md5_default);
    v3_default = v3;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
var import_crypto4, native_default;
var init_native = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js"() {
    import_crypto4 = __toESM(require("crypto"));
    native_default = {
      randomUUID: import_crypto4.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 i2 = 0; i2 < 16; ++i2) {
      buf[offset + i2] = rnds[i2];
    }
    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"() {
    init_native();
    init_rng();
    init_stringify();
    v4_default = v4;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/sha1.js
function sha1(bytes) {
  if (Array.isArray(bytes)) {
    bytes = Buffer.from(bytes);
  } else if (typeof bytes === "string") {
    bytes = Buffer.from(bytes, "utf8");
  }
  return import_crypto5.default.createHash("sha1").update(bytes).digest();
}
var import_crypto5, sha1_default;
var init_sha1 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/sha1.js"() {
    import_crypto5 = __toESM(require("crypto"));
    sha1_default = sha1;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v5.js
var v5, v5_default;
var init_v5 = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v5.js"() {
    init_v35();
    init_sha1();
    v5 = v35("v5", 80, sha1_default);
    v5_default = v5;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/nil.js
var nil_default;
var init_nil = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/nil.js"() {
    nil_default = "00000000-0000-0000-0000-000000000000";
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/version.js
function version(uuid) {
  if (!validate_default(uuid)) {
    throw TypeError("Invalid UUID");
  }
  return parseInt(uuid.slice(14, 15), 16);
}
var version_default;
var init_version = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/version.js"() {
    init_validate();
    version_default = version;
  }
});

// ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js
var esm_node_exports = {};
__export(esm_node_exports, {
  NIL: () => nil_default,
  parse: () => parse_default,
  stringify: () => stringify_default,
  v1: () => v1_default,
  v3: () => v3_default,
  v4: () => v4_default,
  v5: () => v5_default,
  validate: () => validate_default,
  version: () => version_default
});
var init_esm_node = __esm({
  "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js"() {
    init_v1();
    init_v3();
    init_v4();
    init_v5();
    init_nil();
    init_version();
    init_validate();
    init_stringify();
    init_parse();
  }
});

// ../node_modules/.pnpm/@smithy+service-error-classification@3.0.0/node_modules/@smithy/service-error-classification/dist-cjs/index.js
var require_dist_cjs19 = __commonJS({
  "../node_modules/.pnpm/@smithy+service-error-classification@3.0.0/node_modules/@smithy/service-error-classification/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      isClockSkewCorrectedError: () => isClockSkewCorrectedError,
      isClockSkewError: () => isClockSkewError,
      isRetryableByTrait: () => isRetryableByTrait,
      isServerError: () => isServerError,
      isThrottlingError: () => isThrottlingError,
      isTransientError: () => isTransientError
    });
    module2.exports = __toCommonJS2(src_exports);
    var CLOCK_SKEW_ERROR_CODES = [
      "AuthFailure",
      "InvalidSignatureException",
      "RequestExpired",
      "RequestInTheFuture",
      "RequestTimeTooSkewed",
      "SignatureDoesNotMatch"
    ];
    var THROTTLING_ERROR_CODES = [
      "BandwidthLimitExceeded",
      "EC2ThrottledException",
      "LimitExceededException",
      "PriorRequestNotComplete",
      "ProvisionedThroughputExceededException",
      "RequestLimitExceeded",
      "RequestThrottled",
      "RequestThrottledException",
      "SlowDown",
      "ThrottledException",
      "Throttling",
      "ThrottlingException",
      "TooManyRequestsException",
      "TransactionInProgressException"
      // DynamoDB
    ];
    var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
    var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
    var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
    var isRetryableByTrait = /* @__PURE__ */ __name((error2) => error2.$retryable !== void 0, "isRetryableByTrait");
    var isClockSkewError = /* @__PURE__ */ __name((error2) => CLOCK_SKEW_ERROR_CODES.includes(error2.name), "isClockSkewError");
    var isClockSkewCorrectedError = /* @__PURE__ */ __name((error2) => {
      var _a;
      return (_a = error2.$metadata) == null ? void 0 : _a.clockSkewCorrected;
    }, "isClockSkewCorrectedError");
    var isThrottlingError = /* @__PURE__ */ __name((error2) => {
      var _a, _b;
      return ((_a = error2.$metadata) == null ? void 0 : _a.httpStatusCode) === 429 || THROTTLING_ERROR_CODES.includes(error2.name) || ((_b = error2.$retryable) == null ? void 0 : _b.throttling) == true;
    }, "isThrottlingError");
    var isTransientError = /* @__PURE__ */ __name((error2) => {
      var _a;
      return isClockSkewCorrectedError(error2) || TRANSIENT_ERROR_CODES.includes(error2.name) || NODEJS_TIMEOUT_ERROR_CODES.includes((error2 == null ? void 0 : error2.code) || "") || TRANSIENT_ERROR_STATUS_CODES.includes(((_a = error2.$metadata) == null ? void 0 : _a.httpStatusCode) || 0);
    }, "isTransientError");
    var isServerError = /* @__PURE__ */ __name((error2) => {
      var _a;
      if (((_a = error2.$metadata) == null ? void 0 : _a.httpStatusCode) !== void 0) {
        const statusCode = error2.$metadata.httpStatusCode;
        if (500 <= statusCode && statusCode <= 599 && !isTransientError(error2)) {
          return true;
        }
        return false;
      }
      return false;
    }, "isServerError");
  }
});

// ../node_modules/.pnpm/@smithy+util-retry@3.0.0/node_modules/@smithy/util-retry/dist-cjs/index.js
var require_dist_cjs20 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-retry@3.0.0/node_modules/@smithy/util-retry/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AdaptiveRetryStrategy: () => AdaptiveRetryStrategy,
      ConfiguredRetryStrategy: () => ConfiguredRetryStrategy,
      DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS,
      DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE,
      DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE,
      DefaultRateLimiter: () => DefaultRateLimiter,
      INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS,
      INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER,
      MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY,
      NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT,
      REQUEST_HEADER: () => REQUEST_HEADER,
      RETRY_COST: () => RETRY_COST,
      RETRY_MODES: () => RETRY_MODES,
      StandardRetryStrategy: () => StandardRetryStrategy,
      THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE,
      TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST
    });
    module2.exports = __toCommonJS2(src_exports);
    var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => {
      RETRY_MODES2["STANDARD"] = "standard";
      RETRY_MODES2["ADAPTIVE"] = "adaptive";
      return RETRY_MODES2;
    })(RETRY_MODES || {});
    var DEFAULT_MAX_ATTEMPTS = 3;
    var DEFAULT_RETRY_MODE = "standard";
    var import_service_error_classification = require_dist_cjs19();
    var _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 == null ? void 0 : options.beta) ?? 0.7;
        this.minCapacity = (options == null ? void 0 : options.minCapacity) ?? 1;
        this.minFillRate = (options == null ? void 0 : options.minFillRate) ?? 0.5;
        this.scaleConstant = (options == null ? void 0 : options.scaleConstant) ?? 0.4;
        this.smooth = (options == null ? void 0 : 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((resolve2) => setTimeout(resolve2, 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 ((0, import_service_error_classification.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 t2 = this.getCurrentTimeInSeconds();
        const timeBucket = Math.floor(t2 * 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));
      }
    };
    __name(_DefaultRateLimiter, "DefaultRateLimiter");
    var DefaultRateLimiter = _DefaultRateLimiter;
    var DEFAULT_RETRY_DELAY_BASE = 100;
    var MAXIMUM_RETRY_DELAY = 20 * 1e3;
    var THROTTLING_RETRY_DELAY_BASE = 500;
    var INITIAL_RETRY_TOKENS = 500;
    var RETRY_COST = 5;
    var TIMEOUT_RETRY_COST = 10;
    var NO_RETRY_INCREMENT = 1;
    var INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
    var REQUEST_HEADER = "amz-sdk-request";
    var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => {
      let delayBase = DEFAULT_RETRY_DELAY_BASE;
      const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => {
        return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
      }, "computeNextBackoffDelay");
      const setDelayBase = /* @__PURE__ */ __name((delay) => {
        delayBase = delay;
      }, "setDelayBase");
      return {
        computeNextBackoffDelay,
        setDelayBase
      };
    }, "getDefaultRetryBackoffStrategy");
    var createDefaultRetryToken = /* @__PURE__ */ __name(({
      retryDelay,
      retryCount,
      retryCost
    }) => {
      const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount");
      const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay");
      const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost");
      return {
        getRetryCount,
        getRetryDelay,
        getRetryCost
      };
    }, "createDefaultRetryToken");
    var _StandardRetryStrategy = class _StandardRetryStrategy {
      constructor(maxAttempts) {
        this.maxAttempts = maxAttempts;
        this.mode = "standard";
        this.capacity = INITIAL_RETRY_TOKENS;
        this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
        this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      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));
      }
      /**
       * @returns the current available retry capacity.
       *
       * This number decreases when retries are executed and refills when requests or retries succeed.
       */
      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";
      }
    };
    __name(_StandardRetryStrategy, "StandardRetryStrategy");
    var StandardRetryStrategy = _StandardRetryStrategy;
    var _AdaptiveRetryStrategy = class _AdaptiveRetryStrategy {
      constructor(maxAttemptsProvider, options) {
        this.maxAttemptsProvider = maxAttemptsProvider;
        this.mode = "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);
      }
    };
    __name(_AdaptiveRetryStrategy, "AdaptiveRetryStrategy");
    var AdaptiveRetryStrategy = _AdaptiveRetryStrategy;
    var _ConfiguredRetryStrategy = class _ConfiguredRetryStrategy extends StandardRetryStrategy {
      /**
       * @param maxAttempts - the maximum number of retry attempts allowed.
       *                      e.g., if set to 3, then 4 total requests are possible.
       * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt
       *                                  and returns the delay.
       *
       * @example exponential backoff.
       * ```js
       * new Client({
       *   retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2)
       * });
       * ```
       * @example constant delay.
       * ```js
       * new Client({
       *   retryStrategy: new ConfiguredRetryStrategy(3, 2000)
       * });
       * ```
       */
      constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) {
        super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts);
        if (typeof computeNextBackoffDelay === "number") {
          this.computeNextBackoffDelay = () => computeNextBackoffDelay;
        } else {
          this.computeNextBackoffDelay = computeNextBackoffDelay;
        }
      }
      async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
        const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
        token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount());
        return token;
      }
    };
    __name(_ConfiguredRetryStrategy, "ConfiguredRetryStrategy");
    var ConfiguredRetryStrategy = _ConfiguredRetryStrategy;
  }
});

// ../node_modules/.pnpm/@smithy+middleware-stack@3.0.0/node_modules/@smithy/middleware-stack/dist-cjs/index.js
var require_dist_cjs21 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-stack@3.0.0/node_modules/@smithy/middleware-stack/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      constructStack: () => constructStack
    });
    module2.exports = __toCommonJS2(src_exports);
    var getAllAliases = /* @__PURE__ */ __name((name, aliases) => {
      const _aliases = [];
      if (name) {
        _aliases.push(name);
      }
      if (aliases) {
        for (const alias of aliases) {
          _aliases.push(alias);
        }
      }
      return _aliases;
    }, "getAllAliases");
    var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => {
      return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
    }, "getMiddlewareNameWithAliases");
    var constructStack = /* @__PURE__ */ __name(() => {
      let absoluteEntries = [];
      let relativeEntries = [];
      let identifyOnResolve = false;
      const entriesNameSet = /* @__PURE__ */ new Set();
      const sort = /* @__PURE__ */ __name((entries) => entries.sort(
        (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"]
      ), "sort");
      const removeByName = /* @__PURE__ */ __name((toRemove) => {
        let isRemoved = false;
        const filterCb = /* @__PURE__ */ __name((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;
        }, "filterCb");
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      }, "removeByName");
      const removeByReference = /* @__PURE__ */ __name((toRemove) => {
        let isRemoved = false;
        const filterCb = /* @__PURE__ */ __name((entry) => {
          if (entry.middleware === toRemove) {
            isRemoved = true;
            for (const alias of getAllAliases(entry.name, entry.aliases)) {
              entriesNameSet.delete(alias);
            }
            return false;
          }
          return true;
        }, "filterCb");
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      }, "removeByReference");
      const cloneTo = /* @__PURE__ */ __name((toStack) => {
        var _a;
        absoluteEntries.forEach((entry) => {
          toStack.add(entry.middleware, { ...entry });
        });
        relativeEntries.forEach((entry) => {
          toStack.addRelativeTo(entry.middleware, { ...entry });
        });
        (_a = toStack.identifyOnResolve) == null ? void 0 : _a.call(toStack, stack.identifyOnResolve());
        return toStack;
      }, "cloneTo");
      const expandRelativeMiddlewareList = /* @__PURE__ */ __name((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;
      }, "expandRelativeMiddlewareList");
      const getMiddlewareList = /* @__PURE__ */ __name((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;
      }, "getMiddlewareList");
      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) => {
                    var _a;
                    return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === 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) => {
                    var _a;
                    return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === 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 = /* @__PURE__ */ __name((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;
          }, "filterCb");
          absoluteEntries = absoluteEntries.filter(filterCb);
          relativeEntries = relativeEntries.filter(filterCb);
          return isRemoved;
        },
        concat: (from) => {
          var _a;
          const cloned = cloneTo(constructStack());
          cloned.use(from);
          cloned.identifyOnResolve(
            identifyOnResolve || cloned.identifyOnResolve() || (((_a = from.identifyOnResolve) == null ? void 0 : _a.call(from)) ?? 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;
    }, "constructStack");
    var stepWeights = {
      initialize: 5,
      serialize: 4,
      build: 3,
      finalizeRequest: 2,
      deserialize: 1
    };
    var priorityWeights = {
      high: 3,
      normal: 2,
      low: 1
    };
  }
});

// ../node_modules/.pnpm/@smithy+is-array-buffer@3.0.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
var require_dist_cjs22 = __commonJS({
  "../node_modules/.pnpm/@smithy+is-array-buffer@3.0.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      isArrayBuffer: () => isArrayBuffer
    });
    module2.exports = __toCommonJS2(src_exports);
    var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer");
  }
});

// ../node_modules/.pnpm/@smithy+util-buffer-from@3.0.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
var require_dist_cjs23 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-buffer-from@3.0.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromArrayBuffer: () => fromArrayBuffer,
      fromString: () => fromString
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_is_array_buffer = require_dist_cjs22();
    var import_buffer2 = require("buffer");
    var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => {
      if (!(0, import_is_array_buffer.isArrayBuffer)(input)) {
        throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
      }
      return import_buffer2.Buffer.from(input, offset, length);
    }, "fromArrayBuffer");
    var fromString = /* @__PURE__ */ __name((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);
    }, "fromString");
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
var require_fromBase64 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromBase64 = void 0;
    var util_buffer_from_1 = require_dist_cjs23();
    var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
    var fromBase642 = (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 = (0, util_buffer_from_1.fromString)(input, "base64");
      return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
    };
    exports2.fromBase64 = fromBase642;
  }
});

// ../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-cjs/index.js
var require_dist_cjs24 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-utf8@3.0.0/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromUtf8: () => fromUtf8,
      toUint8Array: () => toUint8Array,
      toUtf8: () => toUtf8
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_buffer_from = require_dist_cjs23();
    var fromUtf8 = /* @__PURE__ */ __name((input) => {
      const buf = (0, import_util_buffer_from.fromString)(input, "utf8");
      return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
    }, "fromUtf8");
    var toUint8Array = /* @__PURE__ */ __name((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);
    }, "toUint8Array");
    var toUtf8 = /* @__PURE__ */ __name((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 (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
    }, "toUtf8");
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
var require_toBase64 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-cjs/toBase64.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.toBase64 = void 0;
    var util_buffer_from_1 = require_dist_cjs23();
    var util_utf8_1 = require_dist_cjs24();
    var toBase642 = (_input) => {
      let input;
      if (typeof _input === "string") {
        input = (0, util_utf8_1.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 (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
    };
    exports2.toBase64 = toBase642;
  }
});

// ../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-cjs/index.js
var require_dist_cjs25 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-base64@3.0.0/node_modules/@smithy/util-base64/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    module2.exports = __toCommonJS2(src_exports);
    __reExport(src_exports, require_fromBase64(), module2.exports);
    __reExport(src_exports, require_toBase64(), module2.exports);
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js
var require_getAwsChunkedEncodingStream = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getAwsChunkedEncodingStream = void 0;
    var stream_1 = require("stream");
    var getAwsChunkedEncodingStream2 = (readableStream, options) => {
      const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options;
      const checksumRequired = base64Encoder !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0;
      const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : void 0;
      const awsChunkedEncodingStream = new stream_1.Readable({ read: () => {
      } });
      readableStream.on("data", (data) => {
        const length = bodyLengthChecker(data) || 0;
        awsChunkedEncodingStream.push(`${length.toString(16)}\r
`);
        awsChunkedEncodingStream.push(data);
        awsChunkedEncodingStream.push("\r\n");
      });
      readableStream.on("end", async () => {
        awsChunkedEncodingStream.push(`0\r
`);
        if (checksumRequired) {
          const checksum = base64Encoder(await digest);
          awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r
`);
          awsChunkedEncodingStream.push(`\r
`);
        }
        awsChunkedEncodingStream.push(null);
      });
      return awsChunkedEncodingStream;
    };
    exports2.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream2;
  }
});

// ../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-cjs/index.js
var require_dist_cjs26 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-uri-escape@3.0.0/node_modules/@smithy/util-uri-escape/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      escapeUri: () => escapeUri,
      escapeUriPath: () => escapeUriPath
    });
    module2.exports = __toCommonJS2(src_exports);
    var escapeUri = /* @__PURE__ */ __name((uri) => (
      // AWS percent-encodes some extra non-standard characters in a URI
      encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode)
    ), "escapeUri");
    var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode");
    var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath");
  }
});

// ../node_modules/.pnpm/@smithy+querystring-builder@3.0.0/node_modules/@smithy/querystring-builder/dist-cjs/index.js
var require_dist_cjs27 = __commonJS({
  "../node_modules/.pnpm/@smithy+querystring-builder@3.0.0/node_modules/@smithy/querystring-builder/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      buildQueryString: () => buildQueryString
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_uri_escape = require_dist_cjs26();
    function buildQueryString(query) {
      const parts = [];
      for (let key of Object.keys(query).sort()) {
        const value = query[key];
        key = (0, import_util_uri_escape.escapeUri)(key);
        if (Array.isArray(value)) {
          for (let i2 = 0, iLen = value.length; i2 < iLen; i2++) {
            parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i2])}`);
          }
        } else {
          let qsEntry = key;
          if (value || typeof value === "string") {
            qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`;
          }
          parts.push(qsEntry);
        }
      }
      return parts.join("&");
    }
    __name(buildQueryString, "buildQueryString");
  }
});

// ../node_modules/.pnpm/@smithy+node-http-handler@3.0.0/node_modules/@smithy/node-http-handler/dist-cjs/index.js
var require_dist_cjs28 = __commonJS({
  "../node_modules/.pnpm/@smithy+node-http-handler@3.0.0/node_modules/@smithy/node-http-handler/dist-cjs/index.js"(exports2, module2) {
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT,
      NodeHttp2Handler: () => NodeHttp2Handler,
      NodeHttpHandler: () => NodeHttpHandler,
      streamCollector: () => streamCollector
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http = require_dist_cjs2();
    var import_querystring_builder = require_dist_cjs27();
    var import_http3 = require("http");
    var import_https = require("https");
    var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"];
    var getTransformedHeaders = /* @__PURE__ */ __name((headers) => {
      const transformedHeaders = {};
      for (const name of Object.keys(headers)) {
        const headerValues = headers[name];
        transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues;
      }
      return transformedHeaders;
    }, "getTransformedHeaders");
    var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => {
      if (!timeoutInMs) {
        return;
      }
      const timeoutId = setTimeout(() => {
        request.destroy();
        reject(
          Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
            name: "TimeoutError"
          })
        );
      }, timeoutInMs);
      request.on("socket", (socket) => {
        if (socket.connecting) {
          socket.on("connect", () => {
            clearTimeout(timeoutId);
          });
        } else {
          clearTimeout(timeoutId);
        }
      });
    }, "setConnectionTimeout");
    var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }) => {
      if (keepAlive !== true) {
        return;
      }
      request.on("socket", (socket) => {
        socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
      });
    }, "setSocketKeepAlive");
    var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => {
      request.setTimeout(timeoutInMs, () => {
        request.destroy();
        reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
      });
    }, "setSocketTimeout");
    var import_stream3 = require("stream");
    var MIN_WAIT_TIME = 1e3;
    async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) {
      const headers = request.headers ?? {};
      const expect = headers["Expect"] || headers["expect"];
      let timeoutId = -1;
      let hasError = false;
      if (expect === "100-continue") {
        await Promise.race([
          new Promise((resolve2) => {
            timeoutId = Number(setTimeout(resolve2, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
          }),
          new Promise((resolve2) => {
            httpRequest.on("continue", () => {
              clearTimeout(timeoutId);
              resolve2();
            });
            httpRequest.on("error", () => {
              hasError = true;
              clearTimeout(timeoutId);
              resolve2();
            });
          })
        ]);
      }
      if (!hasError) {
        writeBody(httpRequest, request.body);
      }
    }
    __name(writeRequestBody, "writeRequestBody");
    function writeBody(httpRequest, body) {
      if (body instanceof import_stream3.Readable) {
        body.pipe(httpRequest);
        return;
      }
      if (body) {
        if (Buffer.isBuffer(body) || typeof body === "string") {
          httpRequest.end(body);
          return;
        }
        const uint8 = body;
        if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
          httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
          return;
        }
        httpRequest.end(Buffer.from(body));
        return;
      }
      httpRequest.end();
    }
    __name(writeBody, "writeBody");
    var DEFAULT_REQUEST_TIMEOUT = 0;
    var _NodeHttpHandler = class _NodeHttpHandler2 {
      constructor(options) {
        this.socketWarningTimestamp = 0;
        this.metadata = { handlerProtocol: "http/1.1" };
        this.configProvider = new Promise((resolve2, reject) => {
          if (typeof options === "function") {
            options().then((_options) => {
              resolve2(this.resolveDefaultConfig(_options));
            }).catch(reject);
          } else {
            resolve2(this.resolveDefaultConfig(options));
          }
        });
      }
      /**
       * @returns the input if it is an HttpHandler of any class,
       * or instantiates a new instance of this handler.
       */
      static create(instanceOrOptions) {
        if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
          return instanceOrOptions;
        }
        return new _NodeHttpHandler2(instanceOrOptions);
      }
      /**
       * @internal
       *
       * @param agent - http(s) agent in use by the NodeHttpHandler instance.
       * @returns timestamp of last emitted warning.
       */
      static checkSocketUsage(agent, socketWarningTimestamp) {
        var _a, _b;
        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 = ((_a = sockets[origin]) == null ? void 0 : _a.length) ?? 0;
            const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0;
            if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
              console.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;
      }
      resolveDefaultConfig(options) {
        const { requestTimeout, connectionTimeout, socketTimeout, httpAgent, httpsAgent } = options || {};
        const keepAlive = true;
        const maxSockets = 50;
        return {
          connectionTimeout,
          requestTimeout: requestTimeout ?? socketTimeout,
          httpAgent: (() => {
            if (httpAgent instanceof import_http3.Agent || typeof (httpAgent == null ? void 0 : httpAgent.destroy) === "function") {
              return httpAgent;
            }
            return new import_http3.Agent({ keepAlive, maxSockets, ...httpAgent });
          })(),
          httpsAgent: (() => {
            if (httpsAgent instanceof import_https.Agent || typeof (httpsAgent == null ? void 0 : httpsAgent.destroy) === "function") {
              return httpsAgent;
            }
            return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent });
          })()
        };
      }
      destroy() {
        var _a, _b, _c, _d;
        (_b = (_a = this.config) == null ? void 0 : _a.httpAgent) == null ? void 0 : _b.destroy();
        (_d = (_c = this.config) == null ? void 0 : _c.httpsAgent) == null ? void 0 : _d.destroy();
      }
      async handle(request, { abortSignal } = {}) {
        if (!this.config) {
          this.config = await this.configProvider;
        }
        let socketCheckTimeoutId;
        return new Promise((_resolve, _reject) => {
          let writeRequestBodyPromise = void 0;
          const resolve2 = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            clearTimeout(socketCheckTimeoutId);
            _resolve(arg);
          }, "resolve");
          const reject = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            _reject(arg);
          }, "reject");
          if (!this.config) {
            throw new Error("Node HTTP request handler config is not resolved");
          }
          if (abortSignal == null ? void 0 : abortSignal.aborted) {
            const abortError = new Error("Request aborted");
            abortError.name = "AbortError";
            reject(abortError);
            return;
          }
          const isSSL = request.protocol === "https:";
          const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
          socketCheckTimeoutId = setTimeout(
            () => {
              this.socketWarningTimestamp = _NodeHttpHandler2.checkSocketUsage(agent, this.socketWarningTimestamp);
            },
            this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)
          );
          const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {});
          let auth = void 0;
          if (request.username != null || request.password != null) {
            const username = request.username ?? "";
            const password = request.password ?? "";
            auth = `${username}:${password}`;
          }
          let path4 = request.path;
          if (queryString) {
            path4 += `?${queryString}`;
          }
          if (request.fragment) {
            path4 += `#${request.fragment}`;
          }
          const nodeHttpsOptions = {
            headers: request.headers,
            host: request.hostname,
            method: request.method,
            path: path4,
            port: request.port,
            agent,
            auth
          };
          const requestFunc = isSSL ? import_https.request : import_http3.request;
          const req = requestFunc(nodeHttpsOptions, (res) => {
            const httpResponse = new import_protocol_http.HttpResponse({
              statusCode: res.statusCode || -1,
              reason: res.statusMessage,
              headers: getTransformedHeaders(res.headers),
              body: res
            });
            resolve2({ response: httpResponse });
          });
          req.on("error", (err2) => {
            if (NODEJS_TIMEOUT_ERROR_CODES.includes(err2.code)) {
              reject(Object.assign(err2, { name: "TimeoutError" }));
            } else {
              reject(err2);
            }
          });
          setConnectionTimeout(req, reject, this.config.connectionTimeout);
          setSocketTimeout(req, reject, this.config.requestTimeout);
          if (abortSignal) {
            abortSignal.onabort = () => {
              req.abort();
              const abortError = new Error("Request aborted");
              abortError.name = "AbortError";
              reject(abortError);
            };
          }
          const httpAgent = nodeHttpsOptions.agent;
          if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
            setSocketKeepAlive(req, {
              // @ts-expect-error keepAlive is not public on httpAgent.
              keepAlive: httpAgent.keepAlive,
              // @ts-expect-error keepAliveMsecs is not public on httpAgent.
              keepAliveMsecs: httpAgent.keepAliveMsecs
            });
          }
          writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch(_reject);
        });
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          return {
            ...config,
            [key]: value
          };
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
    };
    __name(_NodeHttpHandler, "NodeHttpHandler");
    var NodeHttpHandler = _NodeHttpHandler;
    var import_http22 = require("http2");
    var import_http23 = __toESM3(require("http2"));
    var _NodeHttp2ConnectionPool = class _NodeHttp2ConnectionPool {
      constructor(sessions) {
        this.sessions = [];
        this.sessions = sessions ?? [];
      }
      poll() {
        if (this.sessions.length > 0) {
          return this.sessions.shift();
        }
      }
      offerLast(session) {
        this.sessions.push(session);
      }
      contains(session) {
        return this.sessions.includes(session);
      }
      remove(session) {
        this.sessions = this.sessions.filter((s2) => s2 !== session);
      }
      [Symbol.iterator]() {
        return this.sessions[Symbol.iterator]();
      }
      destroy(connection) {
        for (const session of this.sessions) {
          if (session === connection) {
            if (!session.destroyed) {
              session.destroy();
            }
          }
        }
      }
    };
    __name(_NodeHttp2ConnectionPool, "NodeHttp2ConnectionPool");
    var NodeHttp2ConnectionPool = _NodeHttp2ConnectionPool;
    var _NodeHttp2ConnectionManager = class _NodeHttp2ConnectionManager {
      constructor(config) {
        this.sessionCache = /* @__PURE__ */ new Map();
        this.config = config;
        if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {
          throw new RangeError("maxConcurrency must be greater than zero.");
        }
      }
      lease(requestContext, connectionConfiguration) {
        const url = this.getUrlString(requestContext);
        const existingPool = this.sessionCache.get(url);
        if (existingPool) {
          const existingSession = existingPool.poll();
          if (existingSession && !this.config.disableConcurrency) {
            return existingSession;
          }
        }
        const session = import_http23.default.connect(url);
        if (this.config.maxConcurrency) {
          session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err2) => {
            if (err2) {
              throw new Error(
                "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString()
              );
            }
          });
        }
        session.unref();
        const destroySessionCb = /* @__PURE__ */ __name(() => {
          session.destroy();
          this.deleteSession(url, session);
        }, "destroySessionCb");
        session.on("goaway", destroySessionCb);
        session.on("error", destroySessionCb);
        session.on("frameError", destroySessionCb);
        session.on("close", () => this.deleteSession(url, session));
        if (connectionConfiguration.requestTimeout) {
          session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb);
        }
        const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool();
        connectionPool.offerLast(session);
        this.sessionCache.set(url, connectionPool);
        return session;
      }
      /**
       * Delete a session from the connection pool.
       * @param authority The authority of the session to delete.
       * @param session The session to delete.
       */
      deleteSession(authority, session) {
        const existingConnectionPool = this.sessionCache.get(authority);
        if (!existingConnectionPool) {
          return;
        }
        if (!existingConnectionPool.contains(session)) {
          return;
        }
        existingConnectionPool.remove(session);
        this.sessionCache.set(authority, existingConnectionPool);
      }
      release(requestContext, session) {
        var _a;
        const cacheKey2 = this.getUrlString(requestContext);
        (_a = this.sessionCache.get(cacheKey2)) == null ? void 0 : _a.offerLast(session);
      }
      destroy() {
        for (const [key, connectionPool] of this.sessionCache) {
          for (const session of connectionPool) {
            if (!session.destroyed) {
              session.destroy();
            }
            connectionPool.remove(session);
          }
          this.sessionCache.delete(key);
        }
      }
      setMaxConcurrentStreams(maxConcurrentStreams) {
        if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {
          throw new RangeError("maxConcurrentStreams must be greater than zero.");
        }
        this.config.maxConcurrency = maxConcurrentStreams;
      }
      setDisableConcurrentStreams(disableConcurrentStreams) {
        this.config.disableConcurrency = disableConcurrentStreams;
      }
      getUrlString(request) {
        return request.destination.toString();
      }
    };
    __name(_NodeHttp2ConnectionManager, "NodeHttp2ConnectionManager");
    var NodeHttp2ConnectionManager = _NodeHttp2ConnectionManager;
    var _NodeHttp2Handler = class _NodeHttp2Handler2 {
      constructor(options) {
        this.metadata = { handlerProtocol: "h2" };
        this.connectionManager = new NodeHttp2ConnectionManager({});
        this.configProvider = new Promise((resolve2, reject) => {
          if (typeof options === "function") {
            options().then((opts) => {
              resolve2(opts || {});
            }).catch(reject);
          } else {
            resolve2(options || {});
          }
        });
      }
      /**
       * @returns the input if it is an HttpHandler of any class,
       * or instantiates a new instance of this handler.
       */
      static create(instanceOrOptions) {
        if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
          return instanceOrOptions;
        }
        return new _NodeHttp2Handler2(instanceOrOptions);
      }
      destroy() {
        this.connectionManager.destroy();
      }
      async handle(request, { abortSignal } = {}) {
        if (!this.config) {
          this.config = await this.configProvider;
          this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false);
          if (this.config.maxConcurrentStreams) {
            this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams);
          }
        }
        const { requestTimeout, disableConcurrentStreams } = this.config;
        return new Promise((_resolve, _reject) => {
          var _a;
          let fulfilled = false;
          let writeRequestBodyPromise = void 0;
          const resolve2 = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            _resolve(arg);
          }, "resolve");
          const reject = /* @__PURE__ */ __name(async (arg) => {
            await writeRequestBodyPromise;
            _reject(arg);
          }, "reject");
          if (abortSignal == null ? void 0 : abortSignal.aborted) {
            fulfilled = true;
            const abortError = new Error("Request aborted");
            abortError.name = "AbortError";
            reject(abortError);
            return;
          }
          const { hostname, method, port, protocol, query } = request;
          let auth = "";
          if (request.username != null || request.password != null) {
            const username = request.username ?? "";
            const password = request.password ?? "";
            auth = `${username}:${password}@`;
          }
          const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`;
          const requestContext = { destination: new URL(authority) };
          const session = this.connectionManager.lease(requestContext, {
            requestTimeout: (_a = this.config) == null ? void 0 : _a.sessionTimeout,
            disableConcurrentStreams: disableConcurrentStreams || false
          });
          const rejectWithDestroy = /* @__PURE__ */ __name((err2) => {
            if (disableConcurrentStreams) {
              this.destroySession(session);
            }
            fulfilled = true;
            reject(err2);
          }, "rejectWithDestroy");
          const queryString = (0, import_querystring_builder.buildQueryString)(query || {});
          let path4 = request.path;
          if (queryString) {
            path4 += `?${queryString}`;
          }
          if (request.fragment) {
            path4 += `#${request.fragment}`;
          }
          const req = session.request({
            ...request.headers,
            [import_http22.constants.HTTP2_HEADER_PATH]: path4,
            [import_http22.constants.HTTP2_HEADER_METHOD]: method
          });
          session.ref();
          req.on("response", (headers) => {
            const httpResponse = new import_protocol_http.HttpResponse({
              statusCode: headers[":status"] || -1,
              headers: getTransformedHeaders(headers),
              body: req
            });
            fulfilled = true;
            resolve2({ response: httpResponse });
            if (disableConcurrentStreams) {
              session.close();
              this.connectionManager.deleteSession(authority, session);
            }
          });
          if (requestTimeout) {
            req.setTimeout(requestTimeout, () => {
              req.close();
              const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`);
              timeoutError.name = "TimeoutError";
              rejectWithDestroy(timeoutError);
            });
          }
          if (abortSignal) {
            abortSignal.onabort = () => {
              req.close();
              const abortError = new Error("Request aborted");
              abortError.name = "AbortError";
              rejectWithDestroy(abortError);
            };
          }
          req.on("frameError", (type, code, id) => {
            rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));
          });
          req.on("error", rejectWithDestroy);
          req.on("aborted", () => {
            rejectWithDestroy(
              new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)
            );
          });
          req.on("close", () => {
            session.unref();
            if (disableConcurrentStreams) {
              session.destroy();
            }
            if (!fulfilled) {
              rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response"));
            }
          });
          writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout);
        });
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          return {
            ...config,
            [key]: value
          };
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
      /**
       * Destroys a session.
       * @param session The session to destroy.
       */
      destroySession(session) {
        if (!session.destroyed) {
          session.destroy();
        }
      }
    };
    __name(_NodeHttp2Handler, "NodeHttp2Handler");
    var NodeHttp2Handler = _NodeHttp2Handler;
    var _Collector = class _Collector extends import_stream3.Writable {
      constructor() {
        super(...arguments);
        this.bufferedBytes = [];
      }
      _write(chunk, encoding, callback) {
        this.bufferedBytes.push(chunk);
        callback();
      }
    };
    __name(_Collector, "Collector");
    var Collector = _Collector;
    var streamCollector = /* @__PURE__ */ __name((stream) => {
      if (isReadableStreamInstance(stream)) {
        return collectReadableStream(stream);
      }
      return new Promise((resolve2, 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));
          resolve2(bytes);
        });
      });
    }, "streamCollector");
    var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance");
    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;
    }
    __name(collectReadableStream, "collectReadableStream");
  }
});

// ../node_modules/.pnpm/@smithy+fetch-http-handler@3.0.1/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js
var require_dist_cjs29 = __commonJS({
  "../node_modules/.pnpm/@smithy+fetch-http-handler@3.0.1/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      FetchHttpHandler: () => FetchHttpHandler,
      keepAliveSupport: () => keepAliveSupport,
      streamCollector: () => streamCollector
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http = require_dist_cjs2();
    var import_querystring_builder = require_dist_cjs27();
    function requestTimeout(timeoutInMs = 0) {
      return new Promise((resolve2, reject) => {
        if (timeoutInMs) {
          setTimeout(() => {
            const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
            timeoutError.name = "TimeoutError";
            reject(timeoutError);
          }, timeoutInMs);
        }
      });
    }
    __name(requestTimeout, "requestTimeout");
    var keepAliveSupport = {
      supported: Boolean(typeof Request !== "undefined" && "keepalive" in new Request("https://[::1]"))
    };
    var _FetchHttpHandler = class _FetchHttpHandler2 {
      /**
       * @returns the input if it is an HttpHandler of any class,
       * or instantiates a new instance of this handler.
       */
      static create(instanceOrOptions) {
        if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
          return instanceOrOptions;
        }
        return new _FetchHttpHandler2(instanceOrOptions);
      }
      constructor(options) {
        if (typeof options === "function") {
          this.configProvider = options().then((opts) => opts || {});
        } else {
          this.config = options ?? {};
          this.configProvider = Promise.resolve(this.config);
        }
      }
      destroy() {
      }
      async handle(request, { abortSignal } = {}) {
        if (!this.config) {
          this.config = await this.configProvider;
        }
        const requestTimeoutInMs = this.config.requestTimeout;
        const keepAlive = this.config.keepAlive === true;
        if (abortSignal == null ? void 0 : abortSignal.aborted) {
          const abortError = new Error("Request aborted");
          abortError.name = "AbortError";
          return Promise.reject(abortError);
        }
        let path4 = request.path;
        const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {});
        if (queryString) {
          path4 += `?${queryString}`;
        }
        if (request.fragment) {
          path4 += `#${request.fragment}`;
        }
        let auth = "";
        if (request.username != null || request.password != null) {
          const username = request.username ?? "";
          const password = request.password ?? "";
          auth = `${username}:${password}@`;
        }
        const { port, method } = request;
        const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path4}`;
        const body = method === "GET" || method === "HEAD" ? void 0 : request.body;
        const requestOptions = {
          body,
          headers: new Headers(request.headers),
          method
        };
        if (body) {
          requestOptions.duplex = "half";
        }
        if (typeof AbortController !== "undefined") {
          requestOptions.signal = abortSignal;
        }
        if (keepAliveSupport.supported) {
          requestOptions.keepalive = keepAlive;
        }
        const fetchRequest = new Request(url, requestOptions);
        const raceOfPromises = [
          fetch(fetchRequest).then((response) => {
            const fetchHeaders = response.headers;
            const transformedHeaders = {};
            for (const pair of fetchHeaders.entries()) {
              transformedHeaders[pair[0]] = pair[1];
            }
            const hasReadableStream = response.body != void 0;
            if (!hasReadableStream) {
              return response.blob().then((body2) => ({
                response: new import_protocol_http.HttpResponse({
                  headers: transformedHeaders,
                  reason: response.statusText,
                  statusCode: response.status,
                  body: body2
                })
              }));
            }
            return {
              response: new import_protocol_http.HttpResponse({
                headers: transformedHeaders,
                reason: response.statusText,
                statusCode: response.status,
                body: response.body
              })
            };
          }),
          requestTimeout(requestTimeoutInMs)
        ];
        if (abortSignal) {
          raceOfPromises.push(
            new Promise((resolve2, reject) => {
              abortSignal.onabort = () => {
                const abortError = new Error("Request aborted");
                abortError.name = "AbortError";
                reject(abortError);
              };
            })
          );
        }
        return Promise.race(raceOfPromises);
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          config[key] = value;
          return config;
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
    };
    __name(_FetchHttpHandler, "FetchHttpHandler");
    var FetchHttpHandler = _FetchHttpHandler;
    var import_util_base64 = require_dist_cjs25();
    var streamCollector = /* @__PURE__ */ __name((stream) => {
      if (typeof Blob === "function" && stream instanceof Blob) {
        return collectBlob(stream);
      }
      return collectStream(stream);
    }, "streamCollector");
    async function collectBlob(blob) {
      const base64 = await readToBase64(blob);
      const arrayBuffer = (0, import_util_base64.fromBase64)(base64);
      return new Uint8Array(arrayBuffer);
    }
    __name(collectBlob, "collectBlob");
    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;
    }
    __name(collectStream, "collectStream");
    function readToBase64(blob) {
      return new Promise((resolve2, 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;
          resolve2(result.substring(dataOffset));
        };
        reader.onabort = () => reject(new Error("Read aborted"));
        reader.onerror = () => reject(reader.error);
        reader.readAsDataURL(blob);
      });
    }
    __name(readToBase64, "readToBase64");
  }
});

// ../node_modules/.pnpm/@smithy+util-hex-encoding@3.0.0/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js
var require_dist_cjs30 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-hex-encoding@3.0.0/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromHex: () => fromHex,
      toHex: () => toHex
    });
    module2.exports = __toCommonJS2(src_exports);
    var SHORT_TO_HEX = {};
    var HEX_TO_SHORT = {};
    for (let i2 = 0; i2 < 256; i2++) {
      let encodedByte = i2.toString(16).toLowerCase();
      if (encodedByte.length === 1) {
        encodedByte = `0${encodedByte}`;
      }
      SHORT_TO_HEX[i2] = encodedByte;
      HEX_TO_SHORT[encodedByte] = i2;
    }
    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 i2 = 0; i2 < encoded.length; i2 += 2) {
        const encodedByte = encoded.slice(i2, i2 + 2).toLowerCase();
        if (encodedByte in HEX_TO_SHORT) {
          out[i2 / 2] = HEX_TO_SHORT[encodedByte];
        } else {
          throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
        }
      }
      return out;
    }
    __name(fromHex, "fromHex");
    function toHex(bytes) {
      let out = "";
      for (let i2 = 0; i2 < bytes.byteLength; i2++) {
        out += SHORT_TO_HEX[bytes[i2]];
      }
      return out;
    }
    __name(toHex, "toHex");
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js
var require_sdk_stream_mixin_browser = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sdkStreamMixin = void 0;
    var fetch_http_handler_1 = require_dist_cjs29();
    var util_base64_1 = require_dist_cjs25();
    var util_hex_encoding_1 = require_dist_cjs30();
    var util_utf8_1 = require_dist_cjs24();
    var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
    var sdkStreamMixin2 = (stream) => {
      var _a, _b;
      if (!isBlobInstance(stream) && !isReadableStreamInstance(stream)) {
        const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.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 (0, fetch_http_handler_1.streamCollector)(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 (0, util_base64_1.toBase64)(buf);
          } else if (encoding === "hex") {
            return (0, util_hex_encoding_1.toHex)(buf);
          } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
            return (0, util_utf8_1.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 (isReadableStreamInstance(stream)) {
            return stream;
          } else {
            throw new Error(`Cannot transform payload to web stream, got ${stream}`);
          }
        }
      });
    };
    exports2.sdkStreamMixin = sdkStreamMixin2;
    var isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob;
    var isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js
var require_sdk_stream_mixin = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sdkStreamMixin = void 0;
    var node_http_handler_1 = require_dist_cjs28();
    var util_buffer_from_1 = require_dist_cjs23();
    var stream_1 = require("stream");
    var util_1 = require("util");
    var sdk_stream_mixin_browser_1 = require_sdk_stream_mixin_browser();
    var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
    var sdkStreamMixin2 = (stream) => {
      var _a, _b;
      if (!(stream instanceof stream_1.Readable)) {
        try {
          return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream);
        } catch (e2) {
          const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.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_TRANSFORMED);
        }
        transformed = true;
        return await (0, node_http_handler_1.streamCollector)(stream);
      };
      return Object.assign(stream, {
        transformToByteArray,
        transformToString: async (encoding) => {
          const buf = await transformToByteArray();
          if (encoding === void 0 || Buffer.isEncoding(encoding)) {
            return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);
          } else {
            const decoder = new util_1.TextDecoder(encoding);
            return decoder.decode(buf);
          }
        },
        transformToWebStream: () => {
          if (transformed) {
            throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
          }
          if (stream.readableFlowing !== null) {
            throw new Error("The stream has been consumed by other callbacks.");
          }
          if (typeof stream_1.Readable.toWeb !== "function") {
            throw new Error("Readable.toWeb() is not supported. Please make sure you are using Node.js >= 17.0.0, or polyfill is available.");
          }
          transformed = true;
          return stream_1.Readable.toWeb(stream);
        }
      });
    };
    exports2.sdkStreamMixin = sdkStreamMixin2;
  }
});

// ../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/index.js
var require_dist_cjs31 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-stream@3.0.1/node_modules/@smithy/util-stream/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_base64 = require_dist_cjs25();
    var import_util_utf8 = require_dist_cjs24();
    function transformToString(payload, encoding = "utf-8") {
      if (encoding === "base64") {
        return (0, import_util_base64.toBase64)(payload);
      }
      return (0, import_util_utf8.toUtf8)(payload);
    }
    __name(transformToString, "transformToString");
    function transformFromString(str, encoding) {
      if (encoding === "base64") {
        return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str));
      }
      return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str));
    }
    __name(transformFromString, "transformFromString");
    var _Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter2 extends Uint8Array {
      /**
       * @param source - such as a string or Stream.
       * @returns a new Uint8ArrayBlobAdapter extending 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.`);
        }
      }
      /**
       * @param source - Uint8Array to be mutated.
       * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter.
       */
      static mutate(source) {
        Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter2.prototype);
        return source;
      }
      /**
       * @param encoding - default 'utf-8'.
       * @returns the blob as string.
       */
      transformToString(encoding = "utf-8") {
        return transformToString(this, encoding);
      }
    };
    __name(_Uint8ArrayBlobAdapter, "Uint8ArrayBlobAdapter");
    var Uint8ArrayBlobAdapter = _Uint8ArrayBlobAdapter;
    __reExport(src_exports, require_getAwsChunkedEncodingStream(), module2.exports);
    __reExport(src_exports, require_sdk_stream_mixin(), module2.exports);
  }
});

// ../node_modules/.pnpm/@smithy+smithy-client@3.0.1/node_modules/@smithy/smithy-client/dist-cjs/index.js
var require_dist_cjs32 = __commonJS({
  "../node_modules/.pnpm/@smithy+smithy-client@3.0.1/node_modules/@smithy/smithy-client/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Client: () => Client,
      Command: () => Command,
      LazyJsonString: () => LazyJsonString,
      NoOpLogger: () => NoOpLogger,
      SENSITIVE_STRING: () => SENSITIVE_STRING,
      ServiceException: () => ServiceException,
      StringWrapper: () => StringWrapper,
      _json: () => _json,
      collectBody: () => collectBody,
      convertMap: () => convertMap,
      createAggregatedClient: () => createAggregatedClient,
      dateToUtcString: () => dateToUtcString,
      decorateServiceException: () => decorateServiceException,
      emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion,
      expectBoolean: () => expectBoolean,
      expectByte: () => expectByte,
      expectFloat32: () => expectFloat32,
      expectInt: () => expectInt,
      expectInt32: () => expectInt32,
      expectLong: () => expectLong,
      expectNonNull: () => expectNonNull,
      expectNumber: () => expectNumber,
      expectObject: () => expectObject,
      expectShort: () => expectShort,
      expectString: () => expectString,
      expectUnion: () => expectUnion,
      extendedEncodeURIComponent: () => extendedEncodeURIComponent,
      getArrayIfSingleItem: () => getArrayIfSingleItem,
      getDefaultClientConfiguration: () => getDefaultClientConfiguration,
      getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration,
      getValueFromTextNode: () => getValueFromTextNode,
      handleFloat: () => handleFloat,
      limitedParseDouble: () => limitedParseDouble,
      limitedParseFloat: () => limitedParseFloat,
      limitedParseFloat32: () => limitedParseFloat32,
      loadConfigsForDefaultMode: () => loadConfigsForDefaultMode,
      logger: () => logger,
      map: () => map,
      parseBoolean: () => parseBoolean,
      parseEpochTimestamp: () => parseEpochTimestamp,
      parseRfc3339DateTime: () => parseRfc3339DateTime,
      parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset,
      parseRfc7231DateTime: () => parseRfc7231DateTime,
      resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig,
      resolvedPath: () => resolvedPath,
      serializeFloat: () => serializeFloat,
      splitEvery: () => splitEvery,
      strictParseByte: () => strictParseByte,
      strictParseDouble: () => strictParseDouble,
      strictParseFloat: () => strictParseFloat,
      strictParseFloat32: () => strictParseFloat32,
      strictParseInt: () => strictParseInt,
      strictParseInt32: () => strictParseInt32,
      strictParseLong: () => strictParseLong,
      strictParseShort: () => strictParseShort,
      take: () => take,
      throwDefaultError: () => throwDefaultError,
      withBaseException: () => withBaseException
    });
    module2.exports = __toCommonJS2(src_exports);
    var _NoOpLogger = class _NoOpLogger {
      trace() {
      }
      debug() {
      }
      info() {
      }
      warn() {
      }
      error() {
      }
    };
    __name(_NoOpLogger, "NoOpLogger");
    var NoOpLogger = _NoOpLogger;
    var import_middleware_stack = require_dist_cjs21();
    var _Client = class _Client {
      constructor(config) {
        this.middlewareStack = (0, import_middleware_stack.constructStack)();
        this.config = config;
      }
      send(command, optionsOrCb, cb) {
        const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
        const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
        const handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
        if (callback) {
          handler(command).then(
            (result) => callback(null, result.output),
            (err2) => callback(err2)
          ).catch(
            // prevent any errors thrown in the callback from triggering an
            // unhandled promise rejection
            () => {
            }
          );
        } else {
          return handler(command).then((result) => result.output);
        }
      }
      destroy() {
        if (this.config.requestHandler.destroy)
          this.config.requestHandler.destroy();
      }
    };
    __name(_Client, "Client");
    var Client = _Client;
    var import_util_stream = require_dist_cjs31();
    var collectBody = /* @__PURE__ */ __name(async (streamBody = new Uint8Array(), context) => {
      if (streamBody instanceof Uint8Array) {
        return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody);
      }
      if (!streamBody) {
        return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array());
      }
      const fromContext = context.streamCollector(streamBody);
      return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext);
    }, "collectBody");
    var import_types = require_dist_cjs();
    var _Command = class _Command {
      constructor() {
        this.middlewareStack = (0, import_middleware_stack.constructStack)();
      }
      /**
       * Factory for Command ClassBuilder.
       * @internal
       */
      static classBuilder() {
        return new ClassBuilder();
      }
      /**
       * @internal
       */
      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,
          [import_types.SMITHY_CONTEXT_KEY]: {
            ...smithyContext
          },
          ...additionalContext
        };
        const { requestHandler } = configuration;
        return stack.resolve(
          (request) => requestHandler.handle(request.request, options || {}),
          handlerExecutionContext
        );
      }
    };
    __name(_Command, "Command");
    var Command = _Command;
    var _ClassBuilder = class _ClassBuilder {
      constructor() {
        this._init = () => {
        };
        this._ep = {};
        this._middlewareFn = () => [];
        this._commandName = "";
        this._clientName = "";
        this._additionalContext = {};
        this._smithyContext = {};
        this._inputFilterSensitiveLog = (_2) => _2;
        this._outputFilterSensitiveLog = (_2) => _2;
        this._serializer = null;
        this._deserializer = null;
      }
      /**
       * Optional init callback.
       */
      init(cb) {
        this._init = cb;
      }
      /**
       * Set the endpoint parameter instructions.
       */
      ep(endpointParameterInstructions) {
        this._ep = endpointParameterInstructions;
        return this;
      }
      /**
       * Add any number of middleware.
       */
      m(middlewareSupplier) {
        this._middlewareFn = middlewareSupplier;
        return this;
      }
      /**
       * Set the initial handler execution context Smithy field.
       */
      s(service, operation, smithyContext = {}) {
        this._smithyContext = {
          service,
          operation,
          ...smithyContext
        };
        return this;
      }
      /**
       * Set the initial handler execution context.
       */
      c(additionalContext = {}) {
        this._additionalContext = additionalContext;
        return this;
      }
      /**
       * Set constant string identifiers for the operation.
       */
      n(clientName, commandName) {
        this._clientName = clientName;
        this._commandName = commandName;
        return this;
      }
      /**
       * Set the input and output sensistive log filters.
       */
      f(inputFilter = (_2) => _2, outputFilter = (_2) => _2) {
        this._inputFilterSensitiveLog = inputFilter;
        this._outputFilterSensitiveLog = outputFilter;
        return this;
      }
      /**
       * Sets the serializer.
       */
      ser(serializer) {
        this._serializer = serializer;
        return this;
      }
      /**
       * Sets the deserializer.
       */
      de(deserializer) {
        this._deserializer = deserializer;
        return this;
      }
      /**
       * @returns a Command class with the classBuilder properties.
       */
      build() {
        var _a;
        const closure = this;
        let CommandRef;
        return CommandRef = (_a = class extends Command {
          /**
           * @public
           */
          constructor(...[input]) {
            super();
            this.serialize = closure._serializer;
            this.deserialize = closure._deserializer;
            this.input = input ?? {};
            closure._init(this);
          }
          /**
           * @public
           */
          static getEndpointParameterInstructions() {
            return closure._ep;
          }
          /**
           * @internal
           */
          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
            });
          }
        }, __name(_a, "CommandRef"), _a);
      }
    };
    __name(_ClassBuilder, "ClassBuilder");
    var ClassBuilder = _ClassBuilder;
    var SENSITIVE_STRING = "***SensitiveInformation***";
    var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => {
      for (const command of Object.keys(commands)) {
        const CommandCtor = commands[command];
        const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) {
          const command22 = new CommandCtor(args);
          if (typeof optionsOrCb === "function") {
            this.send(command22, optionsOrCb);
          } else if (typeof cb === "function") {
            if (typeof optionsOrCb !== "object")
              throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
            this.send(command22, optionsOrCb || {}, cb);
          } else {
            return this.send(command22, optionsOrCb);
          }
        }, "methodImpl");
        const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
        Client2.prototype[methodName] = methodImpl;
      }
    }, "createAggregatedClient");
    var parseBoolean = /* @__PURE__ */ __name((value) => {
      switch (value) {
        case "true":
          return true;
        case "false":
          return false;
        default:
          throw new Error(`Unable to parse boolean value "${value}"`);
      }
    }, "parseBoolean");
    var expectBoolean = /* @__PURE__ */ __name((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}`);
    }, "expectBoolean");
    var expectNumber = /* @__PURE__ */ __name((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}`);
    }, "expectNumber");
    var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
    var expectFloat32 = /* @__PURE__ */ __name((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;
    }, "expectFloat32");
    var expectLong = /* @__PURE__ */ __name((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}`);
    }, "expectLong");
    var expectInt = expectLong;
    var expectInt32 = /* @__PURE__ */ __name((value) => expectSizedInt(value, 32), "expectInt32");
    var expectShort = /* @__PURE__ */ __name((value) => expectSizedInt(value, 16), "expectShort");
    var expectByte = /* @__PURE__ */ __name((value) => expectSizedInt(value, 8), "expectByte");
    var expectSizedInt = /* @__PURE__ */ __name((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;
    }, "expectSizedInt");
    var castInt = /* @__PURE__ */ __name((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];
      }
    }, "castInt");
    var expectNonNull = /* @__PURE__ */ __name((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;
    }, "expectNonNull");
    var expectObject = /* @__PURE__ */ __name((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}`);
    }, "expectObject");
    var expectString = /* @__PURE__ */ __name((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}`);
    }, "expectString");
    var expectUnion = /* @__PURE__ */ __name((value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      const asObject = expectObject(value);
      const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k);
      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;
    }, "expectUnion");
    var strictParseDouble = /* @__PURE__ */ __name((value) => {
      if (typeof value == "string") {
        return expectNumber(parseNumber(value));
      }
      return expectNumber(value);
    }, "strictParseDouble");
    var strictParseFloat = strictParseDouble;
    var strictParseFloat32 = /* @__PURE__ */ __name((value) => {
      if (typeof value == "string") {
        return expectFloat32(parseNumber(value));
      }
      return expectFloat32(value);
    }, "strictParseFloat32");
    var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
    var parseNumber = /* @__PURE__ */ __name((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);
    }, "parseNumber");
    var limitedParseDouble = /* @__PURE__ */ __name((value) => {
      if (typeof value == "string") {
        return parseFloatString(value);
      }
      return expectNumber(value);
    }, "limitedParseDouble");
    var handleFloat = limitedParseDouble;
    var limitedParseFloat = limitedParseDouble;
    var limitedParseFloat32 = /* @__PURE__ */ __name((value) => {
      if (typeof value == "string") {
        return parseFloatString(value);
      }
      return expectFloat32(value);
    }, "limitedParseFloat32");
    var parseFloatString = /* @__PURE__ */ __name((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}`);
      }
    }, "parseFloatString");
    var strictParseLong = /* @__PURE__ */ __name((value) => {
      if (typeof value === "string") {
        return expectLong(parseNumber(value));
      }
      return expectLong(value);
    }, "strictParseLong");
    var strictParseInt = strictParseLong;
    var strictParseInt32 = /* @__PURE__ */ __name((value) => {
      if (typeof value === "string") {
        return expectInt32(parseNumber(value));
      }
      return expectInt32(value);
    }, "strictParseInt32");
    var strictParseShort = /* @__PURE__ */ __name((value) => {
      if (typeof value === "string") {
        return expectShort(parseNumber(value));
      }
      return expectShort(value);
    }, "strictParseShort");
    var strictParseByte = /* @__PURE__ */ __name((value) => {
      if (typeof value === "string") {
        return expectByte(parseNumber(value));
      }
      return expectByte(value);
    }, "strictParseByte");
    var stackTraceWarning = /* @__PURE__ */ __name((message) => {
      return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s2) => !s2.includes("stackTraceWarning")).join("\n");
    }, "stackTraceWarning");
    var logger = {
      warn: console.warn
    };
    var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    function dateToUtcString(date) {
      const year = date.getUTCFullYear();
      const month = date.getUTCMonth();
      const dayOfWeek = date.getUTCDay();
      const dayOfMonthInt = date.getUTCDate();
      const hoursInt = date.getUTCHours();
      const minutesInt = date.getUTCMinutes();
      const secondsInt = date.getUTCSeconds();
      const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`;
      const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`;
      const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`;
      const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`;
      return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`;
    }
    __name(dateToUtcString, "dateToUtcString");
    var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
    var parseRfc3339DateTime = /* @__PURE__ */ __name((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 [_2, 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 });
    }, "parseRfc3339DateTime");
    var RFC3339_WITH_OFFSET = new RegExp(
      /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/
    );
    var parseRfc3339DateTimeWithOffset = /* @__PURE__ */ __name((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 [_2, 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;
    }, "parseRfc3339DateTimeWithOffset");
    var 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$/
    );
    var 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$/
    );
    var 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})$/
    );
    var parseRfc7231DateTime = /* @__PURE__ */ __name((value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-7231 date-times must be expressed as strings");
      }
      let match2 = IMF_FIXDATE.exec(value);
      if (match2) {
        const [_2, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
        return buildDate(
          strictParseShort(stripLeadingZeroes(yearStr)),
          parseMonthByShortName(monthStr),
          parseDateValue(dayStr, "day", 1, 31),
          { hours, minutes, seconds, fractionalMilliseconds }
        );
      }
      match2 = RFC_850_DATE.exec(value);
      if (match2) {
        const [_2, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
        return adjustRfc850Year(
          buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), {
            hours,
            minutes,
            seconds,
            fractionalMilliseconds
          })
        );
      }
      match2 = ASC_TIME.exec(value);
      if (match2) {
        const [_2, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match2;
        return buildDate(
          strictParseShort(stripLeadingZeroes(yearStr)),
          parseMonthByShortName(monthStr),
          parseDateValue(dayStr.trimLeft(), "day", 1, 31),
          { hours, minutes, seconds, fractionalMilliseconds }
        );
      }
      throw new TypeError("Invalid RFC-7231 date-time value");
    }, "parseRfc7231DateTime");
    var parseEpochTimestamp = /* @__PURE__ */ __name((value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      let valueAsDouble;
      if (typeof value === "number") {
        valueAsDouble = value;
      } else if (typeof value === "string") {
        valueAsDouble = strictParseDouble(value);
      } else {
        throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");
      }
      if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {
        throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");
      }
      return new Date(Math.round(valueAsDouble * 1e3));
    }, "parseEpochTimestamp");
    var buildDate = /* @__PURE__ */ __name((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),
          // seconds can go up to 60 for leap seconds
          parseDateValue(time.seconds, "seconds", 0, 60),
          parseMilliseconds(time.fractionalMilliseconds)
        )
      );
    }, "buildDate");
    var parseTwoDigitYear = /* @__PURE__ */ __name((value) => {
      const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear();
      const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value));
      if (valueInThisCentury < thisYear) {
        return valueInThisCentury + 100;
      }
      return valueInThisCentury;
    }, "parseTwoDigitYear");
    var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
    var adjustRfc850Year = /* @__PURE__ */ __name((input) => {
      if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) {
        return new Date(
          Date.UTC(
            input.getUTCFullYear() - 100,
            input.getUTCMonth(),
            input.getUTCDate(),
            input.getUTCHours(),
            input.getUTCMinutes(),
            input.getUTCSeconds(),
            input.getUTCMilliseconds()
          )
        );
      }
      return input;
    }, "adjustRfc850Year");
    var parseMonthByShortName = /* @__PURE__ */ __name((value) => {
      const monthIdx = MONTHS.indexOf(value);
      if (monthIdx < 0) {
        throw new TypeError(`Invalid month: ${value}`);
      }
      return monthIdx + 1;
    }, "parseMonthByShortName");
    var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var validateDayOfMonth = /* @__PURE__ */ __name((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}`);
      }
    }, "validateDayOfMonth");
    var isLeapYear = /* @__PURE__ */ __name((year) => {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }, "isLeapYear");
    var parseDateValue = /* @__PURE__ */ __name((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;
    }, "parseDateValue");
    var parseMilliseconds = /* @__PURE__ */ __name((value) => {
      if (value === null || value === void 0) {
        return 0;
      }
      return strictParseFloat32("0." + value) * 1e3;
    }, "parseMilliseconds");
    var parseOffsetToMilliseconds = /* @__PURE__ */ __name((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;
    }, "parseOffsetToMilliseconds");
    var stripLeadingZeroes = /* @__PURE__ */ __name((value) => {
      let idx = 0;
      while (idx < value.length - 1 && value.charAt(idx) === "0") {
        idx++;
      }
      if (idx === 0) {
        return value;
      }
      return value.slice(idx);
    }, "stripLeadingZeroes");
    var _ServiceException = class _ServiceException2 extends Error {
      constructor(options) {
        super(options.message);
        Object.setPrototypeOf(this, _ServiceException2.prototype);
        this.name = options.name;
        this.$fault = options.$fault;
        this.$metadata = options.$metadata;
      }
    };
    __name(_ServiceException, "ServiceException");
    var ServiceException = _ServiceException;
    var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => {
      Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => {
        if (exception[k] == void 0 || exception[k] === "") {
          exception[k] = v;
        }
      });
      const message = exception.message || exception.Message || "UnknownError";
      exception.message = message;
      delete exception.Message;
      return exception;
    }, "decorateServiceException");
    var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => {
      const $metadata = deserializeMetadata(output);
      const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
      const response = new exceptionCtor({
        name: (parsedBody == null ? void 0 : parsedBody.code) || (parsedBody == null ? void 0 : parsedBody.Code) || errorCode || statusCode || "UnknownError",
        $fault: "client",
        $metadata
      });
      throw decorateServiceException(response, parsedBody);
    }, "throwDefaultError");
    var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => {
      return ({ output, parsedBody, errorCode }) => {
        throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
      };
    }, "withBaseException");
    var deserializeMetadata = /* @__PURE__ */ __name((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"]
    }), "deserializeMetadata");
    var loadConfigsForDefaultMode = /* @__PURE__ */ __name((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 {};
      }
    }, "loadConfigsForDefaultMode");
    var warningEmitted = false;
    var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version3) => {
      if (version3 && !warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 16) {
        warningEmitted = true;
      }
    }, "emitWarningIfUnsupportedVersion");
    var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const checksumAlgorithms = [];
      for (const id in import_types.AlgorithmId) {
        const algorithmId = import_types.AlgorithmId[id];
        if (runtimeConfig[algorithmId] === void 0) {
          continue;
        }
        checksumAlgorithms.push({
          algorithmId: () => algorithmId,
          checksumConstructor: () => runtimeConfig[algorithmId]
        });
      }
      return {
        _checksumAlgorithms: checksumAlgorithms,
        addChecksumAlgorithm(algo) {
          this._checksumAlgorithms.push(algo);
        },
        checksumAlgorithms() {
          return this._checksumAlgorithms;
        }
      };
    }, "getChecksumConfiguration");
    var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => {
      const runtimeConfig = {};
      clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
        runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
      });
      return runtimeConfig;
    }, "resolveChecksumRuntimeConfig");
    var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      let _retryStrategy = runtimeConfig.retryStrategy;
      return {
        setRetryStrategy(retryStrategy) {
          _retryStrategy = retryStrategy;
        },
        retryStrategy() {
          return _retryStrategy;
        }
      };
    }, "getRetryConfiguration");
    var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => {
      const runtimeConfig = {};
      runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
      return runtimeConfig;
    }, "resolveRetryRuntimeConfig");
    var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      return {
        ...getChecksumConfiguration(runtimeConfig),
        ...getRetryConfiguration(runtimeConfig)
      };
    }, "getDefaultExtensionConfiguration");
    var getDefaultClientConfiguration = getDefaultExtensionConfiguration;
    var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => {
      return {
        ...resolveChecksumRuntimeConfig(config),
        ...resolveRetryRuntimeConfig(config)
      };
    }, "resolveDefaultRuntimeConfig");
    function extendedEncodeURIComponent(str) {
      return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
        return "%" + c.charCodeAt(0).toString(16).toUpperCase();
      });
    }
    __name(extendedEncodeURIComponent, "extendedEncodeURIComponent");
    var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem");
    var getValueFromTextNode = /* @__PURE__ */ __name((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;
    }, "getValueFromTextNode");
    var StringWrapper = /* @__PURE__ */ __name(function() {
      const Class = Object.getPrototypeOf(this).constructor;
      const Constructor = Function.bind.apply(String, [null, ...arguments]);
      const instance = new Constructor();
      Object.setPrototypeOf(instance, Class.prototype);
      return instance;
    }, "StringWrapper");
    StringWrapper.prototype = Object.create(String.prototype, {
      constructor: {
        value: StringWrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    Object.setPrototypeOf(StringWrapper, String);
    var _LazyJsonString = class _LazyJsonString2 extends StringWrapper {
      deserializeJSON() {
        return JSON.parse(super.toString());
      }
      toJSON() {
        return super.toString();
      }
      static fromObject(object) {
        if (object instanceof _LazyJsonString2) {
          return object;
        } else if (object instanceof String || typeof object === "string") {
          return new _LazyJsonString2(object);
        }
        return new _LazyJsonString2(JSON.stringify(object));
      }
    };
    __name(_LazyJsonString, "LazyJsonString");
    var LazyJsonString = _LazyJsonString;
    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;
    }
    __name(map, "map");
    var convertMap = /* @__PURE__ */ __name((target) => {
      const output = {};
      for (const [k, v] of Object.entries(target || {})) {
        output[k] = [, v];
      }
      return output;
    }, "convertMap");
    var take = /* @__PURE__ */ __name((source, instructions) => {
      const out = {};
      for (const key in instructions) {
        applyInstruction(out, source, instructions, key);
      }
      return out;
    }, "take");
    var mapWithFilter = /* @__PURE__ */ __name((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;
          },
          {}
        )
      );
    }, "mapWithFilter");
    var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => {
      if (source !== null) {
        let instruction = instructions[targetKey];
        if (typeof instruction === "function") {
          instruction = [, instruction];
        }
        const [filter22 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
        if (typeof filter22 === "function" && filter22(source[sourceKey]) || typeof filter22 !== "function" && !!filter22) {
          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;
        }
      }
    }, "applyInstruction");
    var nonNullish = /* @__PURE__ */ __name((_2) => _2 != null, "nonNullish");
    var pass = /* @__PURE__ */ __name((_2) => _2, "pass");
    var resolvedPath = /* @__PURE__ */ __name((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;
    }, "resolvedPath");
    var serializeFloat = /* @__PURE__ */ __name((value) => {
      if (value !== value) {
        return "NaN";
      }
      switch (value) {
        case Infinity:
          return "Infinity";
        case -Infinity:
          return "-Infinity";
        default:
          return value;
      }
    }, "serializeFloat");
    var _json = /* @__PURE__ */ __name((obj) => {
      if (obj == null) {
        return {};
      }
      if (Array.isArray(obj)) {
        return obj.filter((_2) => _2 != 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;
    }, "_json");
    function splitEvery(value, delimiter, numDelimiters) {
      if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) {
        throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery.");
      }
      const segments = value.split(delimiter);
      if (numDelimiters === 1) {
        return segments;
      }
      const compoundSegments = [];
      let currentSegment = "";
      for (let i2 = 0; i2 < segments.length; i2++) {
        if (currentSegment === "") {
          currentSegment = segments[i2];
        } else {
          currentSegment += delimiter + segments[i2];
        }
        if ((i2 + 1) % numDelimiters === 0) {
          compoundSegments.push(currentSegment);
          currentSegment = "";
        }
      }
      if (currentSegment !== "") {
        compoundSegments.push(currentSegment);
      }
      return compoundSegments;
    }
    __name(splitEvery, "splitEvery");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@3.0.1/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js
var require_isStreamingPayload = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-retry@3.0.1/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isStreamingPayload = void 0;
    var stream_1 = require("stream");
    var isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream;
    exports2.isStreamingPayload = isStreamingPayload;
  }
});

// ../node_modules/.pnpm/@smithy+middleware-retry@3.0.1/node_modules/@smithy/middleware-retry/dist-cjs/index.js
var require_dist_cjs33 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-retry@3.0.1/node_modules/@smithy/middleware-retry/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AdaptiveRetryStrategy: () => AdaptiveRetryStrategy,
      CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS,
      CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE,
      ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS,
      ENV_RETRY_MODE: () => ENV_RETRY_MODE,
      NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS,
      NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS,
      StandardRetryStrategy: () => StandardRetryStrategy,
      defaultDelayDecider: () => defaultDelayDecider,
      defaultRetryDecider: () => defaultRetryDecider,
      getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin,
      getRetryAfterHint: () => getRetryAfterHint,
      getRetryPlugin: () => getRetryPlugin,
      omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware,
      omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions,
      resolveRetryConfig: () => resolveRetryConfig,
      retryMiddleware: () => retryMiddleware,
      retryMiddlewareOptions: () => retryMiddlewareOptions
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http = require_dist_cjs2();
    var import_uuid = (init_esm_node(), __toCommonJS(esm_node_exports));
    var import_util_retry = require_dist_cjs20();
    var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => {
      const MAX_CAPACITY = initialRetryTokens;
      const noRetryIncrement = (options == null ? void 0 : options.noRetryIncrement) ?? import_util_retry.NO_RETRY_INCREMENT;
      const retryCost = (options == null ? void 0 : options.retryCost) ?? import_util_retry.RETRY_COST;
      const timeoutRetryCost = (options == null ? void 0 : options.timeoutRetryCost) ?? import_util_retry.TIMEOUT_RETRY_COST;
      let availableCapacity = initialRetryTokens;
      const getCapacityAmount = /* @__PURE__ */ __name((error2) => error2.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount");
      const hasRetryTokens = /* @__PURE__ */ __name((error2) => getCapacityAmount(error2) <= availableCapacity, "hasRetryTokens");
      const retrieveRetryTokens = /* @__PURE__ */ __name((error2) => {
        if (!hasRetryTokens(error2)) {
          throw new Error("No retry token available");
        }
        const capacityAmount = getCapacityAmount(error2);
        availableCapacity -= capacityAmount;
        return capacityAmount;
      }, "retrieveRetryTokens");
      const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => {
        availableCapacity += capacityReleaseAmount ?? noRetryIncrement;
        availableCapacity = Math.min(availableCapacity, MAX_CAPACITY);
      }, "releaseRetryTokens");
      return Object.freeze({
        hasRetryTokens,
        retrieveRetryTokens,
        releaseRetryTokens
      });
    }, "getDefaultRetryQuota");
    var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider");
    var import_service_error_classification = require_dist_cjs19();
    var defaultRetryDecider = /* @__PURE__ */ __name((error2) => {
      if (!error2) {
        return false;
      }
      return (0, import_service_error_classification.isRetryableByTrait)(error2) || (0, import_service_error_classification.isClockSkewError)(error2) || (0, import_service_error_classification.isThrottlingError)(error2) || (0, import_service_error_classification.isTransientError)(error2);
    }, "defaultRetryDecider");
    var asSdkError = /* @__PURE__ */ __name((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}`);
    }, "asSdkError");
    var _StandardRetryStrategy = class _StandardRetryStrategy {
      constructor(maxAttemptsProvider, options) {
        this.maxAttemptsProvider = maxAttemptsProvider;
        this.mode = import_util_retry.RETRY_MODES.STANDARD;
        this.retryDecider = (options == null ? void 0 : options.retryDecider) ?? defaultRetryDecider;
        this.delayDecider = (options == null ? void 0 : options.delayDecider) ?? defaultDelayDecider;
        this.retryQuota = (options == null ? void 0 : options.retryQuota) ?? getDefaultRetryQuota(import_util_retry.INITIAL_RETRY_TOKENS);
      }
      shouldRetry(error2, attempts, maxAttempts) {
        return attempts < maxAttempts && this.retryDecider(error2) && this.retryQuota.hasRetryTokens(error2);
      }
      async getMaxAttempts() {
        let maxAttempts;
        try {
          maxAttempts = await this.maxAttemptsProvider();
        } catch (error2) {
          maxAttempts = import_util_retry.DEFAULT_MAX_ATTEMPTS;
        }
        return maxAttempts;
      }
      async retry(next, args, options) {
        let retryTokenAmount;
        let attempts = 0;
        let totalDelay = 0;
        const maxAttempts = await this.getMaxAttempts();
        const { request } = args;
        if (import_protocol_http.HttpRequest.isInstance(request)) {
          request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)();
        }
        while (true) {
          try {
            if (import_protocol_http.HttpRequest.isInstance(request)) {
              request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
            }
            if (options == null ? void 0 : options.beforeRequest) {
              await options.beforeRequest();
            }
            const { response, output } = await next(args);
            if (options == null ? void 0 : options.afterRequest) {
              options.afterRequest(response);
            }
            this.retryQuota.releaseRetryTokens(retryTokenAmount);
            output.$metadata.attempts = attempts + 1;
            output.$metadata.totalRetryDelay = totalDelay;
            return { response, output };
          } catch (e2) {
            const err2 = asSdkError(e2);
            attempts++;
            if (this.shouldRetry(err2, attempts, maxAttempts)) {
              retryTokenAmount = this.retryQuota.retrieveRetryTokens(err2);
              const delayFromDecider = this.delayDecider(
                (0, import_service_error_classification.isThrottlingError)(err2) ? import_util_retry.THROTTLING_RETRY_DELAY_BASE : import_util_retry.DEFAULT_RETRY_DELAY_BASE,
                attempts
              );
              const delayFromResponse = getDelayFromRetryAfterHeader(err2.$response);
              const delay = Math.max(delayFromResponse || 0, delayFromDecider);
              totalDelay += delay;
              await new Promise((resolve2) => setTimeout(resolve2, delay));
              continue;
            }
            if (!err2.$metadata) {
              err2.$metadata = {};
            }
            err2.$metadata.attempts = attempts;
            err2.$metadata.totalRetryDelay = totalDelay;
            throw err2;
          }
        }
      }
    };
    __name(_StandardRetryStrategy, "StandardRetryStrategy");
    var StandardRetryStrategy = _StandardRetryStrategy;
    var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => {
      if (!import_protocol_http.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 retryAfterSeconds * 1e3;
      const retryAfterDate = new Date(retryAfter);
      return retryAfterDate.getTime() - Date.now();
    }, "getDelayFromRetryAfterHeader");
    var _AdaptiveRetryStrategy = class _AdaptiveRetryStrategy extends StandardRetryStrategy {
      constructor(maxAttemptsProvider, options) {
        const { rateLimiter, ...superOptions } = options ?? {};
        super(maxAttemptsProvider, superOptions);
        this.rateLimiter = rateLimiter ?? new import_util_retry.DefaultRateLimiter();
        this.mode = import_util_retry.RETRY_MODES.ADAPTIVE;
      }
      async retry(next, args) {
        return super.retry(next, args, {
          beforeRequest: async () => {
            return this.rateLimiter.getSendToken();
          },
          afterRequest: (response) => {
            this.rateLimiter.updateClientSendingRate(response);
          }
        });
      }
    };
    __name(_AdaptiveRetryStrategy, "AdaptiveRetryStrategy");
    var AdaptiveRetryStrategy = _AdaptiveRetryStrategy;
    var import_util_middleware = require_dist_cjs10();
    var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
    var CONFIG_MAX_ATTEMPTS = "max_attempts";
    var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => {
        const value = env3[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: import_util_retry.DEFAULT_MAX_ATTEMPTS
    };
    var resolveRetryConfig = /* @__PURE__ */ __name((input) => {
      const { retryStrategy } = input;
      const maxAttempts = (0, import_util_middleware.normalizeProvider)(input.maxAttempts ?? import_util_retry.DEFAULT_MAX_ATTEMPTS);
      return {
        ...input,
        maxAttempts,
        retryStrategy: async () => {
          if (retryStrategy) {
            return retryStrategy;
          }
          const retryMode = await (0, import_util_middleware.normalizeProvider)(input.retryMode)();
          if (retryMode === import_util_retry.RETRY_MODES.ADAPTIVE) {
            return new import_util_retry.AdaptiveRetryStrategy(maxAttempts);
          }
          return new import_util_retry.StandardRetryStrategy(maxAttempts);
        }
      };
    }, "resolveRetryConfig");
    var ENV_RETRY_MODE = "AWS_RETRY_MODE";
    var CONFIG_RETRY_MODE = "retry_mode";
    var NODE_RETRY_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => env3[ENV_RETRY_MODE],
      configFileSelector: (profile) => profile[CONFIG_RETRY_MODE],
      default: import_util_retry.DEFAULT_RETRY_MODE
    };
    var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => {
      const { request } = args;
      if (import_protocol_http.HttpRequest.isInstance(request)) {
        delete request.headers[import_util_retry.INVOCATION_ID_HEADER];
        delete request.headers[import_util_retry.REQUEST_HEADER];
      }
      return next(args);
    }, "omitRetryHeadersMiddleware");
    var omitRetryHeadersMiddlewareOptions = {
      name: "omitRetryHeadersMiddleware",
      tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"],
      relation: "before",
      toMiddleware: "awsAuthMiddleware",
      override: true
    };
    var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions);
      }
    }), "getOmitRetryHeadersPlugin");
    var import_smithy_client = require_dist_cjs32();
    var import_isStreamingPayload = require_isStreamingPayload();
    var retryMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => {
      var _a;
      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 } = args;
        const isRequest2 = import_protocol_http.HttpRequest.isInstance(request);
        if (isRequest2) {
          request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)();
        }
        while (true) {
          try {
            if (isRequest2) {
              request.headers[import_util_retry.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 (e2) {
            const retryErrorInfo = getRetryErrorInfo(e2);
            lastError = asSdkError(e2);
            if (isRequest2 && (0, import_isStreamingPayload.isStreamingPayload)(request)) {
              (_a = context.logger instanceof import_smithy_client.NoOpLogger ? console : context.logger) == null ? void 0 : _a.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((resolve2) => setTimeout(resolve2, delay));
          }
        }
      } else {
        retryStrategy = retryStrategy;
        if (retryStrategy == null ? void 0 : retryStrategy.mode)
          context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
        return retryStrategy.retry(next, args);
      }
    }, "retryMiddleware");
    var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2");
    var getRetryErrorInfo = /* @__PURE__ */ __name((error2) => {
      const errorInfo = {
        error: error2,
        errorType: getRetryErrorType(error2)
      };
      const retryAfterHint = getRetryAfterHint(error2.$response);
      if (retryAfterHint) {
        errorInfo.retryAfterHint = retryAfterHint;
      }
      return errorInfo;
    }, "getRetryErrorInfo");
    var getRetryErrorType = /* @__PURE__ */ __name((error2) => {
      if ((0, import_service_error_classification.isThrottlingError)(error2))
        return "THROTTLING";
      if ((0, import_service_error_classification.isTransientError)(error2))
        return "TRANSIENT";
      if ((0, import_service_error_classification.isServerError)(error2))
        return "SERVER_ERROR";
      return "CLIENT_ERROR";
    }, "getRetryErrorType");
    var retryMiddlewareOptions = {
      name: "retryMiddleware",
      tags: ["RETRY"],
      step: "finalizeRequest",
      priority: "high",
      override: true
    };
    var getRetryPlugin = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
      }
    }), "getRetryPlugin");
    var getRetryAfterHint = /* @__PURE__ */ __name((response) => {
      if (!import_protocol_http.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;
    }, "getRetryAfterHint");
  }
});

// ../node_modules/.pnpm/@smithy+core@2.0.1/node_modules/@smithy/core/dist-cjs/index.js
var require_dist_cjs34 = __commonJS({
  "../node_modules/.pnpm/@smithy+core@2.0.1/node_modules/@smithy/core/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig,
      EXPIRATION_MS: () => EXPIRATION_MS,
      HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner,
      HttpBearerAuthSigner: () => HttpBearerAuthSigner,
      NoAuthSigner: () => NoAuthSigner,
      RequestBuilder: () => RequestBuilder,
      createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction,
      createPaginator: () => createPaginator,
      doesIdentityRequireRefresh: () => doesIdentityRequireRefresh,
      getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin,
      getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin,
      getHttpSigningPlugin: () => getHttpSigningPlugin,
      getSmithyContext: () => getSmithyContext3,
      httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions,
      httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware,
      httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions,
      httpSigningMiddleware: () => httpSigningMiddleware,
      httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions,
      isIdentityExpired: () => isIdentityExpired,
      memoizeIdentityProvider: () => memoizeIdentityProvider,
      normalizeProvider: () => normalizeProvider,
      requestBuilder: () => requestBuilder
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_middleware = require_dist_cjs10();
    function convertHttpAuthSchemesToMap(httpAuthSchemes) {
      const map = /* @__PURE__ */ new Map();
      for (const scheme of httpAuthSchemes) {
        map.set(scheme.schemeId, scheme);
      }
      return map;
    }
    __name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap");
    var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => {
      var _a;
      const options = config.httpAuthSchemeProvider(
        await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)
      );
      const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
      const smithyContext = (0, import_util_middleware.getSmithyContext)(context);
      const failureReasons = [];
      for (const option of options) {
        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 = {} } = ((_a = option.propertiesExtractor) == null ? void 0 : _a.call(option, 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);
    }, "httpAuthSchemeMiddleware");
    var import_middleware_endpoint = require_dist_cjs18();
    var httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: import_middleware_endpoint.endpointMiddlewareOptions.name
    };
    var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, {
      httpAuthSchemeParametersProvider,
      identityProviderConfigProvider
    }) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(
          httpAuthSchemeMiddleware(config, {
            httpAuthSchemeParametersProvider,
            identityProviderConfigProvider
          }),
          httpAuthSchemeEndpointRuleSetMiddlewareOptions
        );
      }
    }), "getHttpAuthSchemeEndpointRuleSetPlugin");
    var import_middleware_serde = require_dist_cjs17();
    var httpAuthSchemeMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: import_middleware_serde.serializerMiddlewareOption.name
    };
    var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, {
      httpAuthSchemeParametersProvider,
      identityProviderConfigProvider
    }) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(
          httpAuthSchemeMiddleware(config, {
            httpAuthSchemeParametersProvider,
            identityProviderConfigProvider
          }),
          httpAuthSchemeMiddlewareOptions
        );
      }
    }), "getHttpAuthSchemePlugin");
    var import_protocol_http = require_dist_cjs2();
    var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error2) => {
      throw error2;
    }, "defaultErrorHandler");
    var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => {
    }, "defaultSuccessHandler");
    var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => {
      if (!import_protocol_http.HttpRequest.isInstance(args.request)) {
        return next(args);
      }
      const smithyContext = (0, import_util_middleware.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;
    }, "httpSigningMiddleware");
    var import_middleware_retry = require_dist_cjs33();
    var httpSigningMiddlewareOptions = {
      step: "finalizeRequest",
      tags: ["HTTP_SIGNING"],
      name: "httpSigningMiddleware",
      aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
      override: true,
      relation: "after",
      toMiddleware: import_middleware_retry.retryMiddlewareOptions.name
    };
    var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
      }
    }), "getHttpSigningPlugin");
    var _DefaultIdentityProviderConfig = class _DefaultIdentityProviderConfig {
      /**
       * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers.
       *
       * @param config scheme IDs and identity providers to configure
       */
      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);
      }
    };
    __name(_DefaultIdentityProviderConfig, "DefaultIdentityProviderConfig");
    var DefaultIdentityProviderConfig = _DefaultIdentityProviderConfig;
    var import_types = require_dist_cjs();
    var _HttpApiKeyAuthSigner = class _HttpApiKeyAuthSigner {
      async sign(httpRequest, identity, signingProperties) {
        if (!signingProperties) {
          throw new Error(
            "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"
          );
        }
        if (!signingProperties.name) {
          throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing");
        }
        if (!signingProperties.in) {
          throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing");
        }
        if (!identity.apiKey) {
          throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined");
        }
        const clonedRequest = httpRequest.clone();
        if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) {
          clonedRequest.query[signingProperties.name] = identity.apiKey;
        } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) {
          clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey;
        } else {
          throw new Error(
            "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`"
          );
        }
        return clonedRequest;
      }
    };
    __name(_HttpApiKeyAuthSigner, "HttpApiKeyAuthSigner");
    var HttpApiKeyAuthSigner = _HttpApiKeyAuthSigner;
    var _HttpBearerAuthSigner = class _HttpBearerAuthSigner {
      async sign(httpRequest, identity, signingProperties) {
        const clonedRequest = httpRequest.clone();
        if (!identity.token) {
          throw new Error("request could not be signed with `token` since the `token` is not defined");
        }
        clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`;
        return clonedRequest;
      }
    };
    __name(_HttpBearerAuthSigner, "HttpBearerAuthSigner");
    var HttpBearerAuthSigner = _HttpBearerAuthSigner;
    var _NoAuthSigner = class _NoAuthSigner {
      async sign(httpRequest, identity, signingProperties) {
        return httpRequest;
      }
    };
    __name(_NoAuthSigner, "NoAuthSigner");
    var NoAuthSigner = _NoAuthSigner;
    var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction");
    var EXPIRATION_MS = 3e5;
    var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
    var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh");
    var memoizeIdentityProvider = /* @__PURE__ */ __name((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 = /* @__PURE__ */ __name(async (options) => {
        if (!pending) {
          pending = normalizedProvider(options);
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      }, "coalesceProvider");
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
            resolved = await coalesceProvider(options);
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || (options == null ? void 0 : 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;
      };
    }, "memoizeIdentityProvider");
    var getSmithyContext3 = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext");
    var normalizeProvider = /* @__PURE__ */ __name((input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    }, "normalizeProvider");
    var import_smithy_client = require_dist_cjs32();
    function requestBuilder(input, context) {
      return new RequestBuilder(input, context);
    }
    __name(requestBuilder, "requestBuilder");
    var _RequestBuilder = class _RequestBuilder {
      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 import_protocol_http.HttpRequest({
          protocol,
          hostname: this.hostname || hostname,
          port,
          method: this.method,
          path: this.path,
          query: this.query,
          body: this.body,
          headers: this.headers
        });
      }
      /**
       * Brevity setter for "hostname".
       */
      hn(hostname) {
        this.hostname = hostname;
        return this;
      }
      /**
       * Brevity initial builder for "basepath".
       */
      bp(uriLabel) {
        this.resolvePathStack.push((basePath) => {
          this.path = `${(basePath == null ? void 0 : basePath.endsWith("/")) ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
        });
        return this;
      }
      /**
       * Brevity incremental builder for "path".
       */
      p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
        this.resolvePathStack.push((path4) => {
          this.path = (0, import_smithy_client.resolvedPath)(path4, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
        });
        return this;
      }
      /**
       * Brevity setter for "headers".
       */
      h(headers) {
        this.headers = headers;
        return this;
      }
      /**
       * Brevity setter for "query".
       */
      q(query) {
        this.query = query;
        return this;
      }
      /**
       * Brevity setter for "body".
       */
      b(body) {
        this.body = body;
        return this;
      }
      /**
       * Brevity setter for "method".
       */
      m(method) {
        this.method = method;
        return this;
      }
    };
    __name(_RequestBuilder, "RequestBuilder");
    var RequestBuilder = _RequestBuilder;
    var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, ...args) => {
      return await client.send(new CommandCtor(input), ...args);
    }, "makePagedClientRequest");
    function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
      return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) {
        let token = config.startingToken || void 0;
        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, ...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;
      }, "paginateOperation");
    }
    __name(createPaginator, "createPaginator");
    var get = /* @__PURE__ */ __name((fromObject, path4) => {
      let cursor = fromObject;
      const pathComponents = path4.split(".");
      for (const step of pathComponents) {
        if (!cursor || typeof cursor !== "object") {
          return void 0;
        }
        cursor = cursor[step];
      }
      return cursor;
    }, "get");
  }
});

// ../node_modules/.pnpm/@smithy+middleware-content-length@3.0.0/node_modules/@smithy/middleware-content-length/dist-cjs/index.js
var require_dist_cjs35 = __commonJS({
  "../node_modules/.pnpm/@smithy+middleware-content-length@3.0.0/node_modules/@smithy/middleware-content-length/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      contentLengthMiddleware: () => contentLengthMiddleware,
      contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions,
      getContentLengthPlugin: () => getContentLengthPlugin
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_protocol_http = require_dist_cjs2();
    var CONTENT_LENGTH_HEADER = "content-length";
    function contentLengthMiddleware(bodyLengthChecker) {
      return (next) => async (args) => {
        const request = args.request;
        if (import_protocol_http.HttpRequest.isInstance(request)) {
          const { body, headers } = request;
          if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
            try {
              const length = bodyLengthChecker(body);
              request.headers = {
                ...request.headers,
                [CONTENT_LENGTH_HEADER]: String(length)
              };
            } catch (error2) {
            }
          }
        }
        return next({
          ...args,
          request
        });
      };
    }
    __name(contentLengthMiddleware, "contentLengthMiddleware");
    var contentLengthMiddlewareOptions = {
      step: "build",
      tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
      name: "contentLengthMiddleware",
      override: true
    };
    var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
      }
    }), "getContentLengthPlugin");
  }
});

// ../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports = {};
__export(tslib_es6_exports, {
  __addDisposableResource: () => __addDisposableResource,
  __assign: () => __assign,
  __asyncDelegator: () => __asyncDelegator,
  __asyncGenerator: () => __asyncGenerator,
  __asyncValues: () => __asyncValues,
  __await: () => __await,
  __awaiter: () => __awaiter,
  __classPrivateFieldGet: () => __classPrivateFieldGet2,
  __classPrivateFieldIn: () => __classPrivateFieldIn,
  __classPrivateFieldSet: () => __classPrivateFieldSet2,
  __createBinding: () => __createBinding,
  __decorate: () => __decorate,
  __disposeResources: () => __disposeResources,
  __esDecorate: () => __esDecorate,
  __exportStar: () => __exportStar,
  __extends: () => __extends,
  __generator: () => __generator,
  __importDefault: () => __importDefault,
  __importStar: () => __importStar,
  __makeTemplateObject: () => __makeTemplateObject,
  __metadata: () => __metadata,
  __param: () => __param,
  __propKey: () => __propKey,
  __read: () => __read,
  __rest: () => __rest,
  __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension,
  __runInitializers: () => __runInitializers,
  __setFunctionName: () => __setFunctionName,
  __spread: () => __spread,
  __spreadArray: () => __spreadArray,
  __spreadArrays: () => __spreadArrays,
  __values: () => __values,
  default: () => tslib_es6_default
});
function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s2, e2) {
  var t2 = {};
  for (var p in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p) && e2.indexOf(p) < 0)
      t2[p] = s2[p];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i2 = 0, p = Object.getOwnPropertySymbols(s2); i2 < p.length; i2++) {
      if (e2.indexOf(p[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p[i2]))
        t2[p[i2]] = s2[p[i2]];
    }
  return t2;
}
function __decorate(decorators, target, key, desc) {
  var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r2 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i2 = decorators.length - 1; i2 >= 0; i2--)
      if (d = decorators[i2])
        r2 = (c < 3 ? d(r2) : c > 3 ? d(target, key, r2) : d(target, key)) || r2;
  return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f3) {
    if (f3 !== void 0 && typeof f3 !== "function")
      throw new TypeError("Function expected");
    return f3;
  }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _2, done = false;
  for (var i2 = decorators.length - 1; i2 >= 0; i2--) {
    var context = {};
    for (var p in contextIn)
      context[p] = p === "access" ? {} : contextIn[p];
    for (var p in contextIn.access)
      context.access[p] = contextIn.access[p];
    context.addInitializer = function(f3) {
      if (done)
        throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f3 || null));
    };
    var result = (0, decorators[i2])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind === "accessor") {
      if (result === void 0)
        continue;
      if (result === null || typeof result !== "object")
        throw new TypeError("Object expected");
      if (_2 = accept(result.get))
        descriptor.get = _2;
      if (_2 = accept(result.set))
        descriptor.set = _2;
      if (_2 = accept(result.init))
        initializers.unshift(_2);
    } else if (_2 = accept(result)) {
      if (kind === "field")
        initializers.unshift(_2);
      else
        descriptor[key] = _2;
    }
  }
  if (target)
    Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i2 = 0; i2 < initializers.length; i2++) {
    value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey(x2) {
  return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName(f3, name, prefix2) {
  if (typeof name === "symbol")
    name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f3, "name", { configurable: true, value: prefix2 ? "".concat(prefix2, " ", name) : name });
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1)
      throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f3, y, t2, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f3)
      throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2)
      try {
        if (f3 = 1, y && (t2 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t2 = y["return"]) && t2.call(y), 0) : y.next) && !(t2 = t2.call(y, op[1])).done)
          return t2;
        if (y = 0, t2)
          op = [op[0] & 2, t2.value];
        switch (op[0]) {
          case 0:
          case 1:
            t2 = op;
            break;
          case 4:
            _2.label++;
            return { value: op[1], done: false };
          case 5:
            _2.label++;
            y = op[1];
            op = [0];
            continue;
          case 7:
            op = _2.ops.pop();
            _2.trys.pop();
            continue;
          default:
            if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _2 = 0;
              continue;
            }
            if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
              _2.label = op[1];
              break;
            }
            if (op[0] === 6 && _2.label < t2[1]) {
              _2.label = t2[1];
              t2 = op;
              break;
            }
            if (t2 && _2.label < t2[2]) {
              _2.label = t2[2];
              _2.ops.push(op);
              break;
            }
            if (t2[2])
              _2.ops.pop();
            _2.trys.pop();
            continue;
        }
        op = body.call(thisArg, _2);
      } catch (e2) {
        op = [6, e2];
        y = 0;
      } finally {
        f3 = t2 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar(m2, o) {
  for (var p in m2)
    if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
      __createBinding(o, m2, p);
}
function __values(o) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o[s2], i2 = 0;
  if (m2)
    return m2.call(o);
  if (o && typeof o.length === "number")
    return {
      next: function() {
        if (o && i2 >= o.length)
          o = void 0;
        return { value: o && o[i2++], done: !o };
      }
    };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m2 = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m2)
    return o;
  var i2 = m2.call(o), r2, ar = [], e2;
  try {
    while ((n === void 0 || n-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error2) {
    e2 = { error: error2 };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read(arguments[i2]));
  return ar;
}
function __spreadArrays() {
  for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++)
    s2 += arguments[i2].length;
  for (var r2 = Array(s2), k = 0, i2 = 0; i2 < il; i2++)
    for (var a = arguments[i2], j = 0, jl = a.length; j < jl; j++, k++)
      r2[k] = a[j];
  return r2;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i2 = 0, l = from.length, ar; i2 < l; i2++) {
      if (ar || !(i2 in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i2);
        ar[i2] = from[i2];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i2, q = [];
  return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2;
  function awaitReturn(f3) {
    return function(v) {
      return Promise.resolve(v).then(f3, reject);
    };
  }
  function verb(n, f3) {
    if (g[n]) {
      i2[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
      if (f3)
        i2[n] = f3(i2[n]);
    }
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e2) {
      settle(q[0][3], e2);
    }
  }
  function step(r2) {
    r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q[0][2], r2);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f3, v) {
    if (f3(v), q.shift(), q.length)
      resume(q[0][0], q[0][1]);
  }
}
function __asyncDelegator(o) {
  var i2, p;
  return i2 = {}, verb("next"), verb("throw", function(e2) {
    throw e2;
  }), verb("return"), i2[Symbol.iterator] = function() {
    return this;
  }, i2;
  function verb(n, f3) {
    i2[n] = o[n] ? function(v) {
      return (p = !p) ? { value: __await(o[n](v)), done: false } : f3 ? f3(v) : v;
    } : f3;
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m2 = o[Symbol.asyncIterator], i2;
  return m2 ? m2.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2);
  function verb(n) {
    i2[n] = o[n] && function(v) {
      return new Promise(function(resolve2, reject) {
        v = o[n](v), settle(resolve2, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve2, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve2({ value: v2, done: d });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw2) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw2 });
  } else {
    cooked.raw = raw2;
  }
  return cooked;
}
function __importStar(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k = ownKeys(mod), i2 = 0; i2 < k.length; i2++)
      if (k[i2] !== "default")
        __createBinding(result, mod, k[i2]);
  }
  __setModuleDefault(result, mod);
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet2(receiver, state, kind, f3) {
  if (kind === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet2(receiver, state, value, kind, f3) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldIn(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function")
    throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env3, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function")
      throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose)
        throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose)
        throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async)
        inner = dispose;
    }
    if (typeof dispose !== "function")
      throw new TypeError("Object not disposable.");
    if (inner)
      dispose = function() {
        try {
          inner.call(this);
        } catch (e2) {
          return Promise.reject(e2);
        }
      };
    env3.stack.push({ value, dispose, async });
  } else if (async) {
    env3.stack.push({ async: true });
  }
  return value;
}
function __disposeResources(env3) {
  function fail(e2) {
    env3.error = env3.hasError ? new _SuppressedError(e2, env3.error, "An error was suppressed during disposal.") : e2;
    env3.hasError = true;
  }
  var r2, s2 = 0;
  function next() {
    while (r2 = env3.stack.pop()) {
      try {
        if (!r2.async && s2 === 1)
          return s2 = 0, env3.stack.push(r2), Promise.resolve().then(next);
        if (r2.dispose) {
          var result = r2.dispose.call(r2.value);
          if (r2.async)
            return s2 |= 2, Promise.resolve(result).then(next, function(e2) {
              fail(e2);
              return next();
            });
        } else
          s2 |= 1;
      } catch (e2) {
        fail(e2);
      }
    }
    if (s2 === 1)
      return env3.hasError ? Promise.reject(env3.error) : Promise.resolve();
    if (env3.hasError)
      throw env3.error;
  }
  return next();
}
function __rewriteRelativeImportExtension(path4, preserveJsx) {
  if (typeof path4 === "string" && /^\.\.?\//.test(path4)) {
    return path4.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m2, tsx, d, ext2, cm) {
      return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext2 || !cm) ? m2 : d + ext2 + "." + cm.toLowerCase() + "js";
    });
  }
  return path4;
}
var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default;
var init_tslib_es6 = __esm({
  "../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs"() {
    extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics(d, b);
    };
    __assign = function() {
      __assign = Object.assign || function __assign3(t2) {
        for (var s2, i2 = 1, n = arguments.length; i2 < n; i2++) {
          s2 = arguments[i2];
          for (var p in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p))
              t2[p] = s2[p];
        }
        return t2;
      };
      return __assign.apply(this, arguments);
    };
    __createBinding = Object.create ? function(o, m2, k, k2) {
      if (k2 === void 0)
        k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m2, k, k2) {
      if (k2 === void 0)
        k2 = k;
      o[k2] = m2[k];
    };
    __setModuleDefault = Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    };
    ownKeys = function(o) {
      ownKeys = Object.getOwnPropertyNames || function(o2) {
        var ar = [];
        for (var k in o2)
          if (Object.prototype.hasOwnProperty.call(o2, k))
            ar[ar.length] = k;
        return ar;
      };
      return ownKeys(o);
    };
    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
      var e2 = new Error(message);
      return e2.name = "SuppressedError", e2.error = error2, e2.suppressed = suppressed, e2;
    };
    tslib_es6_default = {
      __extends,
      __assign,
      __rest,
      __decorate,
      __param,
      __esDecorate,
      __runInitializers,
      __propKey,
      __setFunctionName,
      __metadata,
      __awaiter,
      __generator,
      __createBinding,
      __exportStar,
      __values,
      __read,
      __spread,
      __spreadArrays,
      __spreadArray,
      __await,
      __asyncGenerator,
      __asyncDelegator,
      __asyncValues,
      __makeTemplateObject,
      __importStar,
      __importDefault,
      __classPrivateFieldGet: __classPrivateFieldGet2,
      __classPrivateFieldSet: __classPrivateFieldSet2,
      __classPrivateFieldIn,
      __addDisposableResource,
      __disposeResources,
      __rewriteRelativeImportExtension
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js
var require_client = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var client_exports = {};
    __export2(client_exports, {
      emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion
    });
    module2.exports = __toCommonJS2(client_exports);
    var warningEmitted = false;
    var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version3) => {
      if (version3 && !warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 16) {
        warningEmitted = true;
      }
    }, "emitWarningIfUnsupportedVersion");
  }
});

// ../node_modules/.pnpm/@smithy+signature-v4@3.0.0/node_modules/@smithy/signature-v4/dist-cjs/index.js
var require_dist_cjs36 = __commonJS({
  "../node_modules/.pnpm/@smithy+signature-v4@3.0.0/node_modules/@smithy/signature-v4/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      SignatureV4: () => SignatureV4,
      clearCredentialCache: () => clearCredentialCache,
      createScope: () => createScope,
      getCanonicalHeaders: () => getCanonicalHeaders,
      getCanonicalQuery: () => getCanonicalQuery,
      getPayloadHash: () => getPayloadHash,
      getSigningKey: () => getSigningKey,
      moveHeadersToQuery: () => moveHeadersToQuery,
      prepareRequest: () => prepareRequest
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_middleware = require_dist_cjs10();
    var import_util_utf84 = require_dist_cjs24();
    var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
    var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
    var AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
    var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
    var EXPIRES_QUERY_PARAM = "X-Amz-Expires";
    var SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
    var TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
    var AUTH_HEADER = "authorization";
    var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
    var DATE_HEADER = "date";
    var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
    var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
    var SHA256_HEADER = "x-amz-content-sha256";
    var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
    var 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
    };
    var PROXY_HEADER_PATTERN = /^proxy-/;
    var SEC_HEADER_PATTERN = /^sec-/;
    var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
    var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
    var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
    var MAX_CACHE_SIZE = 50;
    var KEY_TYPE_IDENTIFIER = "aws4_request";
    var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
    var import_util_hex_encoding = require_dist_cjs30();
    var import_util_utf8 = require_dist_cjs24();
    var signingKeyCache = {};
    var cacheQueue = [];
    var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope");
    var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials2, shortDate, region, service) => {
      const credsHash = await hmac(sha256Constructor, credentials2.secretAccessKey, credentials2.accessKeyId);
      const cacheKey2 = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.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;
    }, "getSigningKey");
    var clearCredentialCache = /* @__PURE__ */ __name(() => {
      cacheQueue.length = 0;
      Object.keys(signingKeyCache).forEach((cacheKey2) => {
        delete signingKeyCache[cacheKey2];
      });
    }, "clearCredentialCache");
    var hmac = /* @__PURE__ */ __name((ctor, secret, data) => {
      const hash = new ctor(secret);
      hash.update((0, import_util_utf8.toUint8Array)(data));
      return hash.digest();
    }, "hmac");
    var getCanonicalHeaders = /* @__PURE__ */ __name(({ 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 == null ? void 0 : 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;
    }, "getCanonicalHeaders");
    var import_util_uri_escape = require_dist_cjs26();
    var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => {
      const keys = [];
      const serialized = {};
      for (const key of Object.keys(query).sort()) {
        if (key.toLowerCase() === SIGNATURE_HEADER) {
          continue;
        }
        keys.push(key);
        const value = query[key];
        if (typeof value === "string") {
          serialized[key] = `${(0, import_util_uri_escape.escapeUri)(key)}=${(0, import_util_uri_escape.escapeUri)(value)}`;
        } else if (Array.isArray(value)) {
          serialized[key] = value.slice(0).reduce(
            (encoded, value2) => encoded.concat([`${(0, import_util_uri_escape.escapeUri)(key)}=${(0, import_util_uri_escape.escapeUri)(value2)}`]),
            []
          ).sort().join("&");
        }
      }
      return keys.map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
    }, "getCanonicalQuery");
    var import_is_array_buffer = require_dist_cjs22();
    var import_util_utf82 = require_dist_cjs24();
    var getPayloadHash = /* @__PURE__ */ __name(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) || (0, import_is_array_buffer.isArrayBuffer)(body)) {
        const hashCtor = new hashConstructor();
        hashCtor.update((0, import_util_utf82.toUint8Array)(body));
        return (0, import_util_hex_encoding.toHex)(await hashCtor.digest());
      }
      return UNSIGNED_PAYLOAD;
    }, "getPayloadHash");
    var import_util_utf83 = require_dist_cjs24();
    var _HeaderFormatter = class _HeaderFormatter {
      format(headers) {
        const chunks = [];
        for (const headerName of Object.keys(headers)) {
          const bytes = (0, import_util_utf83.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
              /* boolFalse */
            ]);
          case "byte":
            return Uint8Array.from([2, header.value]);
          case "short":
            const shortView = new DataView(new ArrayBuffer(3));
            shortView.setUint8(
              0,
              3
              /* short */
            );
            shortView.setInt16(1, header.value, false);
            return new Uint8Array(shortView.buffer);
          case "integer":
            const intView = new DataView(new ArrayBuffer(5));
            intView.setUint8(
              0,
              4
              /* integer */
            );
            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
              /* byteArray */
            );
            binView.setUint16(1, header.value.byteLength, false);
            const binBytes = new Uint8Array(binView.buffer);
            binBytes.set(header.value, 3);
            return binBytes;
          case "string":
            const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value);
            const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
            strView.setUint8(
              0,
              7
              /* string */
            );
            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((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1);
            return uuidBytes;
        }
      }
    };
    __name(_HeaderFormatter, "HeaderFormatter");
    var HeaderFormatter = _HeaderFormatter;
    var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
    var _Int64 = class _Int642 {
      constructor(bytes) {
        this.bytes = bytes;
        if (bytes.byteLength !== 8) {
          throw new Error("Int64 buffers must be exactly 8 bytes");
        }
      }
      static fromNumber(number2) {
        if (number2 > 9223372036854776e3 || number2 < -9223372036854776e3) {
          throw new Error(`${number2} is too large (or, if negative, too small) to represent as an Int64`);
        }
        const bytes = new Uint8Array(8);
        for (let i2 = 7, remaining = Math.abs(Math.round(number2)); i2 > -1 && remaining > 0; i2--, remaining /= 256) {
          bytes[i2] = remaining;
        }
        if (number2 < 0) {
          negate(bytes);
        }
        return new _Int642(bytes);
      }
      /**
       * Called implicitly by infix arithmetic operators.
       */
      valueOf() {
        const bytes = this.bytes.slice(0);
        const negative = bytes[0] & 128;
        if (negative) {
          negate(bytes);
        }
        return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1);
      }
      toString() {
        return String(this.valueOf());
      }
    };
    __name(_Int64, "Int64");
    var Int64 = _Int64;
    function negate(bytes) {
      for (let i2 = 0; i2 < 8; i2++) {
        bytes[i2] ^= 255;
      }
      for (let i2 = 7; i2 > -1; i2--) {
        bytes[i2]++;
        if (bytes[i2] !== 0)
          break;
      }
    }
    __name(negate, "negate");
    var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => {
      soughtHeader = soughtHeader.toLowerCase();
      for (const headerName of Object.keys(headers)) {
        if (soughtHeader === headerName.toLowerCase()) {
          return true;
        }
      }
      return false;
    }, "hasHeader");
    var cloneRequest = /* @__PURE__ */ __name(({ headers, query, ...rest }) => ({
      ...rest,
      headers: { ...headers },
      query: query ? cloneQuery(query) : void 0
    }), "cloneRequest");
    var cloneQuery = /* @__PURE__ */ __name((query) => Object.keys(query).reduce((carry, paramName) => {
      const param = query[paramName];
      return {
        ...carry,
        [paramName]: Array.isArray(param) ? [...param] : param
      };
    }, {}), "cloneQuery");
    var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => {
      var _a;
      const { headers, query = {} } = typeof request.clone === "function" ? request.clone() : cloneRequest(request);
      for (const name of Object.keys(headers)) {
        const lname = name.toLowerCase();
        if (lname.slice(0, 6) === "x-amz-" && !((_a = options.unhoistableHeaders) == null ? void 0 : _a.has(lname))) {
          query[name] = headers[name];
          delete headers[name];
        }
      }
      return {
        ...request,
        headers,
        query
      };
    }, "moveHeadersToQuery");
    var prepareRequest = /* @__PURE__ */ __name((request) => {
      request = typeof request.clone === "function" ? request.clone() : cloneRequest(request);
      for (const headerName of Object.keys(request.headers)) {
        if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
          delete request.headers[headerName];
        }
      }
      return request;
    }, "prepareRequest");
    var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601");
    var toDate = /* @__PURE__ */ __name((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;
    }, "toDate");
    var _SignatureV4 = class _SignatureV4 {
      constructor({
        applyChecksum,
        credentials: credentials2,
        region,
        service,
        sha256: sha2562,
        uriEscapePath = true
      }) {
        this.headerFormatter = new HeaderFormatter();
        this.service = service;
        this.sha256 = sha2562;
        this.uriEscapePath = uriEscapePath;
        this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
        this.regionProvider = (0, import_util_middleware.normalizeProvider)(region);
        this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials2);
      }
      async presign(originalRequest, options = {}) {
        const {
          signingDate = /* @__PURE__ */ new Date(),
          expiresIn = 3600,
          unsignableHeaders,
          unhoistableHeaders,
          signableHeaders,
          signingRegion,
          signingService
        } = options;
        const credentials2 = await this.credentialProvider();
        this.validateResolvedCredentials(credentials2);
        const region = signingRegion ?? await this.regionProvider();
        const { longDate, shortDate } = 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 request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders });
        if (credentials2.sessionToken) {
          request.query[TOKEN_QUERY_PARAM] = credentials2.sessionToken;
        }
        request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
        request.query[CREDENTIAL_QUERY_PARAM] = `${credentials2.accessKeyId}/${scope}`;
        request.query[AMZ_DATE_QUERY_PARAM] = longDate;
        request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
        const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
        request.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders);
        request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(
          longDate,
          scope,
          this.getSigningKey(credentials2, region, shortDate, signingService),
          this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))
        );
        return request;
      }
      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 } = 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 = (0, import_util_hex_encoding.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 } = formatDate(signingDate);
        const hash = new this.sha256(await this.getSigningKey(credentials2, region, shortDate, signingService));
        hash.update((0, import_util_utf84.toUint8Array)(stringToSign));
        return (0, import_util_hex_encoding.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 request = prepareRequest(requestToSign);
        const { longDate, shortDate } = formatDate(signingDate);
        const scope = createScope(shortDate, region, signingService ?? this.service);
        request.headers[AMZ_DATE_HEADER] = longDate;
        if (credentials2.sessionToken) {
          request.headers[TOKEN_HEADER] = credentials2.sessionToken;
        }
        const payloadHash = await getPayloadHash(request, this.sha256);
        if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) {
          request.headers[SHA256_HEADER] = payloadHash;
        }
        const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
        const signature = await this.getSignature(
          longDate,
          scope,
          this.getSigningKey(credentials2, region, shortDate, signingService),
          this.createCanonicalRequest(request, canonicalHeaders, payloadHash)
        );
        request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials2.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
        return request;
      }
      createCanonicalRequest(request, canonicalHeaders, payloadHash) {
        const sortedHeaders = Object.keys(canonicalHeaders).sort();
        return `${request.method}
${this.getCanonicalPath(request)}
${getCanonicalQuery(request)}
${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}

${sortedHeaders.join(";")}
${payloadHash}`;
      }
      async createStringToSign(longDate, credentialScope, canonicalRequest) {
        const hash = new this.sha256();
        hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest));
        const hashedRequest = await hash.digest();
        return `${ALGORITHM_IDENTIFIER}
${longDate}
${credentialScope}
${(0, import_util_hex_encoding.toHex)(hashedRequest)}`;
      }
      getCanonicalPath({ path: path4 }) {
        if (this.uriEscapePath) {
          const normalizedPathSegments = [];
          for (const pathSegment of path4.split("/")) {
            if ((pathSegment == null ? void 0 : pathSegment.length) === 0)
              continue;
            if (pathSegment === ".")
              continue;
            if (pathSegment === "..") {
              normalizedPathSegments.pop();
            } else {
              normalizedPathSegments.push(pathSegment);
            }
          }
          const normalizedPath = `${(path4 == null ? void 0 : path4.startsWith("/")) ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && (path4 == null ? void 0 : path4.endsWith("/")) ? "/" : ""}`;
          const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath);
          return doubleEncoded.replace(/%2F/g, "/");
        }
        return path4;
      }
      async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
        const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest);
        const hash = new this.sha256(await keyPromise);
        hash.update((0, import_util_utf84.toUint8Array)(stringToSign));
        return (0, import_util_hex_encoding.toHex)(await hash.digest());
      }
      getSigningKey(credentials2, region, shortDate, service) {
        return getSigningKey(this.sha256, credentials2, shortDate, region, service || this.service);
      }
      validateResolvedCredentials(credentials2) {
        if (typeof credentials2 !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339)
        typeof credentials2.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339)
        typeof credentials2.secretAccessKey !== "string") {
          throw new Error("Resolved credential object is not valid");
        }
      }
    };
    __name(_SignatureV4, "SignatureV4");
    var SignatureV4 = _SignatureV4;
    var formatDate = /* @__PURE__ */ __name((now) => {
      const longDate = iso8601(now).replace(/[\-:]/g, "");
      return {
        longDate,
        shortDate: longDate.slice(0, 8)
      };
    }, "formatDate");
    var getCanonicalHeaderList = /* @__PURE__ */ __name((headers) => Object.keys(headers).sort().join(";"), "getCanonicalHeaderList");
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js
var require_httpAuthSchemes = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var httpAuthSchemes_exports = {};
    __export2(httpAuthSchemes_exports, {
      AWSSDKSigV4Signer: () => AWSSDKSigV4Signer,
      AwsSdkSigV4Signer: () => AwsSdkSigV4Signer,
      resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config,
      resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config
    });
    module2.exports = __toCommonJS2(httpAuthSchemes_exports);
    var import_protocol_http2 = require_dist_cjs2();
    var import_protocol_http = require_dist_cjs2();
    var getDateHeader = /* @__PURE__ */ __name((response) => {
      var _a, _b;
      return import_protocol_http.HttpResponse.isInstance(response) ? ((_a = response.headers) == null ? void 0 : _a.date) ?? ((_b = response.headers) == null ? void 0 : _b.Date) : void 0;
    }, "getDateHeader");
    var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate");
    var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed");
    var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => {
      const clockTimeInMs = Date.parse(clockTime);
      if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
        return clockTimeInMs - Date.now();
      }
      return currentSystemClockOffset;
    }, "getUpdatedSystemClockOffset");
    var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => {
      if (!property) {
        throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
      }
      return property;
    }, "throwSigningPropertyError");
    var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => {
      var _a, _b, _c;
      const context = throwSigningPropertyError(
        "context",
        signingProperties.context
      );
      const config = throwSigningPropertyError("config", signingProperties.config);
      const authScheme = (_c = (_b = (_a = context.endpointV2) == null ? void 0 : _a.properties) == null ? void 0 : _b.authSchemes) == null ? void 0 : _c[0];
      const signerFunction = throwSigningPropertyError(
        "signer",
        config.signer
      );
      const signer = await signerFunction(authScheme);
      const signingRegion = signingProperties == null ? void 0 : signingProperties.signingRegion;
      const signingName = signingProperties == null ? void 0 : signingProperties.signingName;
      return {
        config,
        signer,
        signingRegion,
        signingName
      };
    }, "validateSigningProperties");
    var _AwsSdkSigV4Signer = class _AwsSdkSigV4Signer {
      async sign(httpRequest, identity, signingProperties) {
        if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) {
          throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
        }
        const { config, signer, signingRegion, signingName } = await validateSigningProperties(signingProperties);
        const signedRequest = await signer.sign(httpRequest, {
          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);
        }
      }
    };
    __name(_AwsSdkSigV4Signer, "AwsSdkSigV4Signer");
    var AwsSdkSigV4Signer = _AwsSdkSigV4Signer;
    var AWSSDKSigV4Signer = AwsSdkSigV4Signer;
    var import_core = require_dist_cjs34();
    var import_signature_v4 = require_dist_cjs36();
    var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => {
      let normalizedCreds;
      if (config.credentials) {
        normalizedCreds = (0, import_core.memoizeIdentityProvider)(config.credentials, import_core.isIdentityExpired, import_core.doesIdentityRequireRefresh);
      }
      if (!normalizedCreds) {
        if (config.credentialDefaultProvider) {
          normalizedCreds = (0, import_core.normalizeProvider)(
            config.credentialDefaultProvider(
              Object.assign({}, config, {
                parentClientConfig: config
              })
            )
          );
        } else {
          normalizedCreds = /* @__PURE__ */ __name(async () => {
            throw new Error("`credentials` is missing");
          }, "normalizedCreds");
        }
      }
      const {
        // Default for signingEscapePath
        signingEscapePath = true,
        // Default for systemClockOffset
        systemClockOffset = config.systemClockOffset || 0,
        // No default for sha256 since it is platform dependent
        sha256: sha2562
      } = config;
      let signer;
      if (config.signer) {
        signer = (0, import_core.normalizeProvider)(config.signer);
      } else if (config.regionInfoProvider) {
        signer = /* @__PURE__ */ __name(() => (0, import_core.normalizeProvider)(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: normalizedCreds,
            region: config.signingRegion,
            service: config.signingName,
            sha256: sha2562,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4;
          return new SignerCtor(params);
        }), "signer");
      } else {
        signer = /* @__PURE__ */ __name(async (authScheme) => {
          authScheme = Object.assign(
            {},
            {
              name: "sigv4",
              signingName: config.signingName || config.defaultSigningName,
              signingRegion: await (0, import_core.normalizeProvider)(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: normalizedCreds,
            region: config.signingRegion,
            service: config.signingName,
            sha256: sha2562,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4;
          return new SignerCtor(params);
        }, "signer");
      }
      return {
        ...config,
        systemClockOffset,
        signingEscapePath,
        credentials: normalizedCreds,
        signer
      };
    }, "resolveAwsSdkSigV4Config");
    var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/util.js
var require_util2 = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/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(string2, regex) {
      const matches = [];
      let match2 = regex.exec(string2);
      while (match2) {
        const allmatches = [];
        allmatches.startIndex = regex.lastIndex - match2[0].length;
        const len = match2.length;
        for (let index5 = 0; index5 < len; index5++) {
          allmatches.push(match2[index5]);
        }
        matches.push(allmatches);
        match2 = regex.exec(string2);
      }
      return matches;
    };
    var isName = function(string2) {
      const match2 = regexName.exec(string2);
      return !(match2 === null || typeof match2 === "undefined");
    };
    exports2.isExist = function(v) {
      return typeof v !== "undefined";
    };
    exports2.isEmptyObject = function(obj) {
      return Object.keys(obj).length === 0;
    };
    exports2.merge = function(target, a, arrayMode) {
      if (a) {
        const keys = Object.keys(a);
        const len = keys.length;
        for (let i2 = 0; i2 < len; i2++) {
          if (arrayMode === "strict") {
            target[keys[i2]] = [a[keys[i2]]];
          } else {
            target[keys[i2]] = a[keys[i2]];
          }
        }
      }
    };
    exports2.getValue = function(v) {
      if (exports2.isExist(v)) {
        return v;
      } else {
        return "";
      }
    };
    exports2.isName = isName;
    exports2.getAllMatches = getAllMatches;
    exports2.nameRegexp = nameRegexp;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/validator.js
var require_validator = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/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 i2 = 0; i2 < xmlData.length; i2++) {
        if (xmlData[i2] === "<" && xmlData[i2 + 1] === "?") {
          i2 += 2;
          i2 = readPI(xmlData, i2);
          if (i2.err)
            return i2;
        } else if (xmlData[i2] === "<") {
          let tagStartPos = i2;
          i2++;
          if (xmlData[i2] === "!") {
            i2 = readCommentAndCDATA(xmlData, i2);
            continue;
          } else {
            let closingTag = false;
            if (xmlData[i2] === "/") {
              closingTag = true;
              i2++;
            }
            let tagName = "";
            for (; i2 < xmlData.length && xmlData[i2] !== ">" && xmlData[i2] !== " " && xmlData[i2] !== "	" && xmlData[i2] !== "\n" && xmlData[i2] !== "\r"; i2++) {
              tagName += xmlData[i2];
            }
            tagName = tagName.trim();
            if (tagName[tagName.length - 1] === "/") {
              tagName = tagName.substring(0, tagName.length - 1);
              i2--;
            }
            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, i2));
            }
            const result = readAttributeStr(xmlData, i2);
            if (result === false) {
              return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i2));
            }
            let attrStr = result.value;
            i2 = result.index;
            if (attrStr[attrStr.length - 1] === "/") {
              const attrStrStart = i2 - 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, i2));
              } else if (attrStr.trim().length > 0) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", 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, i2 - attrStr.length + isValid2.err.line));
              }
              if (reachedRoot === true) {
                return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i2));
              } else if (options.unpairedTags.indexOf(tagName) !== -1) {
              } else {
                tags.push({ tagName, tagStartPos });
              }
              tagFound = true;
            }
            for (i2++; i2 < xmlData.length; i2++) {
              if (xmlData[i2] === "<") {
                if (xmlData[i2 + 1] === "!") {
                  i2++;
                  i2 = readCommentAndCDATA(xmlData, i2);
                  continue;
                } else if (xmlData[i2 + 1] === "?") {
                  i2 = readPI(xmlData, ++i2);
                  if (i2.err)
                    return i2;
                } else {
                  break;
                }
              } else if (xmlData[i2] === "&") {
                const afterAmp = validateAmpersand(xmlData, i2);
                if (afterAmp == -1)
                  return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i2));
                i2 = afterAmp;
              } else {
                if (reachedRoot === true && !isWhiteSpace(xmlData[i2])) {
                  return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i2));
                }
              }
            }
            if (xmlData[i2] === "<") {
              i2--;
            }
          }
        } else {
          if (isWhiteSpace(xmlData[i2])) {
            continue;
          }
          return getErrorObject("InvalidChar", "char '" + xmlData[i2] + "' is not expected.", getLineNumberForPosition(xmlData, i2));
        }
      }
      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((t2) => t2.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, i2) {
      const start = i2;
      for (; i2 < xmlData.length; i2++) {
        if (xmlData[i2] == "?" || xmlData[i2] == " ") {
          const tagname = xmlData.substr(start, i2 - start);
          if (i2 > 5 && tagname === "xml") {
            return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i2));
          } else if (xmlData[i2] == "?" && xmlData[i2 + 1] == ">") {
            i2++;
            break;
          } else {
            continue;
          }
        }
      }
      return i2;
    }
    function readCommentAndCDATA(xmlData, i2) {
      if (xmlData.length > i2 + 5 && xmlData[i2 + 1] === "-" && xmlData[i2 + 2] === "-") {
        for (i2 += 3; i2 < xmlData.length; i2++) {
          if (xmlData[i2] === "-" && xmlData[i2 + 1] === "-" && xmlData[i2 + 2] === ">") {
            i2 += 2;
            break;
          }
        }
      } else if (xmlData.length > i2 + 8 && xmlData[i2 + 1] === "D" && xmlData[i2 + 2] === "O" && xmlData[i2 + 3] === "C" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "Y" && xmlData[i2 + 6] === "P" && xmlData[i2 + 7] === "E") {
        let angleBracketsCount = 1;
        for (i2 += 8; i2 < xmlData.length; i2++) {
          if (xmlData[i2] === "<") {
            angleBracketsCount++;
          } else if (xmlData[i2] === ">") {
            angleBracketsCount--;
            if (angleBracketsCount === 0) {
              break;
            }
          }
        }
      } else if (xmlData.length > i2 + 9 && xmlData[i2 + 1] === "[" && xmlData[i2 + 2] === "C" && xmlData[i2 + 3] === "D" && xmlData[i2 + 4] === "A" && xmlData[i2 + 5] === "T" && xmlData[i2 + 6] === "A" && xmlData[i2 + 7] === "[") {
        for (i2 += 8; i2 < xmlData.length; i2++) {
          if (xmlData[i2] === "]" && xmlData[i2 + 1] === "]" && xmlData[i2 + 2] === ">") {
            i2 += 2;
            break;
          }
        }
      }
      return i2;
    }
    var doubleQuote = '"';
    var singleQuote = "'";
    function readAttributeStr(xmlData, i2) {
      let attrStr = "";
      let startChar = "";
      let tagClosed = false;
      for (; i2 < xmlData.length; i2++) {
        if (xmlData[i2] === doubleQuote || xmlData[i2] === singleQuote) {
          if (startChar === "") {
            startChar = xmlData[i2];
          } else if (startChar !== xmlData[i2]) {
          } else {
            startChar = "";
          }
        } else if (xmlData[i2] === ">") {
          if (startChar === "") {
            tagClosed = true;
            break;
          }
        }
        attrStr += xmlData[i2];
      }
      if (startChar !== "") {
        return false;
      }
      return {
        value: attrStr,
        index: i2,
        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 i2 = 0; i2 < matches.length; i2++) {
        if (matches[i2][1].length === 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i2][2] + "' has no space in starting.", getPositionFromMatch(matches[i2]));
        } else if (matches[i2][3] !== void 0 && matches[i2][4] === void 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i2][2] + "' is without value.", getPositionFromMatch(matches[i2]));
        } else if (matches[i2][3] === void 0 && !options.allowBooleanAttributes) {
          return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i2][2] + "' is not allowed.", getPositionFromMatch(matches[i2]));
        }
        const attrName = matches[i2][2];
        if (!validateAttrName(attrName)) {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i2]));
        }
        if (!attrNames.hasOwnProperty(attrName)) {
          attrNames[attrName] = 1;
        } else {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i2]));
        }
      }
      return true;
    }
    function validateNumberAmpersand(xmlData, i2) {
      let re = /\d/;
      if (xmlData[i2] === "x") {
        i2++;
        re = /[\da-fA-F]/;
      }
      for (; i2 < xmlData.length; i2++) {
        if (xmlData[i2] === ";")
          return i2;
        if (!xmlData[i2].match(re))
          break;
      }
      return -1;
    }
    function validateAmpersand(xmlData, i2) {
      i2++;
      if (xmlData[i2] === ";")
        return -1;
      if (xmlData[i2] === "#") {
        i2++;
        return validateNumberAmpersand(xmlData, i2);
      }
      let count = 0;
      for (; i2 < xmlData.length; i2++, count++) {
        if (xmlData[i2].match(/\w/) && count < 20)
          continue;
        if (xmlData[i2] === ";")
          break;
        return -1;
      }
      return i2;
    }
    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, index5) {
      const lines = xmlData.substring(0, index5).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.2.5/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
var require_OptionsBuilder = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) {
    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.2.5/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
var require_xmlNode = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/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.2.5/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
var require_DocTypeReader = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) {
    var util2 = require_util2();
    function readDocType(xmlData, i2) {
      const entities = {};
      if (xmlData[i2 + 3] === "O" && xmlData[i2 + 4] === "C" && xmlData[i2 + 5] === "T" && xmlData[i2 + 6] === "Y" && xmlData[i2 + 7] === "P" && xmlData[i2 + 8] === "E") {
        i2 = i2 + 9;
        let angleBracketsCount = 1;
        let hasBody = false, comment = false;
        let exp = "";
        for (; i2 < xmlData.length; i2++) {
          if (xmlData[i2] === "<" && !comment) {
            if (hasBody && isEntity(xmlData, i2)) {
              i2 += 7;
              [entityName, val, i2] = readEntityExp(xmlData, i2 + 1);
              if (val.indexOf("&") === -1)
                entities[validateEntityName(entityName)] = {
                  regx: RegExp(`&${entityName};`, "g"),
                  val
                };
            } else if (hasBody && isElement(xmlData, i2))
              i2 += 8;
            else if (hasBody && isAttlist(xmlData, i2))
              i2 += 8;
            else if (hasBody && isNotation(xmlData, i2))
              i2 += 9;
            else if (isComment)
              comment = true;
            else
              throw new Error("Invalid DOCTYPE");
            angleBracketsCount++;
            exp = "";
          } else if (xmlData[i2] === ">") {
            if (comment) {
              if (xmlData[i2 - 1] === "-" && xmlData[i2 - 2] === "-") {
                comment = false;
                angleBracketsCount--;
              }
            } else {
              angleBracketsCount--;
            }
            if (angleBracketsCount === 0) {
              break;
            }
          } else if (xmlData[i2] === "[") {
            hasBody = true;
          } else {
            exp += xmlData[i2];
          }
        }
        if (angleBracketsCount !== 0) {
          throw new Error(`Unclosed DOCTYPE`);
        }
      } else {
        throw new Error(`Invalid Tag instead of DOCTYPE`);
      }
      return { entities, i: i2 };
    }
    function readEntityExp(xmlData, i2) {
      let entityName2 = "";
      for (; i2 < xmlData.length && (xmlData[i2] !== "'" && xmlData[i2] !== '"'); i2++) {
        entityName2 += xmlData[i2];
      }
      entityName2 = entityName2.trim();
      if (entityName2.indexOf(" ") !== -1)
        throw new Error("External entites are not supported");
      const startChar = xmlData[i2++];
      let val2 = "";
      for (; i2 < xmlData.length && xmlData[i2] !== startChar; i2++) {
        val2 += xmlData[i2];
      }
      return [entityName2, val2, i2];
    }
    function isComment(xmlData, i2) {
      if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "-" && xmlData[i2 + 3] === "-")
        return true;
      return false;
    }
    function isEntity(xmlData, i2) {
      if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "E" && xmlData[i2 + 3] === "N" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "I" && xmlData[i2 + 6] === "T" && xmlData[i2 + 7] === "Y")
        return true;
      return false;
    }
    function isElement(xmlData, i2) {
      if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "E" && xmlData[i2 + 3] === "L" && xmlData[i2 + 4] === "E" && xmlData[i2 + 5] === "M" && xmlData[i2 + 6] === "E" && xmlData[i2 + 7] === "N" && xmlData[i2 + 8] === "T")
        return true;
      return false;
    }
    function isAttlist(xmlData, i2) {
      if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "A" && xmlData[i2 + 3] === "T" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "L" && xmlData[i2 + 6] === "I" && xmlData[i2 + 7] === "S" && xmlData[i2 + 8] === "T")
        return true;
      return false;
    }
    function isNotation(xmlData, i2) {
      if (xmlData[i2 + 1] === "!" && xmlData[i2 + 2] === "N" && xmlData[i2 + 3] === "O" && xmlData[i2 + 4] === "T" && xmlData[i2 + 5] === "A" && xmlData[i2 + 6] === "T" && xmlData[i2 + 7] === "I" && xmlData[i2 + 8] === "O" && xmlData[i2 + 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.0.5/node_modules/strnum/strnum.js
var require_strnum = __commonJS({
  "../node_modules/.pnpm/strnum@1.0.5/node_modules/strnum/strnum.js"(exports2, module2) {
    var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
    var numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
    if (!Number.parseInt && window.parseInt) {
      Number.parseInt = window.parseInt;
    }
    if (!Number.parseFloat && window.parseFloat) {
      Number.parseFloat = window.parseFloat;
    }
    var consider = {
      hex: true,
      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 (options.hex && hexRegex.test(trimmedStr)) {
        return Number.parseInt(trimmedStr, 16);
      } else {
        const match2 = numRegex.exec(trimmedStr);
        if (match2) {
          const sign = match2[1];
          const leadingZeros = match2[2];
          let numTrimmedByZeros = trimZeros(match2[3]);
          const eNotation = match2[4] || match2[6];
          if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".")
            return str;
          else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".")
            return str;
          else {
            const num = Number(trimmedStr);
            const numStr = "" + num;
            if (numStr.search(/[eE]/) !== -1) {
              if (options.eNotation)
                return num;
              else
                return str;
            } else if (eNotation) {
              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) {
              if (numTrimmedByZeros === numStr)
                return num;
              else if (sign + numTrimmedByZeros === numStr)
                return num;
              else
                return str;
            }
            if (trimmedStr === numStr)
              return num;
            else if (trimmedStr === sign + numStr)
              return num;
            return 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;
    }
    module2.exports = toNumber;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
var require_OrderedObjParser = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/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 regx = "<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)".replace(/NAME/g, util2.nameRegexp);
    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" }
        };
        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 i2 = 0; i2 < entKeys.length; i2++) {
        const ent = entKeys[i2];
        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 i2 = 0; i2 < len; i2++) {
          const attrName = this.resolveNameSpace(matches[i2][1]);
          let oldVal = matches[i2][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 i2 = 0; i2 < xmlData.length; i2++) {
        const ch = xmlData[i2];
        if (ch === "<") {
          if (xmlData[i2 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i2, "Closing Tag is not closed.");
            let tagName = xmlData.substring(i2 + 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 = "";
            i2 = closeIndex;
          } else if (xmlData[i2 + 1] === "?") {
            let tagData = readTagExp(xmlData, i2, 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);
            }
            i2 = tagData.closeIndex + 1;
          } else if (xmlData.substr(i2 + 1, 3) === "!--") {
            const endIndex = findClosingIndex(xmlData, "-->", i2 + 4, "Comment is not closed.");
            if (this.options.commentPropName) {
              const comment = xmlData.substring(i2 + 4, endIndex - 2);
              textData = this.saveTextToParentTag(textData, currentNode, jPath);
              currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
            }
            i2 = endIndex;
          } else if (xmlData.substr(i2 + 1, 2) === "!D") {
            const result = readDocType(xmlData, i2);
            this.docTypeEntities = result.entities;
            i2 = result.i;
          } else if (xmlData.substr(i2 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i2, "CDATA is not closed.") - 2;
            const tagExp = xmlData.substring(i2 + 9, closeIndex);
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            if (this.options.cdataPropName) {
              currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
            } else {
              let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true);
              if (val2 == void 0)
                val2 = "";
              currentNode.add(this.options.textNodeName, val2);
            }
            i2 = closeIndex + 2;
          } else {
            let result = readTagExp(xmlData, i2, this.options.removeNSPrefix);
            let tagName = result.tagName;
            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) {
                i2 = result.closeIndex;
              } else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
                i2 = result.closeIndex;
              } else {
                const result2 = this.readStopNodeData(xmlData, tagName, closeIndex + 1);
                if (!result2)
                  throw new Error(`Unexpected end of ${tagName}`);
                i2 = 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);
                  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 = "";
              i2 = closeIndex;
            }
          }
        } else {
          textData += xmlData[i2];
        }
      }
      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, i2, closingChar = ">") {
      let attrBoundary;
      let tagExp = "";
      for (let index5 = i2; index5 < xmlData.length; index5++) {
        let ch = xmlData[index5];
        if (attrBoundary) {
          if (ch === attrBoundary)
            attrBoundary = "";
        } else if (ch === '"' || ch === "'") {
          attrBoundary = ch;
        } else if (ch === closingChar[0]) {
          if (closingChar[1]) {
            if (xmlData[index5 + 1] === closingChar[1]) {
              return {
                data: tagExp,
                index: index5
              };
            }
          } else {
            return {
              data: tagExp,
              index: index5
            };
          }
        } else if (ch === "	") {
          ch = " ";
        }
        tagExp += ch;
      }
    }
    function findClosingIndex(xmlData, str, i2, errMsg) {
      const closingIndex = xmlData.indexOf(str, i2);
      if (closingIndex === -1) {
        throw new Error(errMsg);
      } else {
        return closingIndex + str.length - 1;
      }
    }
    function readTagExp(xmlData, i2, removeNSPrefix, closingChar = ">") {
      const result = tagExpWithClosingIndex(xmlData, i2 + 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.substr(0, separatorIndex).replace(/\s\s*$/, "");
        tagExp = tagExp.substr(separatorIndex + 1);
      }
      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
      };
    }
    function readStopNodeData(xmlData, tagName, i2) {
      const startIndex = i2;
      let openTagCount = 1;
      for (; i2 < xmlData.length; i2++) {
        if (xmlData[i2] === "<") {
          if (xmlData[i2 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i2, `${tagName} is not closed`);
            let closeTagName = xmlData.substring(i2 + 2, closeIndex).trim();
            if (closeTagName === tagName) {
              openTagCount--;
              if (openTagCount === 0) {
                return {
                  tagContent: xmlData.substring(startIndex, i2),
                  i: closeIndex
                };
              }
            }
            i2 = closeIndex;
          } else if (xmlData[i2 + 1] === "?") {
            const closeIndex = findClosingIndex(xmlData, "?>", i2 + 1, "StopNode is not closed.");
            i2 = closeIndex;
          } else if (xmlData.substr(i2 + 1, 3) === "!--") {
            const closeIndex = findClosingIndex(xmlData, "-->", i2 + 3, "StopNode is not closed.");
            i2 = closeIndex;
          } else if (xmlData.substr(i2 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i2, "StopNode is not closed.") - 2;
            i2 = closeIndex;
          } else {
            const tagData = readTagExp(xmlData, i2, ">");
            if (tagData) {
              const openTagName = tagData && tagData.tagName;
              if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
                openTagCount++;
              }
              i2 = 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.2.5/node_modules/fast-xml-parser/src/xmlparser/node2json.js
var require_node2json = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/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 i2 = 0; i2 < arr.length; i2++) {
        const tagObj = arr[i2];
        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 i2 = 0; i2 < keys.length; i2++) {
        const key = keys[i2];
        if (key !== ":@")
          return key;
      }
    }
    function assignAttributes(obj, attrMap, jpath, options) {
      if (attrMap) {
        const keys = Object.keys(attrMap);
        const len = keys.length;
        for (let i2 = 0; i2 < len; i2++) {
          const atrrName = keys[i2];
          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.2.5/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
var require_XMLParser = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) {
    var { buildOptions } = require_OptionsBuilder();
    var OrderedObjParser = require_OrderedObjParser();
    var { prettify } = require_node2json();
    var validator2 = require_validator();
    var XMLParser = 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 = XMLParser;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
var require_orderedJs2Xml = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) {
    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 i2 = 0; i2 < arr.length; i2++) {
        const tagObj = arr[i2];
        const tagName = propName(tagObj);
        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 i2 = 0; i2 < keys.length; i2++) {
        const key = keys[i2];
        if (key !== ":@")
          return key;
      }
    }
    function attr_to_str(attrMap, options) {
      let attrStr = "";
      if (attrMap && !options.ignoreAttributes) {
        for (let attr in attrMap) {
          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 index5 in options.stopNodes) {
        if (options.stopNodes[index5] === jPath || options.stopNodes[index5] === "*." + tagName)
          return true;
      }
      return false;
    }
    function replaceEntitiesValue(textValue, options) {
      if (textValue && textValue.length > 0 && options.processEntities) {
        for (let i2 = 0; i2 < options.entities.length; i2++) {
          const entity = options.entities[i2];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      }
      return textValue;
    }
    module2.exports = toXml;
  }
});

// ../node_modules/.pnpm/fast-xml-parser@4.2.5/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
var require_json2xml = __commonJS({
  "../node_modules/.pnpm/fast-xml-parser@4.2.5/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, a) {
        return a;
      },
      attributeValueProcessor: function(attrName, a) {
        return a;
      },
      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 (typeof jObj[key] === "undefined") {
        } else if (jObj[key] === null) {
          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 = "";
          for (let j = 0; j < arrLen; j++) {
            const item = jObj[key][j];
            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) {
                listTagVal += this.j2x(item, level + 1).val;
              } else {
                listTagVal += this.processTextOrObjNode(item, key, level);
              }
            } else {
              listTagVal += this.buildTextValNode(item, key, "", level);
            }
          }
          if (this.options.oneListGroup) {
            listTagVal = this.buildObjectNode(listTagVal, key, "", level);
          }
          val2 += listTagVal;
        } else {
          if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
            const Ks = Object.keys(jObj[key]);
            const L = Ks.length;
            for (let j = 0; j < L; j++) {
              attrStr += this.buildAttrPairStr(Ks[j], "" + jObj[key][Ks[j]]);
            }
          } 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 && 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 i2 = 0; i2 < this.options.entities.length; i2++) {
          const entity = this.options.entities[i2];
          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)) {
        return name.substr(this.attrPrefixLen);
      } else {
        return false;
      }
    }
    module2.exports = Builder;
  }
});

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

// ../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js
var require_protocols = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var protocols_exports = {};
    __export2(protocols_exports, {
      _toBool: () => _toBool,
      _toNum: () => _toNum,
      _toStr: () => _toStr,
      awsExpectUnion: () => awsExpectUnion,
      loadRestJsonErrorCode: () => loadRestJsonErrorCode,
      loadRestXmlErrorCode: () => loadRestXmlErrorCode,
      parseJsonBody: () => parseJsonBody,
      parseJsonErrorBody: () => parseJsonErrorBody,
      parseXmlBody: () => parseXmlBody,
      parseXmlErrorBody: () => parseXmlErrorBody
    });
    module2.exports = __toCommonJS2(protocols_exports);
    var _toStr = /* @__PURE__ */ __name((val2) => {
      if (val2 == null) {
        return val2;
      }
      if (typeof val2 === "number" || typeof val2 === "bigint") {
        const warning3 = new Error(`Received number ${val2} where a string was expected.`);
        warning3.name = "Warning";
        console.warn(warning3);
        return String(val2);
      }
      if (typeof val2 === "boolean") {
        const warning3 = new Error(`Received boolean ${val2} where a string was expected.`);
        warning3.name = "Warning";
        console.warn(warning3);
        return String(val2);
      }
      return val2;
    }, "_toStr");
    var _toBool = /* @__PURE__ */ __name((val2) => {
      if (val2 == null) {
        return val2;
      }
      if (typeof val2 === "number") {
      }
      if (typeof val2 === "string") {
        const lowercase = val2.toLowerCase();
        if (val2 !== "" && lowercase !== "false" && lowercase !== "true") {
          const warning3 = new Error(`Received string "${val2}" where a boolean was expected.`);
          warning3.name = "Warning";
          console.warn(warning3);
        }
        return val2 !== "" && lowercase !== "false";
      }
      return val2;
    }, "_toBool");
    var _toNum = /* @__PURE__ */ __name((val2) => {
      if (val2 == null) {
        return val2;
      }
      if (typeof val2 === "boolean") {
      }
      if (typeof val2 === "string") {
        const num = Number(val2);
        if (num.toString() !== val2) {
          const warning3 = new Error(`Received string "${val2}" where a number was expected.`);
          warning3.name = "Warning";
          console.warn(warning3);
          return val2;
        }
        return num;
      }
      return val2;
    }, "_toNum");
    var import_smithy_client = require_dist_cjs32();
    var awsExpectUnion = /* @__PURE__ */ __name((value) => {
      if (value == null) {
        return void 0;
      }
      if (typeof value === "object" && "__type" in value) {
        delete value.__type;
      }
      return (0, import_smithy_client.expectUnion)(value);
    }, "awsExpectUnion");
    var import_smithy_client2 = require_dist_cjs32();
    var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client2.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)), "collectBodyString");
    var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
      if (encoded.length) {
        try {
          return JSON.parse(encoded);
        } catch (e2) {
          if ((e2 == null ? void 0 : e2.name) === "SyntaxError") {
            Object.defineProperty(e2, "$responseBodyText", {
              value: encoded
            });
          }
          throw e2;
        }
      }
      return {};
    }), "parseJsonBody");
    var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => {
      const value = await parseJsonBody(errorBody, context);
      value.message = value.message ?? value.Message;
      return value;
    }, "parseJsonErrorBody");
    var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => {
      const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey");
      const sanitizeErrorCode = /* @__PURE__ */ __name((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;
      }, "sanitizeErrorCode");
      const headerKey = findKey(output.headers, "x-amzn-errortype");
      if (headerKey !== void 0) {
        return sanitizeErrorCode(output.headers[headerKey]);
      }
      if (data.code !== void 0) {
        return sanitizeErrorCode(data.code);
      }
      if (data["__type"] !== void 0) {
        return sanitizeErrorCode(data["__type"]);
      }
    }, "loadRestJsonErrorCode");
    var import_smithy_client3 = require_dist_cjs32();
    var import_fast_xml_parser = require_fxp();
    var parseXmlBody = /* @__PURE__ */ __name((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: (_2, 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 (e2) {
          if (e2 && typeof e2 === "object") {
            Object.defineProperty(e2, "$responseBodyText", {
              value: encoded
            });
          }
          throw e2;
        }
        const textNodeName = "#text";
        const key = Object.keys(parsedObj)[0];
        const parsedObjToReturn = parsedObj[key];
        if (parsedObjToReturn[textNodeName]) {
          parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
          delete parsedObjToReturn[textNodeName];
        }
        return (0, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn);
      }
      return {};
    }), "parseXmlBody");
    var parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => {
      const value = await parseXmlBody(errorBody, context);
      if (value.Error) {
        value.Error.message = value.Error.message ?? value.Error.Message;
      }
      return value;
    }, "parseXmlErrorBody");
    var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => {
      var _a;
      if (((_a = data == null ? void 0 : data.Error) == null ? void 0 : _a.Code) !== void 0) {
        return data.Error.Code;
      }
      if ((data == null ? void 0 : data.Code) !== void 0) {
        return data.Code;
      }
      if (output.statusCode == 404) {
        return "NotFound";
      }
    }, "loadRestXmlErrorCode");
  }
});

// ../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/index.js
var require_dist_cjs37 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+core@3.582.0/node_modules/@aws-sdk/core/dist-cjs/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    tslib_1.__exportStar(require_client(), exports2);
    tslib_1.__exportStar(require_httpAuthSchemes(), exports2);
    tslib_1.__exportStar(require_protocols(), exports2);
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/auth/httpAuthSchemeProvider.js
var require_httpAuthSchemeProvider = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthSchemeConfig = exports2.defaultRDSDataHttpAuthSchemeProvider = exports2.defaultRDSDataHttpAuthSchemeParametersProvider = void 0;
    var core_1 = require_dist_cjs37();
    var util_middleware_1 = require_dist_cjs10();
    var defaultRDSDataHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, util_middleware_1.getSmithyContext)(context).operation,
        region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    exports2.defaultRDSDataHttpAuthSchemeParametersProvider = defaultRDSDataHttpAuthSchemeParametersProvider;
    function createAwsAuthSigv4HttpAuthOption(authParameters) {
      return {
        schemeId: "aws.auth#sigv4",
        signingProperties: {
          name: "rds-data",
          region: authParameters.region
        },
        propertiesExtractor: (config, context) => ({
          signingProperties: {
            config,
            context
          }
        })
      };
    }
    var defaultRDSDataHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    exports2.defaultRDSDataHttpAuthSchemeProvider = defaultRDSDataHttpAuthSchemeProvider;
    var resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
      return {
        ...config_0
      };
    };
    exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
  }
});

// ../node_modules/.pnpm/tslib@2.6.2/node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports2 = {};
__export(tslib_es6_exports2, {
  __addDisposableResource: () => __addDisposableResource2,
  __assign: () => __assign2,
  __asyncDelegator: () => __asyncDelegator2,
  __asyncGenerator: () => __asyncGenerator2,
  __asyncValues: () => __asyncValues2,
  __await: () => __await2,
  __awaiter: () => __awaiter2,
  __classPrivateFieldGet: () => __classPrivateFieldGet3,
  __classPrivateFieldIn: () => __classPrivateFieldIn2,
  __classPrivateFieldSet: () => __classPrivateFieldSet3,
  __createBinding: () => __createBinding2,
  __decorate: () => __decorate2,
  __disposeResources: () => __disposeResources2,
  __esDecorate: () => __esDecorate2,
  __exportStar: () => __exportStar2,
  __extends: () => __extends2,
  __generator: () => __generator2,
  __importDefault: () => __importDefault2,
  __importStar: () => __importStar2,
  __makeTemplateObject: () => __makeTemplateObject2,
  __metadata: () => __metadata2,
  __param: () => __param2,
  __propKey: () => __propKey2,
  __read: () => __read2,
  __rest: () => __rest2,
  __runInitializers: () => __runInitializers2,
  __setFunctionName: () => __setFunctionName2,
  __spread: () => __spread2,
  __spreadArray: () => __spreadArray2,
  __spreadArrays: () => __spreadArrays2,
  __values: () => __values2,
  default: () => tslib_es6_default2
});
function __extends2(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics2(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest2(s2, e2) {
  var t2 = {};
  for (var p in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p) && e2.indexOf(p) < 0)
      t2[p] = s2[p];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i2 = 0, p = Object.getOwnPropertySymbols(s2); i2 < p.length; i2++) {
      if (e2.indexOf(p[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p[i2]))
        t2[p[i2]] = s2[p[i2]];
    }
  return t2;
}
function __decorate2(decorators, target, key, desc) {
  var c = arguments.length, r2 = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r2 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i2 = decorators.length - 1; i2 >= 0; i2--)
      if (d = decorators[i2])
        r2 = (c < 3 ? d(r2) : c > 3 ? d(target, key, r2) : d(target, key)) || r2;
  return c > 3 && r2 && Object.defineProperty(target, key, r2), r2;
}
function __param2(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate2(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f3) {
    if (f3 !== void 0 && typeof f3 !== "function")
      throw new TypeError("Function expected");
    return f3;
  }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _2, done = false;
  for (var i2 = decorators.length - 1; i2 >= 0; i2--) {
    var context = {};
    for (var p in contextIn)
      context[p] = p === "access" ? {} : contextIn[p];
    for (var p in contextIn.access)
      context.access[p] = contextIn.access[p];
    context.addInitializer = function(f3) {
      if (done)
        throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f3 || null));
    };
    var result = (0, decorators[i2])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind === "accessor") {
      if (result === void 0)
        continue;
      if (result === null || typeof result !== "object")
        throw new TypeError("Object expected");
      if (_2 = accept(result.get))
        descriptor.get = _2;
      if (_2 = accept(result.set))
        descriptor.set = _2;
      if (_2 = accept(result.init))
        initializers.unshift(_2);
    } else if (_2 = accept(result)) {
      if (kind === "field")
        initializers.unshift(_2);
      else
        descriptor[key] = _2;
    }
  }
  if (target)
    Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers2(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i2 = 0; i2 < initializers.length; i2++) {
    value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey2(x2) {
  return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName2(f3, name, prefix2) {
  if (typeof name === "symbol")
    name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f3, "name", { configurable: true, value: prefix2 ? "".concat(prefix2, " ", name) : name });
}
function __metadata2(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter2(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator2(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1)
      throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f3, y, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f3)
      throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2)
      try {
        if (f3 = 1, y && (t2 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t2 = y["return"]) && t2.call(y), 0) : y.next) && !(t2 = t2.call(y, op[1])).done)
          return t2;
        if (y = 0, t2)
          op = [op[0] & 2, t2.value];
        switch (op[0]) {
          case 0:
          case 1:
            t2 = op;
            break;
          case 4:
            _2.label++;
            return { value: op[1], done: false };
          case 5:
            _2.label++;
            y = op[1];
            op = [0];
            continue;
          case 7:
            op = _2.ops.pop();
            _2.trys.pop();
            continue;
          default:
            if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _2 = 0;
              continue;
            }
            if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
              _2.label = op[1];
              break;
            }
            if (op[0] === 6 && _2.label < t2[1]) {
              _2.label = t2[1];
              t2 = op;
              break;
            }
            if (t2 && _2.label < t2[2]) {
              _2.label = t2[2];
              _2.ops.push(op);
              break;
            }
            if (t2[2])
              _2.ops.pop();
            _2.trys.pop();
            continue;
        }
        op = body.call(thisArg, _2);
      } catch (e2) {
        op = [6, e2];
        y = 0;
      } finally {
        f3 = t2 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar2(m2, o) {
  for (var p in m2)
    if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
      __createBinding2(o, m2, p);
}
function __values2(o) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o[s2], i2 = 0;
  if (m2)
    return m2.call(o);
  if (o && typeof o.length === "number")
    return {
      next: function() {
        if (o && i2 >= o.length)
          o = void 0;
        return { value: o && o[i2++], done: !o };
      }
    };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read2(o, n) {
  var m2 = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m2)
    return o;
  var i2 = m2.call(o), r2, ar = [], e2;
  try {
    while ((n === void 0 || n-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error2) {
    e2 = { error: error2 };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread2() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read2(arguments[i2]));
  return ar;
}
function __spreadArrays2() {
  for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++)
    s2 += arguments[i2].length;
  for (var r2 = Array(s2), k = 0, i2 = 0; i2 < il; i2++)
    for (var a = arguments[i2], j = 0, jl = a.length; j < jl; j++, k++)
      r2[k] = a[j];
  return r2;
}
function __spreadArray2(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i2 = 0, l = from.length, ar; i2 < l; i2++) {
      if (ar || !(i2 in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i2);
        ar[i2] = from[i2];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await2(v) {
  return this instanceof __await2 ? (this.v = v, this) : new __await2(v);
}
function __asyncGenerator2(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i2, q = [];
  return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2;
  function verb(n) {
    if (g[n])
      i2[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e2) {
      settle(q[0][3], e2);
    }
  }
  function step(r2) {
    r2.value instanceof __await2 ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q[0][2], r2);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f3, v) {
    if (f3(v), q.shift(), q.length)
      resume(q[0][0], q[0][1]);
  }
}
function __asyncDelegator2(o) {
  var i2, p;
  return i2 = {}, verb("next"), verb("throw", function(e2) {
    throw e2;
  }), verb("return"), i2[Symbol.iterator] = function() {
    return this;
  }, i2;
  function verb(n, f3) {
    i2[n] = o[n] ? function(v) {
      return (p = !p) ? { value: __await2(o[n](v)), done: false } : f3 ? f3(v) : v;
    } : f3;
  }
}
function __asyncValues2(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m2 = o[Symbol.asyncIterator], i2;
  return m2 ? m2.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2);
  function verb(n) {
    i2[n] = o[n] && function(v) {
      return new Promise(function(resolve2, reject) {
        v = o[n](v), settle(resolve2, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve2, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve2({ value: v2, done: d });
    }, reject);
  }
}
function __makeTemplateObject2(cooked, raw2) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw2 });
  } else {
    cooked.raw = raw2;
  }
  return cooked;
}
function __importStar2(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k in mod)
      if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
        __createBinding2(result, mod, k);
  }
  __setModuleDefault2(result, mod);
  return result;
}
function __importDefault2(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet3(receiver, state, kind, f3) {
  if (kind === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet3(receiver, state, value, kind, f3) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldIn2(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function")
    throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource2(env3, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function")
      throw new TypeError("Object expected.");
    var dispose;
    if (async) {
      if (!Symbol.asyncDispose)
        throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose)
        throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
    }
    if (typeof dispose !== "function")
      throw new TypeError("Object not disposable.");
    env3.stack.push({ value, dispose, async });
  } else if (async) {
    env3.stack.push({ async: true });
  }
  return value;
}
function __disposeResources2(env3) {
  function fail(e2) {
    env3.error = env3.hasError ? new _SuppressedError2(e2, env3.error, "An error was suppressed during disposal.") : e2;
    env3.hasError = true;
  }
  function next() {
    while (env3.stack.length) {
      var rec = env3.stack.pop();
      try {
        var result = rec.dispose && rec.dispose.call(rec.value);
        if (rec.async)
          return Promise.resolve(result).then(next, function(e2) {
            fail(e2);
            return next();
          });
      } catch (e2) {
        fail(e2);
      }
    }
    if (env3.hasError)
      throw env3.error;
  }
  return next();
}
var extendStatics2, __assign2, __createBinding2, __setModuleDefault2, _SuppressedError2, tslib_es6_default2;
var init_tslib_es62 = __esm({
  "../node_modules/.pnpm/tslib@2.6.2/node_modules/tslib/tslib.es6.mjs"() {
    extendStatics2 = function(d, b) {
      extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2)
          if (Object.prototype.hasOwnProperty.call(b2, p))
            d2[p] = b2[p];
      };
      return extendStatics2(d, b);
    };
    __assign2 = function() {
      __assign2 = Object.assign || function __assign3(t2) {
        for (var s2, i2 = 1, n = arguments.length; i2 < n; i2++) {
          s2 = arguments[i2];
          for (var p in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p))
              t2[p] = s2[p];
        }
        return t2;
      };
      return __assign2.apply(this, arguments);
    };
    __createBinding2 = Object.create ? function(o, m2, k, k2) {
      if (k2 === void 0)
        k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m2, k, k2) {
      if (k2 === void 0)
        k2 = k;
      o[k2] = m2[k];
    };
    __setModuleDefault2 = Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    };
    _SuppressedError2 = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
      var e2 = new Error(message);
      return e2.name = "SuppressedError", e2.error = error2, e2.suppressed = suppressed, e2;
    };
    tslib_es6_default2 = {
      __extends: __extends2,
      __assign: __assign2,
      __rest: __rest2,
      __decorate: __decorate2,
      __param: __param2,
      __metadata: __metadata2,
      __awaiter: __awaiter2,
      __generator: __generator2,
      __createBinding: __createBinding2,
      __exportStar: __exportStar2,
      __values: __values2,
      __read: __read2,
      __spread: __spread2,
      __spreadArrays: __spreadArrays2,
      __spreadArray: __spreadArray2,
      __await: __await2,
      __asyncGenerator: __asyncGenerator2,
      __asyncDelegator: __asyncDelegator2,
      __asyncValues: __asyncValues2,
      __makeTemplateObject: __makeTemplateObject2,
      __importStar: __importStar2,
      __importDefault: __importDefault2,
      __classPrivateFieldGet: __classPrivateFieldGet3,
      __classPrivateFieldSet: __classPrivateFieldSet3,
      __classPrivateFieldIn: __classPrivateFieldIn2,
      __addDisposableResource: __addDisposableResource2,
      __disposeResources: __disposeResources2
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/package.json
var require_package2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/package.json"(exports2, module2) {
    module2.exports = {
      name: "@aws-sdk/client-rds-data",
      description: "AWS SDK for JavaScript Rds Data Client for Node.js, Browser and React Native",
      version: "3.583.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": "3.0.0",
        "@aws-crypto/sha256-js": "3.0.0",
        "@aws-sdk/client-sso-oidc": "3.583.0",
        "@aws-sdk/client-sts": "3.583.0",
        "@aws-sdk/core": "3.582.0",
        "@aws-sdk/credential-provider-node": "3.583.0",
        "@aws-sdk/middleware-host-header": "3.577.0",
        "@aws-sdk/middleware-logger": "3.577.0",
        "@aws-sdk/middleware-recursion-detection": "3.577.0",
        "@aws-sdk/middleware-user-agent": "3.583.0",
        "@aws-sdk/region-config-resolver": "3.577.0",
        "@aws-sdk/types": "3.577.0",
        "@aws-sdk/util-endpoints": "3.583.0",
        "@aws-sdk/util-user-agent-browser": "3.577.0",
        "@aws-sdk/util-user-agent-node": "3.577.0",
        "@smithy/config-resolver": "^3.0.0",
        "@smithy/core": "^2.0.1",
        "@smithy/fetch-http-handler": "^3.0.1",
        "@smithy/hash-node": "^3.0.0",
        "@smithy/invalid-dependency": "^3.0.0",
        "@smithy/middleware-content-length": "^3.0.0",
        "@smithy/middleware-endpoint": "^3.0.0",
        "@smithy/middleware-retry": "^3.0.1",
        "@smithy/middleware-serde": "^3.0.0",
        "@smithy/middleware-stack": "^3.0.0",
        "@smithy/node-config-provider": "^3.0.0",
        "@smithy/node-http-handler": "^3.0.0",
        "@smithy/protocol-http": "^4.0.0",
        "@smithy/smithy-client": "^3.0.1",
        "@smithy/types": "^3.0.0",
        "@smithy/url-parser": "^3.0.0",
        "@smithy/util-base64": "^3.0.0",
        "@smithy/util-body-length-browser": "^3.0.0",
        "@smithy/util-body-length-node": "^3.0.0",
        "@smithy/util-defaults-mode-browser": "^3.0.1",
        "@smithy/util-defaults-mode-node": "^3.0.1",
        "@smithy/util-endpoints": "^2.0.0",
        "@smithy/util-middleware": "^3.0.0",
        "@smithy/util-retry": "^3.0.0",
        "@smithy/util-utf8": "^3.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node16": "16.1.3",
        "@types/node": "^16.18.96",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~4.9.5"
      },
      engines: {
        node: ">=16.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.577.0/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js
var require_dist_cjs38 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.577.0/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE,
      ENV_EXPIRATION: () => ENV_EXPIRATION,
      ENV_KEY: () => ENV_KEY,
      ENV_SECRET: () => ENV_SECRET,
      ENV_SESSION: () => ENV_SESSION,
      fromEnv: () => fromEnv
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_property_provider = require_dist_cjs12();
    var ENV_KEY = "AWS_ACCESS_KEY_ID";
    var ENV_SECRET = "AWS_SECRET_ACCESS_KEY";
    var ENV_SESSION = "AWS_SESSION_TOKEN";
    var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION";
    var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE";
    var fromEnv = /* @__PURE__ */ __name((init2) => async () => {
      var _a;
      (_a = init2 == null ? void 0 : init2.logger) == null ? void 0 : _a.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];
      if (accessKeyId && secretAccessKey) {
        return {
          accessKeyId,
          secretAccessKey,
          ...sessionToken && { sessionToken },
          ...expiry && { expiration: new Date(expiry) },
          ...credentialScope && { credentialScope }
        };
      }
      throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.");
    }, "fromEnv");
  }
});

// ../node_modules/.pnpm/@smithy+credential-provider-imds@3.0.0/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js
var require_dist_cjs39 = __commonJS({
  "../node_modules/.pnpm/@smithy+credential-provider-imds@3.0.0/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      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
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_url8 = require("url");
    var import_property_provider = require_dist_cjs12();
    var import_buffer2 = require("buffer");
    var import_http3 = require("http");
    function httpRequest(options) {
      return new Promise((resolve2, reject) => {
        var _a;
        const req = (0, import_http3.request)({
          method: "GET",
          ...options,
          // Node.js http module doesn't accept hostname with square brackets
          // Refs: https://github.com/nodejs/node/issues/39738
          hostname: (_a = options.hostname) == null ? void 0 : _a.replace(/^\[(.+)\]$/, "$1")
        });
        req.on("error", (err2) => {
          reject(Object.assign(new import_property_provider.ProviderError("Unable to connect to instance metadata service"), err2));
          req.destroy();
        });
        req.on("timeout", () => {
          reject(new import_property_provider.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 import_property_provider.ProviderError("Error response received from instance metadata service"), { statusCode })
            );
            req.destroy();
          }
          const chunks = [];
          res.on("data", (chunk) => {
            chunks.push(chunk);
          });
          res.on("end", () => {
            resolve2(import_buffer2.Buffer.concat(chunks));
            req.destroy();
          });
        });
        req.end();
      });
    }
    __name(httpRequest, "httpRequest");
    var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials");
    var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({
      accessKeyId: creds.AccessKeyId,
      secretAccessKey: creds.SecretAccessKey,
      sessionToken: creds.Token,
      expiration: new Date(creds.Expiration)
    }), "fromImdsCredentials");
    var DEFAULT_TIMEOUT = 1e3;
    var DEFAULT_MAX_RETRIES = 0;
    var providerConfigFromInit = /* @__PURE__ */ __name(({
      maxRetries = DEFAULT_MAX_RETRIES,
      timeout = DEFAULT_TIMEOUT
    }) => ({ maxRetries, timeout }), "providerConfigFromInit");
    var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => {
      let promise = toRetry();
      for (let i2 = 0; i2 < maxRetries; i2++) {
        promise = promise.catch(toRetry);
      }
      return promise;
    }, "retry");
    var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
    var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
    var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
    var fromContainerMetadata = /* @__PURE__ */ __name((init2 = {}) => {
      const { timeout, maxRetries } = providerConfigFromInit(init2);
      return () => retry(async () => {
        const requestOptions = await getCmdsUri();
        const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));
        if (!isImdsCredentials(credsResponse)) {
          throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.");
        }
        return fromImdsCredentials(credsResponse);
      }, maxRetries);
    }, "fromContainerMetadata");
    var requestFromEcsImds = /* @__PURE__ */ __name(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();
    }, "requestFromEcsImds");
    var CMDS_IP = "169.254.170.2";
    var GREENGRASS_HOSTS = {
      localhost: true,
      "127.0.0.1": true
    };
    var GREENGRASS_PROTOCOLS = {
      "http:": true,
      "https:": true
    };
    var getCmdsUri = /* @__PURE__ */ __name(async () => {
      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 import_property_provider.CredentialsProviderError(
            `${parsed.hostname} is not a valid container metadata service hostname`,
            false
          );
        }
        if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {
          throw new import_property_provider.CredentialsProviderError(
            `${parsed.protocol} is not a valid container metadata service protocol`,
            false
          );
        }
        return {
          ...parsed,
          port: parsed.port ? parseInt(parsed.port, 10) : void 0
        };
      }
      throw new import_property_provider.CredentialsProviderError(
        `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`,
        false
      );
    }, "getCmdsUri");
    var _InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError2 extends import_property_provider.CredentialsProviderError {
      constructor(message, tryNextLink = true) {
        super(message, tryNextLink);
        this.tryNextLink = tryNextLink;
        this.name = "InstanceMetadataV1FallbackError";
        Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError2.prototype);
      }
    };
    __name(_InstanceMetadataV1FallbackError, "InstanceMetadataV1FallbackError");
    var InstanceMetadataV1FallbackError = _InstanceMetadataV1FallbackError;
    var import_node_config_provider = require_dist_cjs14();
    var import_url_parser = require_dist_cjs16();
    var Endpoint = /* @__PURE__ */ ((Endpoint2) => {
      Endpoint2["IPv4"] = "http://169.254.169.254";
      Endpoint2["IPv6"] = "http://[fd00:ec2::254]";
      return Endpoint2;
    })(Endpoint || {});
    var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
    var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint";
    var ENDPOINT_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => env3[ENV_ENDPOINT_NAME],
      configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],
      default: void 0
    };
    var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => {
      EndpointMode2["IPv4"] = "IPv4";
      EndpointMode2["IPv6"] = "IPv6";
      return EndpointMode2;
    })(EndpointMode || {});
    var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
    var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode";
    var ENDPOINT_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => env3[ENV_ENDPOINT_MODE_NAME],
      configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],
      default: "IPv4"
      /* IPv4 */
    };
    var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint");
    var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig");
    var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => {
      const endpointMode = await (0, import_node_config_provider.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)();
      switch (endpointMode) {
        case "IPv4":
          return "http://169.254.169.254";
        case "IPv6":
          return "http://[fd00:ec2::254]";
        default:
          throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`);
      }
    }, "getFromEndpointModeConfig");
    var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
    var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
    var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html";
    var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials2, logger) => {
      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);
      logger.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
      };
    }, "getExtendedInstanceMetadataCredentials");
    var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => {
      const logger = (options == null ? void 0 : options.logger) || console;
      let pastCredentials;
      return async () => {
        let credentials2;
        try {
          credentials2 = await provider();
          if (credentials2.expiration && credentials2.expiration.getTime() < Date.now()) {
            credentials2 = getExtendedInstanceMetadataCredentials(credentials2, logger);
          }
        } catch (e2) {
          if (pastCredentials) {
            logger.warn("Credential renew failed: ", e2);
            credentials2 = getExtendedInstanceMetadataCredentials(pastCredentials, logger);
          } else {
            throw e2;
          }
        }
        pastCredentials = credentials2;
        return credentials2;
      };
    }, "staticStabilityProvider");
    var IMDS_PATH = "/latest/meta-data/iam/security-credentials/";
    var IMDS_TOKEN_PATH = "/latest/api/token";
    var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED";
    var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled";
    var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token";
    var fromInstanceMetadata = /* @__PURE__ */ __name((init2 = {}) => staticStabilityProvider(getInstanceImdsProvider(init2), { logger: init2.logger }), "fromInstanceMetadata");
    var getInstanceImdsProvider = /* @__PURE__ */ __name((init2) => {
      let disableFetchToken = false;
      const { logger, profile } = init2;
      const { timeout, maxRetries } = providerConfigFromInit(init2);
      const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => {
        var _a;
        const isImdsV1Fallback = disableFetchToken || ((_a = options.headers) == null ? void 0 : _a[X_AWS_EC2_METADATA_TOKEN]) == null;
        if (isImdsV1Fallback) {
          let fallbackBlockedFromProfile = false;
          let fallbackBlockedFromProcessEnv = false;
          const configValue = await (0, import_node_config_provider.loadConfig)(
            {
              environmentVariableSelector: (env3) => {
                const envValue = env3[AWS_EC2_METADATA_V1_DISABLED];
                fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false";
                if (envValue === void 0) {
                  throw new import_property_provider.CredentialsProviderError(
                    `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`
                  );
                }
                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);
          } catch (err2) {
            if (err2.statusCode === 401) {
              disableFetchToken = false;
            }
            throw err2;
          }
          return creds;
        }, maxRetries2);
      }, "getCredentials");
      return async () => {
        const endpoint = await getInstanceMetadataEndpoint();
        if (disableFetchToken) {
          logger == null ? void 0 : logger.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
          return getCredentials(maxRetries, { ...endpoint, timeout });
        } else {
          let token;
          try {
            token = (await getMetadataToken({ ...endpoint, timeout })).toString();
          } catch (error2) {
            if ((error2 == null ? void 0 : 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;
            }
            logger == null ? void 0 : logger.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
            return getCredentials(maxRetries, { ...endpoint, timeout });
          }
          return getCredentials(maxRetries, {
            ...endpoint,
            headers: {
              [X_AWS_EC2_METADATA_TOKEN]: token
            },
            timeout
          });
        }
      };
    }, "getInstanceImdsProvider");
    var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({
      ...options,
      path: IMDS_TOKEN_PATH,
      method: "PUT",
      headers: {
        "x-aws-ec2-metadata-token-ttl-seconds": "21600"
      }
    }), "getMetadataToken");
    var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile");
    var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options) => {
      const credsResponse = JSON.parse(
        (await httpRequest({
          ...options,
          path: IMDS_PATH + profile
        })).toString()
      );
      if (!isImdsCredentials(credsResponse)) {
        throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.");
      }
      return fromImdsCredentials(credsResponse);
    }, "getCredentialsFromProfile");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js
var require_checkUrl = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.checkUrl = void 0;
    var property_provider_1 = require_dist_cjs12();
    var ECS_CONTAINER_HOST = "169.254.170.2";
    var EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
    var EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
    var checkUrl = (url) => {
      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 property_provider_1.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]`);
    };
    exports2.checkUrl = checkUrl;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js
var require_requestHelpers = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getCredentials = exports2.createGetRequest = void 0;
    var property_provider_1 = require_dist_cjs12();
    var protocol_http_1 = require_dist_cjs2();
    var smithy_client_1 = require_dist_cjs32();
    var util_stream_1 = require_dist_cjs31();
    function createGetRequest(url) {
      return new protocol_http_1.HttpRequest({
        protocol: url.protocol,
        hostname: url.hostname,
        port: Number(url.port),
        path: url.pathname,
        query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => {
          acc[k] = v;
          return acc;
        }, {}),
        fragment: url.hash
      });
    }
    exports2.createGetRequest = createGetRequest;
    async function getCredentials(response) {
      const contentType = (response == null ? void 0 : response.headers["content-type"]) ?? (response == null ? void 0 : response.headers["Content-Type"]) ?? "";
      if (!contentType.includes("json")) {
        console.warn("HTTP credential provider response header content-type was not application/json. Observed: " + contentType + ".");
      }
      const stream = (0, util_stream_1.sdkStreamMixin)(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 property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }");
        }
        return {
          accessKeyId: parsed.AccessKeyId,
          secretAccessKey: parsed.SecretAccessKey,
          sessionToken: parsed.Token,
          expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration)
        };
      }
      if (response.statusCode >= 400 && response.statusCode < 500) {
        let parsedBody = {};
        try {
          parsedBody = JSON.parse(str);
        } catch (e2) {
        }
        throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`), {
          Code: parsedBody.Code,
          Message: parsedBody.Message
        });
      }
      throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`);
    }
    exports2.getCredentials = getCredentials;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js
var require_retry_wrapper = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.retryWrapper = void 0;
    var retryWrapper = (toRetry, maxRetries, delayMs) => {
      return async () => {
        for (let i2 = 0; i2 < maxRetries; ++i2) {
          try {
            return await toRetry();
          } catch (e2) {
            await new Promise((resolve2) => setTimeout(resolve2, delayMs));
          }
        }
        return await toRetry();
      };
    };
    exports2.retryWrapper = retryWrapper;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js
var require_fromHttp = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromHttp = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var node_http_handler_1 = require_dist_cjs28();
    var property_provider_1 = require_dist_cjs12();
    var promises_1 = tslib_1.__importDefault(require("fs/promises"));
    var checkUrl_1 = require_checkUrl();
    var requestHelpers_1 = require_requestHelpers();
    var retry_wrapper_1 = require_retry_wrapper();
    var AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
    var DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2";
    var AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
    var AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
    var AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
    var fromHttp = (options) => {
      var _a;
      (_a = options.logger) == null ? void 0 : _a.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];
      if (relative && full) {
        console.warn("AWS SDK HTTP credentials provider:", "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.");
        console.warn("awsContainerCredentialsFullUri will take precedence.");
      }
      if (token && tokenFile) {
        console.warn("AWS SDK HTTP credentials provider:", "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.");
        console.warn("awsContainerAuthorizationToken will take precedence.");
      }
      if (full) {
        host = full;
      } else if (relative) {
        host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;
      } else {
        throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided.
Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`);
      }
      const url = new URL(host);
      (0, checkUrl_1.checkUrl)(url);
      const requestHandler = new node_http_handler_1.NodeHttpHandler({
        requestTimeout: options.timeout ?? 1e3,
        connectionTimeout: options.timeout ?? 1e3
      });
      return (0, retry_wrapper_1.retryWrapper)(async () => {
        const request = (0, requestHelpers_1.createGetRequest)(url);
        if (token) {
          request.headers.Authorization = token;
        } else if (tokenFile) {
          request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString();
        }
        try {
          const result = await requestHandler.handle(request);
          return (0, requestHelpers_1.getCredentials)(result.response);
        } catch (e2) {
          throw new property_provider_1.CredentialsProviderError(String(e2));
        }
      }, options.maxRetries ?? 3, options.timeout ?? 1e3);
    };
    exports2.fromHttp = fromHttp;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js
var require_dist_cjs40 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.582.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromHttp = void 0;
    var fromHttp_1 = require_fromHttp();
    Object.defineProperty(exports2, "fromHttp", { enumerable: true, get: function() {
      return fromHttp_1.fromHttp;
    } });
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js
var require_httpAuthSchemeProvider2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthSchemeConfig = exports2.defaultSSOHttpAuthSchemeProvider = exports2.defaultSSOHttpAuthSchemeParametersProvider = void 0;
    var core_1 = require_dist_cjs37();
    var util_middleware_1 = require_dist_cjs10();
    var defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, util_middleware_1.getSmithyContext)(context).operation,
        region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    exports2.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider;
    function createAwsAuthSigv4HttpAuthOption(authParameters) {
      return {
        schemeId: "aws.auth#sigv4",
        signingProperties: {
          name: "awsssoportal",
          region: authParameters.region
        },
        propertiesExtractor: (config, context) => ({
          signingProperties: {
            config,
            context
          }
        })
      };
    }
    function createSmithyApiNoAuthHttpAuthOption(authParameters) {
      return {
        schemeId: "smithy.api#noAuth"
      };
    }
    var defaultSSOHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "GetRoleCredentials": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "ListAccountRoles": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "ListAccounts": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "Logout": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    exports2.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider;
    var resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
      return {
        ...config_0
      };
    };
    exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/package.json
var require_package3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/package.json"(exports2, module2) {
    module2.exports = {
      name: "@aws-sdk/client-sso",
      description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
      version: "3.583.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": "3.0.0",
        "@aws-crypto/sha256-js": "3.0.0",
        "@aws-sdk/core": "3.582.0",
        "@aws-sdk/middleware-host-header": "3.577.0",
        "@aws-sdk/middleware-logger": "3.577.0",
        "@aws-sdk/middleware-recursion-detection": "3.577.0",
        "@aws-sdk/middleware-user-agent": "3.583.0",
        "@aws-sdk/region-config-resolver": "3.577.0",
        "@aws-sdk/types": "3.577.0",
        "@aws-sdk/util-endpoints": "3.583.0",
        "@aws-sdk/util-user-agent-browser": "3.577.0",
        "@aws-sdk/util-user-agent-node": "3.577.0",
        "@smithy/config-resolver": "^3.0.0",
        "@smithy/core": "^2.0.1",
        "@smithy/fetch-http-handler": "^3.0.1",
        "@smithy/hash-node": "^3.0.0",
        "@smithy/invalid-dependency": "^3.0.0",
        "@smithy/middleware-content-length": "^3.0.0",
        "@smithy/middleware-endpoint": "^3.0.0",
        "@smithy/middleware-retry": "^3.0.1",
        "@smithy/middleware-serde": "^3.0.0",
        "@smithy/middleware-stack": "^3.0.0",
        "@smithy/node-config-provider": "^3.0.0",
        "@smithy/node-http-handler": "^3.0.0",
        "@smithy/protocol-http": "^4.0.0",
        "@smithy/smithy-client": "^3.0.1",
        "@smithy/types": "^3.0.0",
        "@smithy/url-parser": "^3.0.0",
        "@smithy/util-base64": "^3.0.0",
        "@smithy/util-body-length-browser": "^3.0.0",
        "@smithy/util-body-length-node": "^3.0.0",
        "@smithy/util-defaults-mode-browser": "^3.0.1",
        "@smithy/util-defaults-mode-node": "^3.0.1",
        "@smithy/util-endpoints": "^2.0.0",
        "@smithy/util-middleware": "^3.0.0",
        "@smithy/util-retry": "^3.0.0",
        "@smithy/util-utf8": "^3.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node16": "16.1.3",
        "@types/node": "^16.18.96",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~4.9.5"
      },
      engines: {
        node: ">=16.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+util-user-agent-node@3.577.0/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js
var require_dist_cjs41 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.577.0/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME,
      UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME,
      crtAvailability: () => crtAvailability,
      defaultUserAgent: () => defaultUserAgent
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_node_config_provider = require_dist_cjs14();
    var import_os = require("os");
    var import_process = require("process");
    var crtAvailability = {
      isCrtAvailable: false
    };
    var isCrtAvailable = /* @__PURE__ */ __name(() => {
      if (crtAvailability.isCrtAvailable) {
        return ["md/crt-avail"];
      }
      return null;
    }, "isCrtAvailable");
    var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
    var UA_APP_ID_INI_NAME = "sdk-ua-app-id";
    var defaultUserAgent = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => {
      const sections = [
        // sdk-metadata
        ["aws-sdk-js", clientVersion],
        // ua-metadata
        ["ua", "2.0"],
        // os-metadata
        [`os/${(0, import_os.platform)()}`, (0, import_os.release)()],
        // language-metadata
        // ECMAScript edition doesn't matter in JS, so no version needed.
        ["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 appIdPromise = (0, import_node_config_provider.loadConfig)({
        environmentVariableSelector: (env22) => env22[UA_APP_ID_ENV_NAME],
        configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME],
        default: void 0
      })();
      let resolvedUserAgent = void 0;
      return async () => {
        if (!resolvedUserAgent) {
          const appId = await appIdPromise;
          resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];
        }
        return resolvedUserAgent;
      };
    }, "defaultUserAgent");
  }
});

// ../node_modules/.pnpm/@smithy+hash-node@3.0.0/node_modules/@smithy/hash-node/dist-cjs/index.js
var require_dist_cjs42 = __commonJS({
  "../node_modules/.pnpm/@smithy+hash-node@3.0.0/node_modules/@smithy/hash-node/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      Hash: () => Hash
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_buffer_from = require_dist_cjs23();
    var import_util_utf8 = require_dist_cjs24();
    var import_buffer2 = require("buffer");
    var import_crypto10 = require("crypto");
    var _Hash = class _Hash {
      constructor(algorithmIdentifier, secret) {
        this.algorithmIdentifier = algorithmIdentifier;
        this.secret = secret;
        this.reset();
      }
      update(toHash, encoding) {
        this.hash.update((0, import_util_utf8.toUint8Array)(castSourceData(toHash, encoding)));
      }
      digest() {
        return Promise.resolve(this.hash.digest());
      }
      reset() {
        this.hash = this.secret ? (0, import_crypto10.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto10.createHash)(this.algorithmIdentifier);
      }
    };
    __name(_Hash, "Hash");
    var Hash = _Hash;
    function castSourceData(toCast, encoding) {
      if (import_buffer2.Buffer.isBuffer(toCast)) {
        return toCast;
      }
      if (typeof toCast === "string") {
        return (0, import_util_buffer_from.fromString)(toCast, encoding);
      }
      if (ArrayBuffer.isView(toCast)) {
        return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength);
      }
      return (0, import_util_buffer_from.fromArrayBuffer)(toCast);
    }
    __name(castSourceData, "castSourceData");
  }
});

// ../node_modules/.pnpm/@smithy+util-body-length-node@3.0.0/node_modules/@smithy/util-body-length-node/dist-cjs/index.js
var require_dist_cjs43 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-body-length-node@3.0.0/node_modules/@smithy/util-body-length-node/dist-cjs/index.js"(exports2, module2) {
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      calculateBodyLength: () => calculateBodyLength
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_fs14 = require("fs");
    var calculateBodyLength = /* @__PURE__ */ __name((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_fs14.lstatSync)(body.path).size;
      } else if (typeof body.fd === "number") {
        return (0, import_fs14.fstatSync)(body.fd).size;
      }
      throw new Error(`Body Length computation failed for ${body}`);
    }, "calculateBodyLength");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js
var require_ruleset = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ruleSet = void 0;
    var u = "required";
    var v = "fn";
    var w = "argv";
    var x2 = "ref";
    var a = true;
    var b = "isSet";
    var c = "booleanEquals";
    var d = "error";
    var e2 = "endpoint";
    var f3 = "tree";
    var g = "PartitionResult";
    var h2 = "getAttr";
    var i2 = { [u]: false, "type": "String" };
    var j = { [u]: true, "default": false, "type": "Boolean" };
    var k = { [x2]: "Endpoint" };
    var l = { [v]: c, [w]: [{ [x2]: "UseFIPS" }, true] };
    var m2 = { [v]: c, [w]: [{ [x2]: "UseDualStack" }, true] };
    var n = {};
    var o = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
    var p = { [x2]: g };
    var q = { [v]: c, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
    var r2 = [l];
    var s2 = [m2];
    var t2 = [{ [x2]: "Region" }];
    var _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://portal.sso-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://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e2 }, { endpoint: { url: "https://portal.sso-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://portal.sso.{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://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }], type: f3 }, { error: "Invalid Configuration: Missing Region", type: d }] };
    exports2.ruleSet = _data;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js
var require_endpointResolver = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultEndpointResolver = void 0;
    var util_endpoints_1 = require_dist_cjs7();
    var util_endpoints_2 = require_dist_cjs6();
    var ruleset_1 = require_ruleset();
    var defaultEndpointResolver = (endpointParams, context = {}) => {
      return (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
        endpointParams,
        logger: context.logger
      });
    };
    exports2.defaultEndpointResolver = defaultEndpointResolver;
    util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js
var require_runtimeConfig_shared = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var core_1 = require_dist_cjs37();
    var core_2 = require_dist_cjs34();
    var smithy_client_1 = require_dist_cjs32();
    var url_parser_1 = require_dist_cjs16();
    var util_base64_1 = require_dist_cjs25();
    var util_utf8_1 = require_dist_cjs24();
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider2();
    var endpointResolver_1 = require_endpointResolver();
    var getRuntimeConfig = (config) => {
      return {
        apiVersion: "2019-06-10",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new core_1.AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new core_2.NoAuthSigner()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "SSO",
        urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.1/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js
var require_dist_cjs44 = __commonJS({
  "../node_modules/.pnpm/@smithy+util-defaults-mode-node@3.0.1/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js"(exports2, module2) {
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      resolveDefaultsModeConfig: () => resolveDefaultsModeConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_config_resolver = require_dist_cjs11();
    var import_node_config_provider = require_dist_cjs14();
    var import_property_provider = require_dist_cjs12();
    var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
    var AWS_REGION_ENV = "AWS_REGION";
    var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
    var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
    var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
    var IMDS_REGION_PATH = "/latest/meta-data/placement/region";
    var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
    var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
    var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => {
        return env3[AWS_DEFAULTS_MODE_ENV];
      },
      configFileSelector: (profile) => {
        return profile[AWS_DEFAULTS_MODE_CONFIG];
      },
      default: "legacy"
    };
    var resolveDefaultsModeConfig = /* @__PURE__ */ __name(({
      region = (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS),
      defaultsMode = (0, import_node_config_provider.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS)
    } = {}) => (0, import_property_provider.memoize)(async () => {
      const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
      switch (mode == null ? void 0 : mode.toLowerCase()) {
        case "auto":
          return resolveNodeDefaultsModeAuto(region);
        case "in-region":
        case "cross-region":
        case "mobile":
        case "standard":
        case "legacy":
          return Promise.resolve(mode == null ? void 0 : mode.toLocaleLowerCase());
        case void 0:
          return Promise.resolve("legacy");
        default:
          throw new Error(
            `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`
          );
      }
    }), "resolveDefaultsModeConfig");
    var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(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";
    }, "resolveNodeDefaultsModeAuto");
    var inferPhysicalRegion = /* @__PURE__ */ __name(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_DISABLED]) {
        try {
          const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM3(require_dist_cjs39()));
          const endpoint = await getInstanceMetadataEndpoint();
          return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString();
        } catch (e2) {
        }
      }
    }, "inferPhysicalRegion");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js
var require_runtimeConfig = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var package_json_1 = tslib_1.__importDefault(require_package3());
    var core_1 = require_dist_cjs37();
    var util_user_agent_node_1 = require_dist_cjs41();
    var config_resolver_1 = require_dist_cjs11();
    var hash_node_1 = require_dist_cjs42();
    var middleware_retry_1 = require_dist_cjs33();
    var node_config_provider_1 = require_dist_cjs14();
    var node_http_handler_1 = require_dist_cjs28();
    var util_body_length_node_1 = require_dist_cjs43();
    var util_retry_1 = require_dist_cjs20();
    var runtimeConfig_shared_1 = require_runtimeConfig_shared();
    var smithy_client_1 = require_dist_cjs32();
    var util_defaults_mode_node_1 = require_dist_cjs44();
    var smithy_client_2 = require_dist_cjs32();
    var getRuntimeConfig = (config) => {
      (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
      const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
      (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS),
        region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS),
        requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
          ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
        }),
        sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS)
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.577.0/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js
var require_dist_cjs45 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.577.0/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS,
      NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS,
      REGION_ENV_NAME: () => REGION_ENV_NAME,
      REGION_INI_NAME: () => REGION_INI_NAME,
      getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration,
      resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration,
      resolveRegionConfig: () => resolveRegionConfig
    });
    module2.exports = __toCommonJS2(src_exports);
    var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      let runtimeConfigRegion = /* @__PURE__ */ __name(async () => {
        if (runtimeConfig.region === void 0) {
          throw new Error("Region is missing from runtimeConfig");
        }
        const region = runtimeConfig.region;
        if (typeof region === "string") {
          return region;
        }
        return region();
      }, "runtimeConfigRegion");
      return {
        setRegion(region) {
          runtimeConfigRegion = region;
        },
        region() {
          return runtimeConfigRegion;
        }
      };
    }, "getAwsRegionExtensionConfiguration");
    var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => {
      return {
        region: awsRegionExtensionConfiguration.region()
      };
    }, "resolveAwsRegionExtensionConfiguration");
    var REGION_ENV_NAME = "AWS_REGION";
    var REGION_INI_NAME = "region";
    var NODE_REGION_CONFIG_OPTIONS = {
      environmentVariableSelector: (env3) => env3[REGION_ENV_NAME],
      configFileSelector: (profile) => profile[REGION_INI_NAME],
      default: () => {
        throw new Error("Region is missing");
      }
    };
    var NODE_REGION_CONFIG_FILE_OPTIONS = {
      preferredFile: "credentials"
    };
    var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion");
    var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion");
    var resolveRegionConfig = /* @__PURE__ */ __name((input) => {
      const { region, useFipsEndpoint } = input;
      if (!region) {
        throw new Error("Region is missing");
      }
      return {
        ...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();
        }
      };
    }, "resolveRegionConfig");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/index.js
var require_dist_cjs46 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso@3.583.0/node_modules/@aws-sdk/client-sso/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      GetRoleCredentialsCommand: () => GetRoleCredentialsCommand,
      GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog,
      GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog,
      InvalidRequestException: () => InvalidRequestException,
      ListAccountRolesCommand: () => ListAccountRolesCommand,
      ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog,
      ListAccountsCommand: () => ListAccountsCommand,
      ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog,
      LogoutCommand: () => LogoutCommand,
      LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog,
      ResourceNotFoundException: () => ResourceNotFoundException,
      RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog,
      SSO: () => SSO,
      SSOClient: () => SSOClient,
      SSOServiceException: () => SSOServiceException,
      TooManyRequestsException: () => TooManyRequestsException,
      UnauthorizedException: () => UnauthorizedException,
      __Client: () => import_smithy_client.Client,
      paginateListAccountRoles: () => paginateListAccountRoles,
      paginateListAccounts: () => paginateListAccounts
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_middleware_host_header = require_dist_cjs3();
    var import_middleware_logger = require_dist_cjs4();
    var import_middleware_recursion_detection = require_dist_cjs5();
    var import_middleware_user_agent = require_dist_cjs8();
    var import_config_resolver = require_dist_cjs11();
    var import_core = require_dist_cjs34();
    var import_middleware_content_length = require_dist_cjs35();
    var import_middleware_endpoint = require_dist_cjs18();
    var import_middleware_retry = require_dist_cjs33();
    var import_httpAuthSchemeProvider = require_httpAuthSchemeProvider2();
    var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => {
      return {
        ...options,
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "awsssoportal"
      };
    }, "resolveClientEndpointParameters");
    var commonParams = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
    var import_runtimeConfig = require_runtimeConfig();
    var import_region_config_resolver = require_dist_cjs45();
    var import_protocol_http = require_dist_cjs2();
    var import_smithy_client = require_dist_cjs32();
    var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index5 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index5 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index5, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    }, "getHttpAuthExtensionConfiguration");
    var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    }, "resolveHttpAuthRuntimeConfig");
    var asPartial = /* @__PURE__ */ __name((t2) => t2, "asPartial");
    var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
      const extensionConfiguration = {
        ...asPartial((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig)),
        ...asPartial(getHttpAuthExtensionConfiguration(runtimeConfig))
      };
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return {
        ...runtimeConfig,
        ...(0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
        ...(0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration),
        ...(0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
        ...resolveHttpAuthRuntimeConfig(extensionConfiguration)
      };
    }, "resolveRuntimeExtensions");
    var _SSOClient = class _SSOClient extends import_smithy_client.Client {
      constructor(...[configuration]) {
        const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {});
        const _config_1 = resolveClientEndpointParameters(_config_0);
        const _config_2 = (0, import_config_resolver.resolveRegionConfig)(_config_1);
        const _config_3 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_2);
        const _config_4 = (0, import_middleware_retry.resolveRetryConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_5);
        const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6);
        const _config_8 = resolveRuntimeExtensions(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        super(_config_8);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config));
        this.middlewareStack.use(
          (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
            httpAuthSchemeParametersProvider: this.getDefaultHttpAuthSchemeParametersProvider(),
            identityProviderConfigProvider: this.getIdentityProviderConfigProvider()
          })
        );
        this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config));
      }
      /**
       * Destroy underlying resources, like sockets. It's usually not necessary to do this.
       * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
       * Otherwise, sockets might stay open for quite a long time before the server terminates them.
       */
      destroy() {
        super.destroy();
      }
      getDefaultHttpAuthSchemeParametersProvider() {
        return import_httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider;
      }
      getIdentityProviderConfigProvider() {
        return async (config) => new import_core.DefaultIdentityProviderConfig({
          "aws.auth#sigv4": config.credentials
        });
      }
    };
    __name(_SSOClient, "SSOClient");
    var SSOClient = _SSOClient;
    var import_middleware_serde = require_dist_cjs17();
    var import_types = require_dist_cjs();
    var _SSOServiceException = class _SSOServiceException2 extends import_smithy_client.ServiceException {
      /**
       * @internal
       */
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _SSOServiceException2.prototype);
      }
    };
    __name(_SSOServiceException, "SSOServiceException");
    var SSOServiceException = _SSOServiceException;
    var _InvalidRequestException = class _InvalidRequestException2 extends SSOServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRequestException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidRequestException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidRequestException2.prototype);
      }
    };
    __name(_InvalidRequestException, "InvalidRequestException");
    var InvalidRequestException = _InvalidRequestException;
    var _ResourceNotFoundException = class _ResourceNotFoundException2 extends SSOServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ResourceNotFoundException",
          $fault: "client",
          ...opts
        });
        this.name = "ResourceNotFoundException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _ResourceNotFoundException2.prototype);
      }
    };
    __name(_ResourceNotFoundException, "ResourceNotFoundException");
    var ResourceNotFoundException = _ResourceNotFoundException;
    var _TooManyRequestsException = class _TooManyRequestsException2 extends SSOServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "TooManyRequestsException",
          $fault: "client",
          ...opts
        });
        this.name = "TooManyRequestsException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _TooManyRequestsException2.prototype);
      }
    };
    __name(_TooManyRequestsException, "TooManyRequestsException");
    var TooManyRequestsException = _TooManyRequestsException;
    var _UnauthorizedException = class _UnauthorizedException2 extends SSOServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnauthorizedException",
          $fault: "client",
          ...opts
        });
        this.name = "UnauthorizedException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _UnauthorizedException2.prototype);
      }
    };
    __name(_UnauthorizedException, "UnauthorizedException");
    var UnauthorizedException = _UnauthorizedException;
    var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING }
    }), "GetRoleCredentialsRequestFilterSensitiveLog");
    var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.secretAccessKey && { secretAccessKey: import_smithy_client.SENSITIVE_STRING },
      ...obj.sessionToken && { sessionToken: import_smithy_client.SENSITIVE_STRING }
    }), "RoleCredentialsFilterSensitiveLog");
    var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) }
    }), "GetRoleCredentialsResponseFilterSensitiveLog");
    var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING }
    }), "ListAccountRolesRequestFilterSensitiveLog");
    var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING }
    }), "ListAccountsRequestFilterSensitiveLog");
    var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING }
    }), "LogoutRequestFilterSensitiveLog");
    var import_core2 = require_dist_cjs37();
    var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = (0, import_smithy_client.map)({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b.bp("/federation/credentials");
      const query = (0, import_smithy_client.map)({
        [_rn]: [, (0, import_smithy_client.expectNonNull)(input[_rN], `roleName`)],
        [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)]
      });
      let body;
      b.m("GET").h(headers).q(query).b(body);
      return b.build();
    }, "se_GetRoleCredentialsCommand");
    var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = (0, import_smithy_client.map)({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b.bp("/assignment/roles");
      const query = (0, import_smithy_client.map)({
        [_nt]: [, input[_nT]],
        [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()],
        [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)]
      });
      let body;
      b.m("GET").h(headers).q(query).b(body);
      return b.build();
    }, "se_ListAccountRolesCommand");
    var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = (0, import_smithy_client.map)({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b.bp("/assignment/accounts");
      const query = (0, import_smithy_client.map)({
        [_nt]: [, input[_nT]],
        [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()]
      });
      let body;
      b.m("GET").h(headers).q(query).b(body);
      return b.build();
    }, "se_ListAccountsCommand");
    var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = (0, import_smithy_client.map)({}, isSerializableHeaderValue, {
        [_xasbt]: input[_aT]
      });
      b.bp("/logout");
      let body;
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_LogoutCommand");
    var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        roleCredentials: import_smithy_client._json
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_GetRoleCredentialsCommand");
    var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        nextToken: import_smithy_client.expectString,
        roleList: import_smithy_client._json
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ListAccountRolesCommand");
    var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        accountList: import_smithy_client._json,
        nextToken: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ListAccountsCommand");
    var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      await (0, import_smithy_client.collectBody)(output.body, context);
      return contents;
    }, "de_LogoutCommand");
    var de_CommandError = /* @__PURE__ */ __name(async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await (0, import_core2.parseJsonErrorBody)(output.body, context)
      };
      const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body);
      switch (errorCode) {
        case "InvalidRequestException":
        case "com.amazonaws.sso#InvalidRequestException":
          throw await de_InvalidRequestExceptionRes(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 throwDefaultError({
            output,
            parsedBody,
            errorCode
          });
      }
    }, "de_CommandError");
    var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOServiceException);
    var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRequestExceptionRes");
    var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new ResourceNotFoundException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ResourceNotFoundExceptionRes");
    var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new TooManyRequestsException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_TooManyRequestsExceptionRes");
    var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnauthorizedException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnauthorizedExceptionRes");
    var deserializeMetadata = /* @__PURE__ */ __name((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"]
    }), "deserializeMetadata");
    var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => value !== void 0 && value !== null && value !== "" && (!Object.getOwnPropertyNames(value).includes("length") || value.length != 0) && (!Object.getOwnPropertyNames(value).includes("size") || value.size != 0), "isSerializableHeaderValue");
    var _aI = "accountId";
    var _aT = "accessToken";
    var _ai = "account_id";
    var _mR = "maxResults";
    var _mr = "max_result";
    var _nT = "nextToken";
    var _nt = "next_token";
    var _rN = "roleName";
    var _rn = "role_name";
    var _xasbt = "x-amz-sso_bearer_token";
    var _GetRoleCredentialsCommand = class _GetRoleCredentialsCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() {
    };
    __name(_GetRoleCredentialsCommand, "GetRoleCredentialsCommand");
    var GetRoleCredentialsCommand = _GetRoleCredentialsCommand;
    var _ListAccountRolesCommand = class _ListAccountRolesCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() {
    };
    __name(_ListAccountRolesCommand, "ListAccountRolesCommand");
    var ListAccountRolesCommand = _ListAccountRolesCommand;
    var _ListAccountsCommand = class _ListAccountsCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() {
    };
    __name(_ListAccountsCommand, "ListAccountsCommand");
    var ListAccountsCommand = _ListAccountsCommand;
    var _LogoutCommand = class _LogoutCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() {
    };
    __name(_LogoutCommand, "LogoutCommand");
    var LogoutCommand = _LogoutCommand;
    var commands = {
      GetRoleCredentialsCommand,
      ListAccountRolesCommand,
      ListAccountsCommand,
      LogoutCommand
    };
    var _SSO = class _SSO extends SSOClient {
    };
    __name(_SSO, "SSO");
    var SSO = _SSO;
    (0, import_smithy_client.createAggregatedClient)(commands, SSO);
    var paginateListAccountRoles = (0, import_core.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults");
    var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/auth/httpAuthSchemeProvider.js
var require_httpAuthSchemeProvider3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthSchemeConfig = exports2.defaultSSOOIDCHttpAuthSchemeProvider = exports2.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0;
    var core_1 = require_dist_cjs37();
    var util_middleware_1 = require_dist_cjs10();
    var defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, util_middleware_1.getSmithyContext)(context).operation,
        region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    exports2.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider;
    function createAwsAuthSigv4HttpAuthOption(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 defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "CreateToken": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "RegisterClient": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "StartDeviceAuthorization": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    exports2.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider;
    var resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
      return {
        ...config_0
      };
    };
    exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/package.json
var require_package4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/package.json"(exports2, module2) {
    module2.exports = {
      name: "@aws-sdk/client-sso-oidc",
      description: "AWS SDK for JavaScript Sso Oidc Client for Node.js, Browser and React Native",
      version: "3.583.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-sso-oidc",
        "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-oidc"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "3.0.0",
        "@aws-crypto/sha256-js": "3.0.0",
        "@aws-sdk/client-sts": "3.583.0",
        "@aws-sdk/core": "3.582.0",
        "@aws-sdk/credential-provider-node": "3.583.0",
        "@aws-sdk/middleware-host-header": "3.577.0",
        "@aws-sdk/middleware-logger": "3.577.0",
        "@aws-sdk/middleware-recursion-detection": "3.577.0",
        "@aws-sdk/middleware-user-agent": "3.583.0",
        "@aws-sdk/region-config-resolver": "3.577.0",
        "@aws-sdk/types": "3.577.0",
        "@aws-sdk/util-endpoints": "3.583.0",
        "@aws-sdk/util-user-agent-browser": "3.577.0",
        "@aws-sdk/util-user-agent-node": "3.577.0",
        "@smithy/config-resolver": "^3.0.0",
        "@smithy/core": "^2.0.1",
        "@smithy/fetch-http-handler": "^3.0.1",
        "@smithy/hash-node": "^3.0.0",
        "@smithy/invalid-dependency": "^3.0.0",
        "@smithy/middleware-content-length": "^3.0.0",
        "@smithy/middleware-endpoint": "^3.0.0",
        "@smithy/middleware-retry": "^3.0.1",
        "@smithy/middleware-serde": "^3.0.0",
        "@smithy/middleware-stack": "^3.0.0",
        "@smithy/node-config-provider": "^3.0.0",
        "@smithy/node-http-handler": "^3.0.0",
        "@smithy/protocol-http": "^4.0.0",
        "@smithy/smithy-client": "^3.0.1",
        "@smithy/types": "^3.0.0",
        "@smithy/url-parser": "^3.0.0",
        "@smithy/util-base64": "^3.0.0",
        "@smithy/util-body-length-browser": "^3.0.0",
        "@smithy/util-body-length-node": "^3.0.0",
        "@smithy/util-defaults-mode-browser": "^3.0.1",
        "@smithy/util-defaults-mode-node": "^3.0.1",
        "@smithy/util-endpoints": "^2.0.0",
        "@smithy/util-middleware": "^3.0.0",
        "@smithy/util-retry": "^3.0.0",
        "@smithy/util-utf8": "^3.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node16": "16.1.3",
        "@types/node": "^16.18.96",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~4.9.5"
      },
      engines: {
        node: ">=16.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-oidc",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-sso-oidc"
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/ruleset.js
var require_ruleset2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/ruleset.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ruleSet = void 0;
    var u = "required";
    var v = "fn";
    var w = "argv";
    var x2 = "ref";
    var a = true;
    var b = "isSet";
    var c = "booleanEquals";
    var d = "error";
    var e2 = "endpoint";
    var f3 = "tree";
    var g = "PartitionResult";
    var h2 = "getAttr";
    var i2 = { [u]: false, "type": "String" };
    var j = { [u]: true, "default": false, "type": "Boolean" };
    var k = { [x2]: "Endpoint" };
    var l = { [v]: c, [w]: [{ [x2]: "UseFIPS" }, true] };
    var m2 = { [v]: c, [w]: [{ [x2]: "UseDualStack" }, true] };
    var n = {};
    var o = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
    var p = { [x2]: g };
    var q = { [v]: c, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
    var r2 = [l];
    var s2 = [m2];
    var t2 = [{ [x2]: "Region" }];
    var _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 }] };
    exports2.ruleSet = _data;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/endpointResolver.js
var require_endpointResolver2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/endpointResolver.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultEndpointResolver = void 0;
    var util_endpoints_1 = require_dist_cjs7();
    var util_endpoints_2 = require_dist_cjs6();
    var ruleset_1 = require_ruleset2();
    var defaultEndpointResolver = (endpointParams, context = {}) => {
      return (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
        endpointParams,
        logger: context.logger
      });
    };
    exports2.defaultEndpointResolver = defaultEndpointResolver;
    util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.shared.js
var require_runtimeConfig_shared2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var core_1 = require_dist_cjs37();
    var core_2 = require_dist_cjs34();
    var smithy_client_1 = require_dist_cjs32();
    var url_parser_1 = require_dist_cjs16();
    var util_base64_1 = require_dist_cjs25();
    var util_utf8_1 = require_dist_cjs24();
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider3();
    var endpointResolver_1 = require_endpointResolver2();
    var getRuntimeConfig = (config) => {
      return {
        apiVersion: "2019-06-10",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new core_1.AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new core_2.NoAuthSigner()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "SSO OIDC",
        urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.js
var require_runtimeConfig2 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var package_json_1 = tslib_1.__importDefault(require_package4());
    var core_1 = require_dist_cjs37();
    var credential_provider_node_1 = require_dist_cjs59();
    var util_user_agent_node_1 = require_dist_cjs41();
    var config_resolver_1 = require_dist_cjs11();
    var hash_node_1 = require_dist_cjs42();
    var middleware_retry_1 = require_dist_cjs33();
    var node_config_provider_1 = require_dist_cjs14();
    var node_http_handler_1 = require_dist_cjs28();
    var util_body_length_node_1 = require_dist_cjs43();
    var util_retry_1 = require_dist_cjs20();
    var runtimeConfig_shared_1 = require_runtimeConfig_shared2();
    var smithy_client_1 = require_dist_cjs32();
    var util_defaults_mode_node_1 = require_dist_cjs44();
    var smithy_client_2 = require_dist_cjs32();
    var getRuntimeConfig = (config) => {
      (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
      const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
      (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
        credentialDefaultProvider: (config == null ? void 0 : config.credentialDefaultProvider) ?? credential_provider_node_1.defaultProvider,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS),
        region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS),
        requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
          ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
        }),
        sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS)
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/index.js
var require_dist_cjs47 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AccessDeniedException: () => AccessDeniedException,
      AuthorizationPendingException: () => AuthorizationPendingException,
      CreateTokenCommand: () => CreateTokenCommand,
      CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog,
      CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog,
      CreateTokenWithIAMCommand: () => CreateTokenWithIAMCommand,
      CreateTokenWithIAMRequestFilterSensitiveLog: () => CreateTokenWithIAMRequestFilterSensitiveLog,
      CreateTokenWithIAMResponseFilterSensitiveLog: () => CreateTokenWithIAMResponseFilterSensitiveLog,
      ExpiredTokenException: () => ExpiredTokenException,
      InternalServerException: () => InternalServerException,
      InvalidClientException: () => InvalidClientException,
      InvalidClientMetadataException: () => InvalidClientMetadataException,
      InvalidGrantException: () => InvalidGrantException,
      InvalidRedirectUriException: () => InvalidRedirectUriException,
      InvalidRequestException: () => InvalidRequestException,
      InvalidRequestRegionException: () => InvalidRequestRegionException,
      InvalidScopeException: () => InvalidScopeException,
      RegisterClientCommand: () => RegisterClientCommand,
      RegisterClientResponseFilterSensitiveLog: () => RegisterClientResponseFilterSensitiveLog,
      SSOOIDC: () => SSOOIDC,
      SSOOIDCClient: () => SSOOIDCClient,
      SSOOIDCServiceException: () => SSOOIDCServiceException,
      SlowDownException: () => SlowDownException,
      StartDeviceAuthorizationCommand: () => StartDeviceAuthorizationCommand,
      StartDeviceAuthorizationRequestFilterSensitiveLog: () => StartDeviceAuthorizationRequestFilterSensitiveLog,
      UnauthorizedClientException: () => UnauthorizedClientException,
      UnsupportedGrantTypeException: () => UnsupportedGrantTypeException,
      __Client: () => import_smithy_client.Client
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_middleware_host_header = require_dist_cjs3();
    var import_middleware_logger = require_dist_cjs4();
    var import_middleware_recursion_detection = require_dist_cjs5();
    var import_middleware_user_agent = require_dist_cjs8();
    var import_config_resolver = require_dist_cjs11();
    var import_core = require_dist_cjs34();
    var import_middleware_content_length = require_dist_cjs35();
    var import_middleware_endpoint = require_dist_cjs18();
    var import_middleware_retry = require_dist_cjs33();
    var import_httpAuthSchemeProvider = require_httpAuthSchemeProvider3();
    var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => {
      return {
        ...options,
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "sso-oauth"
      };
    }, "resolveClientEndpointParameters");
    var commonParams = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
    var import_runtimeConfig = require_runtimeConfig2();
    var import_region_config_resolver = require_dist_cjs45();
    var import_protocol_http = require_dist_cjs2();
    var import_smithy_client = require_dist_cjs32();
    var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index5 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index5 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index5, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    }, "getHttpAuthExtensionConfiguration");
    var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    }, "resolveHttpAuthRuntimeConfig");
    var asPartial = /* @__PURE__ */ __name((t2) => t2, "asPartial");
    var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
      const extensionConfiguration = {
        ...asPartial((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig)),
        ...asPartial(getHttpAuthExtensionConfiguration(runtimeConfig))
      };
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return {
        ...runtimeConfig,
        ...(0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
        ...(0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration),
        ...(0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
        ...resolveHttpAuthRuntimeConfig(extensionConfiguration)
      };
    }, "resolveRuntimeExtensions");
    var _SSOOIDCClient = class _SSOOIDCClient extends import_smithy_client.Client {
      constructor(...[configuration]) {
        const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {});
        const _config_1 = resolveClientEndpointParameters(_config_0);
        const _config_2 = (0, import_config_resolver.resolveRegionConfig)(_config_1);
        const _config_3 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_2);
        const _config_4 = (0, import_middleware_retry.resolveRetryConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_5);
        const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6);
        const _config_8 = resolveRuntimeExtensions(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        super(_config_8);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config));
        this.middlewareStack.use(
          (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
            httpAuthSchemeParametersProvider: this.getDefaultHttpAuthSchemeParametersProvider(),
            identityProviderConfigProvider: this.getIdentityProviderConfigProvider()
          })
        );
        this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config));
      }
      /**
       * Destroy underlying resources, like sockets. It's usually not necessary to do this.
       * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
       * Otherwise, sockets might stay open for quite a long time before the server terminates them.
       */
      destroy() {
        super.destroy();
      }
      getDefaultHttpAuthSchemeParametersProvider() {
        return import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider;
      }
      getIdentityProviderConfigProvider() {
        return async (config) => new import_core.DefaultIdentityProviderConfig({
          "aws.auth#sigv4": config.credentials
        });
      }
    };
    __name(_SSOOIDCClient, "SSOOIDCClient");
    var SSOOIDCClient = _SSOOIDCClient;
    var import_middleware_serde = require_dist_cjs17();
    var import_types = require_dist_cjs();
    var _SSOOIDCServiceException = class _SSOOIDCServiceException2 extends import_smithy_client.ServiceException {
      /**
       * @internal
       */
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _SSOOIDCServiceException2.prototype);
      }
    };
    __name(_SSOOIDCServiceException, "SSOOIDCServiceException");
    var SSOOIDCServiceException = _SSOOIDCServiceException;
    var _AccessDeniedException = class _AccessDeniedException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "AccessDeniedException",
          $fault: "client",
          ...opts
        });
        this.name = "AccessDeniedException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _AccessDeniedException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_AccessDeniedException, "AccessDeniedException");
    var AccessDeniedException = _AccessDeniedException;
    var _AuthorizationPendingException = class _AuthorizationPendingException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "AuthorizationPendingException",
          $fault: "client",
          ...opts
        });
        this.name = "AuthorizationPendingException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _AuthorizationPendingException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_AuthorizationPendingException, "AuthorizationPendingException");
    var AuthorizationPendingException = _AuthorizationPendingException;
    var _ExpiredTokenException = class _ExpiredTokenException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        this.name = "ExpiredTokenException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _ExpiredTokenException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_ExpiredTokenException, "ExpiredTokenException");
    var ExpiredTokenException = _ExpiredTokenException;
    var _InternalServerException = class _InternalServerException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InternalServerException",
          $fault: "server",
          ...opts
        });
        this.name = "InternalServerException";
        this.$fault = "server";
        Object.setPrototypeOf(this, _InternalServerException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InternalServerException, "InternalServerException");
    var InternalServerException = _InternalServerException;
    var _InvalidClientException = class _InvalidClientException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidClientException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidClientException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidClientException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidClientException, "InvalidClientException");
    var InvalidClientException = _InvalidClientException;
    var _InvalidGrantException = class _InvalidGrantException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidGrantException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidGrantException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidGrantException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidGrantException, "InvalidGrantException");
    var InvalidGrantException = _InvalidGrantException;
    var _InvalidRequestException = class _InvalidRequestException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRequestException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidRequestException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidRequestException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidRequestException, "InvalidRequestException");
    var InvalidRequestException = _InvalidRequestException;
    var _InvalidScopeException = class _InvalidScopeException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidScopeException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidScopeException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidScopeException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidScopeException, "InvalidScopeException");
    var InvalidScopeException = _InvalidScopeException;
    var _SlowDownException = class _SlowDownException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "SlowDownException",
          $fault: "client",
          ...opts
        });
        this.name = "SlowDownException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _SlowDownException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_SlowDownException, "SlowDownException");
    var SlowDownException = _SlowDownException;
    var _UnauthorizedClientException = class _UnauthorizedClientException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnauthorizedClientException",
          $fault: "client",
          ...opts
        });
        this.name = "UnauthorizedClientException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _UnauthorizedClientException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_UnauthorizedClientException, "UnauthorizedClientException");
    var UnauthorizedClientException = _UnauthorizedClientException;
    var _UnsupportedGrantTypeException = class _UnsupportedGrantTypeException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnsupportedGrantTypeException",
          $fault: "client",
          ...opts
        });
        this.name = "UnsupportedGrantTypeException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _UnsupportedGrantTypeException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_UnsupportedGrantTypeException, "UnsupportedGrantTypeException");
    var UnsupportedGrantTypeException = _UnsupportedGrantTypeException;
    var _InvalidRequestRegionException = class _InvalidRequestRegionException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRequestRegionException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidRequestRegionException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidRequestRegionException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
        this.endpoint = opts.endpoint;
        this.region = opts.region;
      }
    };
    __name(_InvalidRequestRegionException, "InvalidRequestRegionException");
    var InvalidRequestRegionException = _InvalidRequestRegionException;
    var _InvalidClientMetadataException = class _InvalidClientMetadataException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidClientMetadataException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidClientMetadataException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidClientMetadataException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidClientMetadataException, "InvalidClientMetadataException");
    var InvalidClientMetadataException = _InvalidClientMetadataException;
    var _InvalidRedirectUriException = class _InvalidRedirectUriException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRedirectUriException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidRedirectUriException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidRedirectUriException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidRedirectUriException, "InvalidRedirectUriException");
    var InvalidRedirectUriException = _InvalidRedirectUriException;
    var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: import_smithy_client.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.codeVerifier && { codeVerifier: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenRequestFilterSensitiveLog");
    var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.idToken && { idToken: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenResponseFilterSensitiveLog");
    var CreateTokenWithIAMRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.assertion && { assertion: import_smithy_client.SENSITIVE_STRING },
      ...obj.subjectToken && { subjectToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.codeVerifier && { codeVerifier: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenWithIAMRequestFilterSensitiveLog");
    var CreateTokenWithIAMResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.idToken && { idToken: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenWithIAMResponseFilterSensitiveLog");
    var RegisterClientResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: import_smithy_client.SENSITIVE_STRING }
    }), "RegisterClientResponseFilterSensitiveLog");
    var StartDeviceAuthorizationRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: import_smithy_client.SENSITIVE_STRING }
    }), "StartDeviceAuthorizationRequestFilterSensitiveLog");
    var import_core2 = require_dist_cjs37();
    var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/token");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          clientId: [],
          clientSecret: [],
          code: [],
          codeVerifier: [],
          deviceCode: [],
          grantType: [],
          redirectUri: [],
          refreshToken: [],
          scope: (_2) => (0, import_smithy_client._json)(_2)
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_CreateTokenCommand");
    var se_CreateTokenWithIAMCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/token");
      const query = (0, import_smithy_client.map)({
        [_ai]: [, "t"]
      });
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          assertion: [],
          clientId: [],
          code: [],
          codeVerifier: [],
          grantType: [],
          redirectUri: [],
          refreshToken: [],
          requestedTokenType: [],
          scope: (_2) => (0, import_smithy_client._json)(_2),
          subjectToken: [],
          subjectTokenType: []
        })
      );
      b.m("POST").h(headers).q(query).b(body);
      return b.build();
    }, "se_CreateTokenWithIAMCommand");
    var se_RegisterClientCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/client/register");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          clientName: [],
          clientType: [],
          entitledApplicationArn: [],
          grantTypes: (_2) => (0, import_smithy_client._json)(_2),
          issuerUrl: [],
          redirectUris: (_2) => (0, import_smithy_client._json)(_2),
          scopes: (_2) => (0, import_smithy_client._json)(_2)
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_RegisterClientCommand");
    var se_StartDeviceAuthorizationCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/device_authorization");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          clientId: [],
          clientSecret: [],
          startUrl: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_StartDeviceAuthorizationCommand");
    var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        accessToken: import_smithy_client.expectString,
        expiresIn: import_smithy_client.expectInt32,
        idToken: import_smithy_client.expectString,
        refreshToken: import_smithy_client.expectString,
        tokenType: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_CreateTokenCommand");
    var de_CreateTokenWithIAMCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        accessToken: import_smithy_client.expectString,
        expiresIn: import_smithy_client.expectInt32,
        idToken: import_smithy_client.expectString,
        issuedTokenType: import_smithy_client.expectString,
        refreshToken: import_smithy_client.expectString,
        scope: import_smithy_client._json,
        tokenType: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_CreateTokenWithIAMCommand");
    var de_RegisterClientCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        authorizationEndpoint: import_smithy_client.expectString,
        clientId: import_smithy_client.expectString,
        clientIdIssuedAt: import_smithy_client.expectLong,
        clientSecret: import_smithy_client.expectString,
        clientSecretExpiresAt: import_smithy_client.expectLong,
        tokenEndpoint: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_RegisterClientCommand");
    var de_StartDeviceAuthorizationCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        deviceCode: import_smithy_client.expectString,
        expiresIn: import_smithy_client.expectInt32,
        interval: import_smithy_client.expectInt32,
        userCode: import_smithy_client.expectString,
        verificationUri: import_smithy_client.expectString,
        verificationUriComplete: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_StartDeviceAuthorizationCommand");
    var de_CommandError = /* @__PURE__ */ __name(async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await (0, import_core2.parseJsonErrorBody)(output.body, context)
      };
      const errorCode = (0, import_core2.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);
        case "InvalidRequestRegionException":
        case "com.amazonaws.ssooidc#InvalidRequestRegionException":
          throw await de_InvalidRequestRegionExceptionRes(parsedOutput, context);
        case "InvalidClientMetadataException":
        case "com.amazonaws.ssooidc#InvalidClientMetadataException":
          throw await de_InvalidClientMetadataExceptionRes(parsedOutput, context);
        case "InvalidRedirectUriException":
        case "com.amazonaws.ssooidc#InvalidRedirectUriException":
          throw await de_InvalidRedirectUriExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError({
            output,
            parsedBody,
            errorCode
          });
      }
    }, "de_CommandError");
    var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOOIDCServiceException);
    var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new AccessDeniedException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_AccessDeniedExceptionRes");
    var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new AuthorizationPendingException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_AuthorizationPendingExceptionRes");
    var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new ExpiredTokenException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ExpiredTokenExceptionRes");
    var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InternalServerException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InternalServerExceptionRes");
    var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidClientException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidClientExceptionRes");
    var de_InvalidClientMetadataExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidClientMetadataException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidClientMetadataExceptionRes");
    var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidGrantException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidGrantExceptionRes");
    var de_InvalidRedirectUriExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRedirectUriException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRedirectUriExceptionRes");
    var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRequestExceptionRes");
    var de_InvalidRequestRegionExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        endpoint: import_smithy_client.expectString,
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString,
        region: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestRegionException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRequestRegionExceptionRes");
    var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidScopeException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidScopeExceptionRes");
    var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new SlowDownException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_SlowDownExceptionRes");
    var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnauthorizedClientException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnauthorizedClientExceptionRes");
    var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnsupportedGrantTypeException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnsupportedGrantTypeExceptionRes");
    var deserializeMetadata = /* @__PURE__ */ __name((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"]
    }), "deserializeMetadata");
    var _ai = "aws_iam";
    var _CreateTokenCommand = class _CreateTokenCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() {
    };
    __name(_CreateTokenCommand, "CreateTokenCommand");
    var CreateTokenCommand = _CreateTokenCommand;
    var _CreateTokenWithIAMCommand = class _CreateTokenWithIAMCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "CreateTokenWithIAM", {}).n("SSOOIDCClient", "CreateTokenWithIAMCommand").f(CreateTokenWithIAMRequestFilterSensitiveLog, CreateTokenWithIAMResponseFilterSensitiveLog).ser(se_CreateTokenWithIAMCommand).de(de_CreateTokenWithIAMCommand).build() {
    };
    __name(_CreateTokenWithIAMCommand, "CreateTokenWithIAMCommand");
    var CreateTokenWithIAMCommand = _CreateTokenWithIAMCommand;
    var _RegisterClientCommand = class _RegisterClientCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "RegisterClient", {}).n("SSOOIDCClient", "RegisterClientCommand").f(void 0, RegisterClientResponseFilterSensitiveLog).ser(se_RegisterClientCommand).de(de_RegisterClientCommand).build() {
    };
    __name(_RegisterClientCommand, "RegisterClientCommand");
    var RegisterClientCommand = _RegisterClientCommand;
    var _StartDeviceAuthorizationCommand = class _StartDeviceAuthorizationCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "StartDeviceAuthorization", {}).n("SSOOIDCClient", "StartDeviceAuthorizationCommand").f(StartDeviceAuthorizationRequestFilterSensitiveLog, void 0).ser(se_StartDeviceAuthorizationCommand).de(de_StartDeviceAuthorizationCommand).build() {
    };
    __name(_StartDeviceAuthorizationCommand, "StartDeviceAuthorizationCommand");
    var StartDeviceAuthorizationCommand = _StartDeviceAuthorizationCommand;
    var commands = {
      CreateTokenCommand,
      CreateTokenWithIAMCommand,
      RegisterClientCommand,
      StartDeviceAuthorizationCommand
    };
    var _SSOOIDC = class _SSOOIDC extends SSOOIDCClient {
    };
    __name(_SSOOIDC, "SSOOIDC");
    var SSOOIDC = _SSOOIDC;
    (0, import_smithy_client.createAggregatedClient)(commands, SSOOIDC);
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js
var require_dist_cjs48 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromSso: () => fromSso,
      fromStatic: () => fromStatic,
      nodeProvider: () => nodeProvider
    });
    module2.exports = __toCommonJS2(src_exports);
    var EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
    var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
    var ssoOidcClientsHash = {};
    var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion) => {
      const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM3(require_dist_cjs47()));
      if (ssoOidcClientsHash[ssoRegion]) {
        return ssoOidcClientsHash[ssoRegion];
      }
      const ssoOidcClient = new SSOOIDCClient({ region: ssoRegion });
      ssoOidcClientsHash[ssoRegion] = ssoOidcClient;
      return ssoOidcClient;
    }, "getSsoOidcClient");
    var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion) => {
      const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM3(require_dist_cjs47()));
      const ssoOidcClient = await getSsoOidcClient(ssoRegion);
      return ssoOidcClient.send(
        new CreateTokenCommand({
          clientId: ssoToken.clientId,
          clientSecret: ssoToken.clientSecret,
          refreshToken: ssoToken.refreshToken,
          grantType: "refresh_token"
        })
      );
    }, "getNewSsoOidcToken");
    var import_property_provider = require_dist_cjs12();
    var validateTokenExpiry = /* @__PURE__ */ __name((token) => {
      if (token.expiration && token.expiration.getTime() < Date.now()) {
        throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
      }
    }, "validateTokenExpiry");
    var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => {
      if (typeof value === "undefined") {
        throw new import_property_provider.TokenProviderError(
          `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`,
          false
        );
      }
    }, "validateTokenKey");
    var import_shared_ini_file_loader = require_dist_cjs13();
    var import_fs14 = require("fs");
    var { writeFile } = import_fs14.promises;
    var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => {
      const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id);
      const tokenString = JSON.stringify(ssoToken, null, 2);
      return writeFile(tokenFilepath, tokenString);
    }, "writeSSOTokenToFile");
    var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
    var fromSso = /* @__PURE__ */ __name((init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/token-providers", "fromSso");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      const profileName = (0, import_shared_ini_file_loader.getProfileName)(init2);
      const profile = profiles[profileName];
      if (!profile) {
        throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
      } else if (!profile["sso_session"]) {
        throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
      }
      const ssoSessionName = profile["sso_session"];
      const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init2);
      const ssoSession = ssoSessions[ssoSessionName];
      if (!ssoSession) {
        throw new import_property_provider.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 import_property_provider.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 (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName);
      } catch (e2) {
        throw new import_property_provider.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);
        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;
      }
    }, "fromSso");
    var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => {
      logger == null ? void 0 : logger.debug("@aws-sdk/token-providers", "fromStatic");
      if (!token || !token.token) {
        throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false);
      }
      return token;
    }, "fromStatic");
    var nodeProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider.memoize)(
      (0, import_property_provider.chain)(fromSso(init2), async () => {
        throw new import_property_provider.TokenProviderError("Could not load token from any providers", false);
      }),
      (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5,
      (token) => token.expiration !== void 0
    ), "nodeProvider");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js
var require_dist_cjs49 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __esm2 = (fn, res) => function __init() {
      return fn && (res = (0, fn[__getOwnPropNames3(fn)[0]])(fn = 0)), res;
    };
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var loadSso_exports = {};
    __export2(loadSso_exports, {
      GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand,
      SSOClient: () => import_client_sso.SSOClient
    });
    var import_client_sso;
    var init_loadSso = __esm2({
      "src/loadSso.ts"() {
        "use strict";
        import_client_sso = require_dist_cjs46();
      }
    });
    var src_exports = {};
    __export2(src_exports, {
      fromSSO: () => fromSSO,
      isSsoProfile: () => isSsoProfile,
      validateSsoProfile: () => validateSsoProfile
    });
    module2.exports = __toCommonJS2(src_exports);
    var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile");
    var import_token_providers = require_dist_cjs48();
    var import_property_provider = require_dist_cjs12();
    var import_shared_ini_file_loader = require_dist_cjs13();
    var SHOULD_FAIL_CREDENTIAL_CHAIN = false;
    var resolveSSOCredentials = /* @__PURE__ */ __name(async ({
      ssoStartUrl,
      ssoSession,
      ssoAccountId,
      ssoRegion,
      ssoRoleName,
      ssoClient,
      clientConfig,
      profile
    }) => {
      let token;
      const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
      if (ssoSession) {
        try {
          const _token = await (0, import_token_providers.fromSso)({ profile })();
          token = {
            accessToken: _token.token,
            expiresAt: new Date(_token.expiration).toISOString()
          };
        } catch (e2) {
          throw new import_property_provider.CredentialsProviderError(e2.message, SHOULD_FAIL_CREDENTIAL_CHAIN);
        }
      } else {
        try {
          token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl);
        } catch (e2) {
          throw new import_property_provider.CredentialsProviderError(
            `The SSO session associated with this profile is invalid. ${refreshMessage}`,
            SHOULD_FAIL_CREDENTIAL_CHAIN
          );
        }
      }
      if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
        throw new import_property_provider.CredentialsProviderError(
          `The SSO session associated with this profile has expired. ${refreshMessage}`,
          SHOULD_FAIL_CREDENTIAL_CHAIN
        );
      }
      const { accessToken } = token;
      const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports));
      const sso = ssoClient || new SSOClient2(
        Object.assign({}, clientConfig ?? {}, {
          region: (clientConfig == null ? void 0 : clientConfig.region) ?? ssoRegion
        })
      );
      let ssoResp;
      try {
        ssoResp = await sso.send(
          new GetRoleCredentialsCommand2({
            accountId: ssoAccountId,
            roleName: ssoRoleName,
            accessToken
          })
        );
      } catch (e2) {
        throw import_property_provider.CredentialsProviderError.from(e2, SHOULD_FAIL_CREDENTIAL_CHAIN);
      }
      const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope } = {} } = ssoResp;
      if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
        throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", SHOULD_FAIL_CREDENTIAL_CHAIN);
      }
      return { accessKeyId, secretAccessKey, sessionToken, expiration: new Date(expiration), credentialScope };
    }, "resolveSSOCredentials");
    var validateSsoProfile = /* @__PURE__ */ __name((profile) => {
      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 import_property_provider.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`,
          false
        );
      }
      return profile;
    }, "validateSsoProfile");
    var fromSSO = /* @__PURE__ */ __name((init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-sso", "fromSSO");
      const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
      const { ssoClient } = init2;
      const profileName = (0, import_shared_ini_file_loader.getProfileName)(init2);
      if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
        const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
        const profile = profiles[profileName];
        if (!profile) {
          throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`);
        }
        if (!isSsoProfile(profile)) {
          throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`);
        }
        if (profile == null ? void 0 : profile.sso_session) {
          const ssoSessions = await (0, import_shared_ini_file_loader.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 import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, false);
          }
          if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
            throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, false);
          }
          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);
        return resolveSSOCredentials({
          ssoStartUrl: sso_start_url,
          ssoSession: sso_session,
          ssoAccountId: sso_account_id,
          ssoRegion: sso_region,
          ssoRoleName: sso_role_name,
          ssoClient,
          clientConfig: init2.clientConfig,
          profile: profileName
        });
      } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
        throw new import_property_provider.CredentialsProviderError(
          'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"'
        );
      } else {
        return resolveSSOCredentials({
          ssoStartUrl,
          ssoSession,
          ssoAccountId,
          ssoRegion,
          ssoRoleName,
          ssoClient,
          clientConfig: init2.clientConfig,
          profile: profileName
        });
      }
    }, "fromSSO");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js
var require_httpAuthSchemeProvider4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthSchemeConfig = exports2.resolveStsAuthConfig = exports2.defaultSTSHttpAuthSchemeProvider = exports2.defaultSTSHttpAuthSchemeParametersProvider = void 0;
    var core_1 = require_dist_cjs37();
    var util_middleware_1 = require_dist_cjs10();
    var STSClient_1 = require_STSClient();
    var defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, util_middleware_1.getSmithyContext)(context).operation,
        region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    exports2.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider;
    function createAwsAuthSigv4HttpAuthOption(authParameters) {
      return {
        schemeId: "aws.auth#sigv4",
        signingProperties: {
          name: "sts",
          region: authParameters.region
        },
        propertiesExtractor: (config, context) => ({
          signingProperties: {
            config,
            context
          }
        })
      };
    }
    function createSmithyApiNoAuthHttpAuthOption(authParameters) {
      return {
        schemeId: "smithy.api#noAuth"
      };
    }
    var defaultSTSHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "AssumeRoleWithSAML": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "AssumeRoleWithWebIdentity": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    exports2.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider;
    var resolveStsAuthConfig = (input) => ({
      ...input,
      stsClientCtor: STSClient_1.STSClient
    });
    exports2.resolveStsAuthConfig = resolveStsAuthConfig;
    var resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = (0, exports2.resolveStsAuthConfig)(config);
      const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0);
      return {
        ...config_1
      };
    };
    exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js
var require_EndpointParameters = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.commonParams = exports2.resolveClientEndpointParameters = void 0;
    var resolveClientEndpointParameters = (options) => {
      return {
        ...options,
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        useGlobalEndpoint: options.useGlobalEndpoint ?? false,
        defaultSigningName: "sts"
      };
    };
    exports2.resolveClientEndpointParameters = resolveClientEndpointParameters;
    exports2.commonParams = {
      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+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/package.json
var require_package5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/package.json"(exports2, module2) {
    module2.exports = {
      name: "@aws-sdk/client-sts",
      description: "AWS SDK for JavaScript Sts Client for Node.js, Browser and React Native",
      version: "3.583.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-sts",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "rimraf ./dist-types tsconfig.types.tsbuildinfo && 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 sts",
        test: "yarn test:unit",
        "test:unit": "jest"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "3.0.0",
        "@aws-crypto/sha256-js": "3.0.0",
        "@aws-sdk/client-sso-oidc": "3.583.0",
        "@aws-sdk/core": "3.582.0",
        "@aws-sdk/credential-provider-node": "3.583.0",
        "@aws-sdk/middleware-host-header": "3.577.0",
        "@aws-sdk/middleware-logger": "3.577.0",
        "@aws-sdk/middleware-recursion-detection": "3.577.0",
        "@aws-sdk/middleware-user-agent": "3.583.0",
        "@aws-sdk/region-config-resolver": "3.577.0",
        "@aws-sdk/types": "3.577.0",
        "@aws-sdk/util-endpoints": "3.583.0",
        "@aws-sdk/util-user-agent-browser": "3.577.0",
        "@aws-sdk/util-user-agent-node": "3.577.0",
        "@smithy/config-resolver": "^3.0.0",
        "@smithy/core": "^2.0.1",
        "@smithy/fetch-http-handler": "^3.0.1",
        "@smithy/hash-node": "^3.0.0",
        "@smithy/invalid-dependency": "^3.0.0",
        "@smithy/middleware-content-length": "^3.0.0",
        "@smithy/middleware-endpoint": "^3.0.0",
        "@smithy/middleware-retry": "^3.0.1",
        "@smithy/middleware-serde": "^3.0.0",
        "@smithy/middleware-stack": "^3.0.0",
        "@smithy/node-config-provider": "^3.0.0",
        "@smithy/node-http-handler": "^3.0.0",
        "@smithy/protocol-http": "^4.0.0",
        "@smithy/smithy-client": "^3.0.1",
        "@smithy/types": "^3.0.0",
        "@smithy/url-parser": "^3.0.0",
        "@smithy/util-base64": "^3.0.0",
        "@smithy/util-body-length-browser": "^3.0.0",
        "@smithy/util-body-length-node": "^3.0.0",
        "@smithy/util-defaults-mode-browser": "^3.0.1",
        "@smithy/util-defaults-mode-node": "^3.0.1",
        "@smithy/util-endpoints": "^2.0.0",
        "@smithy/util-middleware": "^3.0.0",
        "@smithy/util-retry": "^3.0.0",
        "@smithy/util-utf8": "^3.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node16": "16.1.3",
        "@types/node": "^16.18.96",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~4.9.5"
      },
      engines: {
        node: ">=16.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-sts",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-sts"
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/auth/httpAuthSchemeProvider.js
var require_httpAuthSchemeProvider5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthSchemeConfig = exports2.defaultSSOOIDCHttpAuthSchemeProvider = exports2.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0;
    var core_1 = require_dist_cjs37();
    var util_middleware_1 = require_dist_cjs10();
    var defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: (0, util_middleware_1.getSmithyContext)(context).operation,
        region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    exports2.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider;
    function createAwsAuthSigv4HttpAuthOption(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 defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "CreateToken": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "RegisterClient": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "StartDeviceAuthorization": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    exports2.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider;
    var resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
      return {
        ...config_0
      };
    };
    exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/package.json
var require_package6 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/package.json"(exports2, module2) {
    module2.exports = {
      name: "@aws-sdk/client-sso-oidc",
      description: "AWS SDK for JavaScript Sso Oidc Client for Node.js, Browser and React Native",
      version: "3.583.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-sso-oidc",
        "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-oidc"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "3.0.0",
        "@aws-crypto/sha256-js": "3.0.0",
        "@aws-sdk/client-sts": "3.583.0",
        "@aws-sdk/core": "3.582.0",
        "@aws-sdk/credential-provider-node": "3.583.0",
        "@aws-sdk/middleware-host-header": "3.577.0",
        "@aws-sdk/middleware-logger": "3.577.0",
        "@aws-sdk/middleware-recursion-detection": "3.577.0",
        "@aws-sdk/middleware-user-agent": "3.583.0",
        "@aws-sdk/region-config-resolver": "3.577.0",
        "@aws-sdk/types": "3.577.0",
        "@aws-sdk/util-endpoints": "3.583.0",
        "@aws-sdk/util-user-agent-browser": "3.577.0",
        "@aws-sdk/util-user-agent-node": "3.577.0",
        "@smithy/config-resolver": "^3.0.0",
        "@smithy/core": "^2.0.1",
        "@smithy/fetch-http-handler": "^3.0.1",
        "@smithy/hash-node": "^3.0.0",
        "@smithy/invalid-dependency": "^3.0.0",
        "@smithy/middleware-content-length": "^3.0.0",
        "@smithy/middleware-endpoint": "^3.0.0",
        "@smithy/middleware-retry": "^3.0.1",
        "@smithy/middleware-serde": "^3.0.0",
        "@smithy/middleware-stack": "^3.0.0",
        "@smithy/node-config-provider": "^3.0.0",
        "@smithy/node-http-handler": "^3.0.0",
        "@smithy/protocol-http": "^4.0.0",
        "@smithy/smithy-client": "^3.0.1",
        "@smithy/types": "^3.0.0",
        "@smithy/url-parser": "^3.0.0",
        "@smithy/util-base64": "^3.0.0",
        "@smithy/util-body-length-browser": "^3.0.0",
        "@smithy/util-body-length-node": "^3.0.0",
        "@smithy/util-defaults-mode-browser": "^3.0.1",
        "@smithy/util-defaults-mode-node": "^3.0.1",
        "@smithy/util-endpoints": "^2.0.0",
        "@smithy/util-middleware": "^3.0.0",
        "@smithy/util-retry": "^3.0.0",
        "@smithy/util-utf8": "^3.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node16": "16.1.3",
        "@types/node": "^16.18.96",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~4.9.5"
      },
      engines: {
        node: ">=16.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-oidc",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-sso-oidc"
      }
    };
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/ruleset.js
var require_ruleset3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/ruleset.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ruleSet = void 0;
    var u = "required";
    var v = "fn";
    var w = "argv";
    var x2 = "ref";
    var a = true;
    var b = "isSet";
    var c = "booleanEquals";
    var d = "error";
    var e2 = "endpoint";
    var f3 = "tree";
    var g = "PartitionResult";
    var h2 = "getAttr";
    var i2 = { [u]: false, "type": "String" };
    var j = { [u]: true, "default": false, "type": "Boolean" };
    var k = { [x2]: "Endpoint" };
    var l = { [v]: c, [w]: [{ [x2]: "UseFIPS" }, true] };
    var m2 = { [v]: c, [w]: [{ [x2]: "UseDualStack" }, true] };
    var n = {};
    var o = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
    var p = { [x2]: g };
    var q = { [v]: c, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
    var r2 = [l];
    var s2 = [m2];
    var t2 = [{ [x2]: "Region" }];
    var _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 }] };
    exports2.ruleSet = _data;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/endpointResolver.js
var require_endpointResolver3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/endpoint/endpointResolver.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultEndpointResolver = void 0;
    var util_endpoints_1 = require_dist_cjs7();
    var util_endpoints_2 = require_dist_cjs6();
    var ruleset_1 = require_ruleset3();
    var defaultEndpointResolver = (endpointParams, context = {}) => {
      return (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
        endpointParams,
        logger: context.logger
      });
    };
    exports2.defaultEndpointResolver = defaultEndpointResolver;
    util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.shared.js
var require_runtimeConfig_shared3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var core_1 = require_dist_cjs37();
    var core_2 = require_dist_cjs34();
    var smithy_client_1 = require_dist_cjs32();
    var url_parser_1 = require_dist_cjs16();
    var util_base64_1 = require_dist_cjs25();
    var util_utf8_1 = require_dist_cjs24();
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider5();
    var endpointResolver_1 = require_endpointResolver3();
    var getRuntimeConfig = (config) => {
      return {
        apiVersion: "2019-06-10",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new core_1.AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new core_2.NoAuthSigner()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "SSO OIDC",
        urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.js
var require_runtimeConfig3 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/runtimeConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var package_json_1 = tslib_1.__importDefault(require_package6());
    var core_1 = require_dist_cjs37();
    var credential_provider_node_1 = require_dist_cjs56();
    var util_user_agent_node_1 = require_dist_cjs41();
    var config_resolver_1 = require_dist_cjs11();
    var hash_node_1 = require_dist_cjs42();
    var middleware_retry_1 = require_dist_cjs33();
    var node_config_provider_1 = require_dist_cjs14();
    var node_http_handler_1 = require_dist_cjs28();
    var util_body_length_node_1 = require_dist_cjs43();
    var util_retry_1 = require_dist_cjs20();
    var runtimeConfig_shared_1 = require_runtimeConfig_shared3();
    var smithy_client_1 = require_dist_cjs32();
    var util_defaults_mode_node_1 = require_dist_cjs44();
    var smithy_client_2 = require_dist_cjs32();
    var getRuntimeConfig = (config) => {
      (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
      const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
      (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
        credentialDefaultProvider: (config == null ? void 0 : config.credentialDefaultProvider) ?? credential_provider_node_1.defaultProvider,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS),
        region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS),
        requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
          ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
        }),
        sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS)
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/index.js
var require_dist_cjs50 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sso-oidc/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AccessDeniedException: () => AccessDeniedException,
      AuthorizationPendingException: () => AuthorizationPendingException,
      CreateTokenCommand: () => CreateTokenCommand,
      CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog,
      CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog,
      CreateTokenWithIAMCommand: () => CreateTokenWithIAMCommand,
      CreateTokenWithIAMRequestFilterSensitiveLog: () => CreateTokenWithIAMRequestFilterSensitiveLog,
      CreateTokenWithIAMResponseFilterSensitiveLog: () => CreateTokenWithIAMResponseFilterSensitiveLog,
      ExpiredTokenException: () => ExpiredTokenException,
      InternalServerException: () => InternalServerException,
      InvalidClientException: () => InvalidClientException,
      InvalidClientMetadataException: () => InvalidClientMetadataException,
      InvalidGrantException: () => InvalidGrantException,
      InvalidRedirectUriException: () => InvalidRedirectUriException,
      InvalidRequestException: () => InvalidRequestException,
      InvalidRequestRegionException: () => InvalidRequestRegionException,
      InvalidScopeException: () => InvalidScopeException,
      RegisterClientCommand: () => RegisterClientCommand,
      RegisterClientResponseFilterSensitiveLog: () => RegisterClientResponseFilterSensitiveLog,
      SSOOIDC: () => SSOOIDC,
      SSOOIDCClient: () => SSOOIDCClient,
      SSOOIDCServiceException: () => SSOOIDCServiceException,
      SlowDownException: () => SlowDownException,
      StartDeviceAuthorizationCommand: () => StartDeviceAuthorizationCommand,
      StartDeviceAuthorizationRequestFilterSensitiveLog: () => StartDeviceAuthorizationRequestFilterSensitiveLog,
      UnauthorizedClientException: () => UnauthorizedClientException,
      UnsupportedGrantTypeException: () => UnsupportedGrantTypeException,
      __Client: () => import_smithy_client.Client
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_middleware_host_header = require_dist_cjs3();
    var import_middleware_logger = require_dist_cjs4();
    var import_middleware_recursion_detection = require_dist_cjs5();
    var import_middleware_user_agent = require_dist_cjs8();
    var import_config_resolver = require_dist_cjs11();
    var import_core = require_dist_cjs34();
    var import_middleware_content_length = require_dist_cjs35();
    var import_middleware_endpoint = require_dist_cjs18();
    var import_middleware_retry = require_dist_cjs33();
    var import_httpAuthSchemeProvider = require_httpAuthSchemeProvider5();
    var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => {
      return {
        ...options,
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "sso-oauth"
      };
    }, "resolveClientEndpointParameters");
    var commonParams = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
    var import_runtimeConfig = require_runtimeConfig3();
    var import_region_config_resolver = require_dist_cjs45();
    var import_protocol_http = require_dist_cjs2();
    var import_smithy_client = require_dist_cjs32();
    var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index5 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index5 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index5, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    }, "getHttpAuthExtensionConfiguration");
    var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    }, "resolveHttpAuthRuntimeConfig");
    var asPartial = /* @__PURE__ */ __name((t2) => t2, "asPartial");
    var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
      const extensionConfiguration = {
        ...asPartial((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig)),
        ...asPartial(getHttpAuthExtensionConfiguration(runtimeConfig))
      };
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return {
        ...runtimeConfig,
        ...(0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
        ...(0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration),
        ...(0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
        ...resolveHttpAuthRuntimeConfig(extensionConfiguration)
      };
    }, "resolveRuntimeExtensions");
    var _SSOOIDCClient = class _SSOOIDCClient extends import_smithy_client.Client {
      constructor(...[configuration]) {
        const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {});
        const _config_1 = resolveClientEndpointParameters(_config_0);
        const _config_2 = (0, import_config_resolver.resolveRegionConfig)(_config_1);
        const _config_3 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_2);
        const _config_4 = (0, import_middleware_retry.resolveRetryConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_5);
        const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6);
        const _config_8 = resolveRuntimeExtensions(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        super(_config_8);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config));
        this.middlewareStack.use(
          (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
            httpAuthSchemeParametersProvider: this.getDefaultHttpAuthSchemeParametersProvider(),
            identityProviderConfigProvider: this.getIdentityProviderConfigProvider()
          })
        );
        this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config));
      }
      /**
       * Destroy underlying resources, like sockets. It's usually not necessary to do this.
       * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
       * Otherwise, sockets might stay open for quite a long time before the server terminates them.
       */
      destroy() {
        super.destroy();
      }
      getDefaultHttpAuthSchemeParametersProvider() {
        return import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider;
      }
      getIdentityProviderConfigProvider() {
        return async (config) => new import_core.DefaultIdentityProviderConfig({
          "aws.auth#sigv4": config.credentials
        });
      }
    };
    __name(_SSOOIDCClient, "SSOOIDCClient");
    var SSOOIDCClient = _SSOOIDCClient;
    var import_middleware_serde = require_dist_cjs17();
    var import_types = require_dist_cjs();
    var _SSOOIDCServiceException = class _SSOOIDCServiceException2 extends import_smithy_client.ServiceException {
      /**
       * @internal
       */
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _SSOOIDCServiceException2.prototype);
      }
    };
    __name(_SSOOIDCServiceException, "SSOOIDCServiceException");
    var SSOOIDCServiceException = _SSOOIDCServiceException;
    var _AccessDeniedException = class _AccessDeniedException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "AccessDeniedException",
          $fault: "client",
          ...opts
        });
        this.name = "AccessDeniedException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _AccessDeniedException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_AccessDeniedException, "AccessDeniedException");
    var AccessDeniedException = _AccessDeniedException;
    var _AuthorizationPendingException = class _AuthorizationPendingException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "AuthorizationPendingException",
          $fault: "client",
          ...opts
        });
        this.name = "AuthorizationPendingException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _AuthorizationPendingException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_AuthorizationPendingException, "AuthorizationPendingException");
    var AuthorizationPendingException = _AuthorizationPendingException;
    var _ExpiredTokenException = class _ExpiredTokenException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        this.name = "ExpiredTokenException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _ExpiredTokenException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_ExpiredTokenException, "ExpiredTokenException");
    var ExpiredTokenException = _ExpiredTokenException;
    var _InternalServerException = class _InternalServerException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InternalServerException",
          $fault: "server",
          ...opts
        });
        this.name = "InternalServerException";
        this.$fault = "server";
        Object.setPrototypeOf(this, _InternalServerException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InternalServerException, "InternalServerException");
    var InternalServerException = _InternalServerException;
    var _InvalidClientException = class _InvalidClientException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidClientException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidClientException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidClientException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidClientException, "InvalidClientException");
    var InvalidClientException = _InvalidClientException;
    var _InvalidGrantException = class _InvalidGrantException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidGrantException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidGrantException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidGrantException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidGrantException, "InvalidGrantException");
    var InvalidGrantException = _InvalidGrantException;
    var _InvalidRequestException = class _InvalidRequestException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRequestException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidRequestException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidRequestException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidRequestException, "InvalidRequestException");
    var InvalidRequestException = _InvalidRequestException;
    var _InvalidScopeException = class _InvalidScopeException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidScopeException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidScopeException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidScopeException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidScopeException, "InvalidScopeException");
    var InvalidScopeException = _InvalidScopeException;
    var _SlowDownException = class _SlowDownException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "SlowDownException",
          $fault: "client",
          ...opts
        });
        this.name = "SlowDownException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _SlowDownException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_SlowDownException, "SlowDownException");
    var SlowDownException = _SlowDownException;
    var _UnauthorizedClientException = class _UnauthorizedClientException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnauthorizedClientException",
          $fault: "client",
          ...opts
        });
        this.name = "UnauthorizedClientException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _UnauthorizedClientException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_UnauthorizedClientException, "UnauthorizedClientException");
    var UnauthorizedClientException = _UnauthorizedClientException;
    var _UnsupportedGrantTypeException = class _UnsupportedGrantTypeException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnsupportedGrantTypeException",
          $fault: "client",
          ...opts
        });
        this.name = "UnsupportedGrantTypeException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _UnsupportedGrantTypeException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_UnsupportedGrantTypeException, "UnsupportedGrantTypeException");
    var UnsupportedGrantTypeException = _UnsupportedGrantTypeException;
    var _InvalidRequestRegionException = class _InvalidRequestRegionException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRequestRegionException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidRequestRegionException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidRequestRegionException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
        this.endpoint = opts.endpoint;
        this.region = opts.region;
      }
    };
    __name(_InvalidRequestRegionException, "InvalidRequestRegionException");
    var InvalidRequestRegionException = _InvalidRequestRegionException;
    var _InvalidClientMetadataException = class _InvalidClientMetadataException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidClientMetadataException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidClientMetadataException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidClientMetadataException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidClientMetadataException, "InvalidClientMetadataException");
    var InvalidClientMetadataException = _InvalidClientMetadataException;
    var _InvalidRedirectUriException = class _InvalidRedirectUriException2 extends SSOOIDCServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidRedirectUriException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidRedirectUriException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidRedirectUriException2.prototype);
        this.error = opts.error;
        this.error_description = opts.error_description;
      }
    };
    __name(_InvalidRedirectUriException, "InvalidRedirectUriException");
    var InvalidRedirectUriException = _InvalidRedirectUriException;
    var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: import_smithy_client.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.codeVerifier && { codeVerifier: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenRequestFilterSensitiveLog");
    var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.idToken && { idToken: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenResponseFilterSensitiveLog");
    var CreateTokenWithIAMRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.assertion && { assertion: import_smithy_client.SENSITIVE_STRING },
      ...obj.subjectToken && { subjectToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.codeVerifier && { codeVerifier: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenWithIAMRequestFilterSensitiveLog");
    var CreateTokenWithIAMResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.refreshToken && { refreshToken: import_smithy_client.SENSITIVE_STRING },
      ...obj.idToken && { idToken: import_smithy_client.SENSITIVE_STRING }
    }), "CreateTokenWithIAMResponseFilterSensitiveLog");
    var RegisterClientResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: import_smithy_client.SENSITIVE_STRING }
    }), "RegisterClientResponseFilterSensitiveLog");
    var StartDeviceAuthorizationRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.clientSecret && { clientSecret: import_smithy_client.SENSITIVE_STRING }
    }), "StartDeviceAuthorizationRequestFilterSensitiveLog");
    var import_core2 = require_dist_cjs37();
    var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/token");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          clientId: [],
          clientSecret: [],
          code: [],
          codeVerifier: [],
          deviceCode: [],
          grantType: [],
          redirectUri: [],
          refreshToken: [],
          scope: (_2) => (0, import_smithy_client._json)(_2)
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_CreateTokenCommand");
    var se_CreateTokenWithIAMCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/token");
      const query = (0, import_smithy_client.map)({
        [_ai]: [, "t"]
      });
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          assertion: [],
          clientId: [],
          code: [],
          codeVerifier: [],
          grantType: [],
          redirectUri: [],
          refreshToken: [],
          requestedTokenType: [],
          scope: (_2) => (0, import_smithy_client._json)(_2),
          subjectToken: [],
          subjectTokenType: []
        })
      );
      b.m("POST").h(headers).q(query).b(body);
      return b.build();
    }, "se_CreateTokenWithIAMCommand");
    var se_RegisterClientCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/client/register");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          clientName: [],
          clientType: [],
          entitledApplicationArn: [],
          grantTypes: (_2) => (0, import_smithy_client._json)(_2),
          issuerUrl: [],
          redirectUris: (_2) => (0, import_smithy_client._json)(_2),
          scopes: (_2) => (0, import_smithy_client._json)(_2)
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_RegisterClientCommand");
    var se_StartDeviceAuthorizationCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/device_authorization");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          clientId: [],
          clientSecret: [],
          startUrl: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_StartDeviceAuthorizationCommand");
    var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        accessToken: import_smithy_client.expectString,
        expiresIn: import_smithy_client.expectInt32,
        idToken: import_smithy_client.expectString,
        refreshToken: import_smithy_client.expectString,
        tokenType: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_CreateTokenCommand");
    var de_CreateTokenWithIAMCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        accessToken: import_smithy_client.expectString,
        expiresIn: import_smithy_client.expectInt32,
        idToken: import_smithy_client.expectString,
        issuedTokenType: import_smithy_client.expectString,
        refreshToken: import_smithy_client.expectString,
        scope: import_smithy_client._json,
        tokenType: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_CreateTokenWithIAMCommand");
    var de_RegisterClientCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        authorizationEndpoint: import_smithy_client.expectString,
        clientId: import_smithy_client.expectString,
        clientIdIssuedAt: import_smithy_client.expectLong,
        clientSecret: import_smithy_client.expectString,
        clientSecretExpiresAt: import_smithy_client.expectLong,
        tokenEndpoint: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_RegisterClientCommand");
    var de_StartDeviceAuthorizationCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        deviceCode: import_smithy_client.expectString,
        expiresIn: import_smithy_client.expectInt32,
        interval: import_smithy_client.expectInt32,
        userCode: import_smithy_client.expectString,
        verificationUri: import_smithy_client.expectString,
        verificationUriComplete: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_StartDeviceAuthorizationCommand");
    var de_CommandError = /* @__PURE__ */ __name(async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await (0, import_core2.parseJsonErrorBody)(output.body, context)
      };
      const errorCode = (0, import_core2.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);
        case "InvalidRequestRegionException":
        case "com.amazonaws.ssooidc#InvalidRequestRegionException":
          throw await de_InvalidRequestRegionExceptionRes(parsedOutput, context);
        case "InvalidClientMetadataException":
        case "com.amazonaws.ssooidc#InvalidClientMetadataException":
          throw await de_InvalidClientMetadataExceptionRes(parsedOutput, context);
        case "InvalidRedirectUriException":
        case "com.amazonaws.ssooidc#InvalidRedirectUriException":
          throw await de_InvalidRedirectUriExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError({
            output,
            parsedBody,
            errorCode
          });
      }
    }, "de_CommandError");
    var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOOIDCServiceException);
    var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new AccessDeniedException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_AccessDeniedExceptionRes");
    var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new AuthorizationPendingException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_AuthorizationPendingExceptionRes");
    var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new ExpiredTokenException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ExpiredTokenExceptionRes");
    var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InternalServerException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InternalServerExceptionRes");
    var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidClientException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidClientExceptionRes");
    var de_InvalidClientMetadataExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidClientMetadataException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidClientMetadataExceptionRes");
    var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidGrantException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidGrantExceptionRes");
    var de_InvalidRedirectUriExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRedirectUriException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRedirectUriExceptionRes");
    var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRequestExceptionRes");
    var de_InvalidRequestRegionExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        endpoint: import_smithy_client.expectString,
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString,
        region: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidRequestRegionException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidRequestRegionExceptionRes");
    var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidScopeException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidScopeExceptionRes");
    var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new SlowDownException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_SlowDownExceptionRes");
    var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnauthorizedClientException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnauthorizedClientExceptionRes");
    var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        error: import_smithy_client.expectString,
        error_description: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnsupportedGrantTypeException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnsupportedGrantTypeExceptionRes");
    var deserializeMetadata = /* @__PURE__ */ __name((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"]
    }), "deserializeMetadata");
    var _ai = "aws_iam";
    var _CreateTokenCommand = class _CreateTokenCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() {
    };
    __name(_CreateTokenCommand, "CreateTokenCommand");
    var CreateTokenCommand = _CreateTokenCommand;
    var _CreateTokenWithIAMCommand = class _CreateTokenWithIAMCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "CreateTokenWithIAM", {}).n("SSOOIDCClient", "CreateTokenWithIAMCommand").f(CreateTokenWithIAMRequestFilterSensitiveLog, CreateTokenWithIAMResponseFilterSensitiveLog).ser(se_CreateTokenWithIAMCommand).de(de_CreateTokenWithIAMCommand).build() {
    };
    __name(_CreateTokenWithIAMCommand, "CreateTokenWithIAMCommand");
    var CreateTokenWithIAMCommand = _CreateTokenWithIAMCommand;
    var _RegisterClientCommand = class _RegisterClientCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "RegisterClient", {}).n("SSOOIDCClient", "RegisterClientCommand").f(void 0, RegisterClientResponseFilterSensitiveLog).ser(se_RegisterClientCommand).de(de_RegisterClientCommand).build() {
    };
    __name(_RegisterClientCommand, "RegisterClientCommand");
    var RegisterClientCommand = _RegisterClientCommand;
    var _StartDeviceAuthorizationCommand = class _StartDeviceAuthorizationCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSSOOIDCService", "StartDeviceAuthorization", {}).n("SSOOIDCClient", "StartDeviceAuthorizationCommand").f(StartDeviceAuthorizationRequestFilterSensitiveLog, void 0).ser(se_StartDeviceAuthorizationCommand).de(de_StartDeviceAuthorizationCommand).build() {
    };
    __name(_StartDeviceAuthorizationCommand, "StartDeviceAuthorizationCommand");
    var StartDeviceAuthorizationCommand = _StartDeviceAuthorizationCommand;
    var commands = {
      CreateTokenCommand,
      CreateTokenWithIAMCommand,
      RegisterClientCommand,
      StartDeviceAuthorizationCommand
    };
    var _SSOOIDC = class _SSOOIDC extends SSOOIDCClient {
    };
    __name(_SSOOIDC, "SSOOIDC");
    var SSOOIDC = _SSOOIDC;
    (0, import_smithy_client.createAggregatedClient)(commands, SSOOIDC);
  }
});

// ../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/token-providers/dist-cjs/index.js
var require_dist_cjs51 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+token-providers@3.577.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromSso: () => fromSso,
      fromStatic: () => fromStatic,
      nodeProvider: () => nodeProvider
    });
    module2.exports = __toCommonJS2(src_exports);
    var EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
    var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
    var ssoOidcClientsHash = {};
    var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion) => {
      const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM3(require_dist_cjs50()));
      if (ssoOidcClientsHash[ssoRegion]) {
        return ssoOidcClientsHash[ssoRegion];
      }
      const ssoOidcClient = new SSOOIDCClient({ region: ssoRegion });
      ssoOidcClientsHash[ssoRegion] = ssoOidcClient;
      return ssoOidcClient;
    }, "getSsoOidcClient");
    var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion) => {
      const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM3(require_dist_cjs50()));
      const ssoOidcClient = await getSsoOidcClient(ssoRegion);
      return ssoOidcClient.send(
        new CreateTokenCommand({
          clientId: ssoToken.clientId,
          clientSecret: ssoToken.clientSecret,
          refreshToken: ssoToken.refreshToken,
          grantType: "refresh_token"
        })
      );
    }, "getNewSsoOidcToken");
    var import_property_provider = require_dist_cjs12();
    var validateTokenExpiry = /* @__PURE__ */ __name((token) => {
      if (token.expiration && token.expiration.getTime() < Date.now()) {
        throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
      }
    }, "validateTokenExpiry");
    var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => {
      if (typeof value === "undefined") {
        throw new import_property_provider.TokenProviderError(
          `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`,
          false
        );
      }
    }, "validateTokenKey");
    var import_shared_ini_file_loader = require_dist_cjs13();
    var import_fs14 = require("fs");
    var { writeFile } = import_fs14.promises;
    var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => {
      const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id);
      const tokenString = JSON.stringify(ssoToken, null, 2);
      return writeFile(tokenFilepath, tokenString);
    }, "writeSSOTokenToFile");
    var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
    var fromSso = /* @__PURE__ */ __name((init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/token-providers", "fromSso");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      const profileName = (0, import_shared_ini_file_loader.getProfileName)(init2);
      const profile = profiles[profileName];
      if (!profile) {
        throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
      } else if (!profile["sso_session"]) {
        throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
      }
      const ssoSessionName = profile["sso_session"];
      const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init2);
      const ssoSession = ssoSessions[ssoSessionName];
      if (!ssoSession) {
        throw new import_property_provider.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 import_property_provider.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 (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName);
      } catch (e2) {
        throw new import_property_provider.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);
        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;
      }
    }, "fromSso");
    var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => {
      logger == null ? void 0 : logger.debug("@aws-sdk/token-providers", "fromStatic");
      if (!token || !token.token) {
        throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false);
      }
      return token;
    }, "fromStatic");
    var nodeProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider.memoize)(
      (0, import_property_provider.chain)(fromSso(init2), async () => {
        throw new import_property_provider.TokenProviderError("Could not load token from any providers", false);
      }),
      (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5,
      (token) => token.expiration !== void 0
    ), "nodeProvider");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js
var require_dist_cjs52 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0_/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __esm2 = (fn, res) => function __init() {
      return fn && (res = (0, fn[__getOwnPropNames3(fn)[0]])(fn = 0)), res;
    };
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var loadSso_exports = {};
    __export2(loadSso_exports, {
      GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand,
      SSOClient: () => import_client_sso.SSOClient
    });
    var import_client_sso;
    var init_loadSso = __esm2({
      "src/loadSso.ts"() {
        "use strict";
        import_client_sso = require_dist_cjs46();
      }
    });
    var src_exports = {};
    __export2(src_exports, {
      fromSSO: () => fromSSO,
      isSsoProfile: () => isSsoProfile,
      validateSsoProfile: () => validateSsoProfile
    });
    module2.exports = __toCommonJS2(src_exports);
    var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile");
    var import_token_providers = require_dist_cjs51();
    var import_property_provider = require_dist_cjs12();
    var import_shared_ini_file_loader = require_dist_cjs13();
    var SHOULD_FAIL_CREDENTIAL_CHAIN = false;
    var resolveSSOCredentials = /* @__PURE__ */ __name(async ({
      ssoStartUrl,
      ssoSession,
      ssoAccountId,
      ssoRegion,
      ssoRoleName,
      ssoClient,
      clientConfig,
      profile
    }) => {
      let token;
      const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
      if (ssoSession) {
        try {
          const _token = await (0, import_token_providers.fromSso)({ profile })();
          token = {
            accessToken: _token.token,
            expiresAt: new Date(_token.expiration).toISOString()
          };
        } catch (e2) {
          throw new import_property_provider.CredentialsProviderError(e2.message, SHOULD_FAIL_CREDENTIAL_CHAIN);
        }
      } else {
        try {
          token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl);
        } catch (e2) {
          throw new import_property_provider.CredentialsProviderError(
            `The SSO session associated with this profile is invalid. ${refreshMessage}`,
            SHOULD_FAIL_CREDENTIAL_CHAIN
          );
        }
      }
      if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
        throw new import_property_provider.CredentialsProviderError(
          `The SSO session associated with this profile has expired. ${refreshMessage}`,
          SHOULD_FAIL_CREDENTIAL_CHAIN
        );
      }
      const { accessToken } = token;
      const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports));
      const sso = ssoClient || new SSOClient2(
        Object.assign({}, clientConfig ?? {}, {
          region: (clientConfig == null ? void 0 : clientConfig.region) ?? ssoRegion
        })
      );
      let ssoResp;
      try {
        ssoResp = await sso.send(
          new GetRoleCredentialsCommand2({
            accountId: ssoAccountId,
            roleName: ssoRoleName,
            accessToken
          })
        );
      } catch (e2) {
        throw import_property_provider.CredentialsProviderError.from(e2, SHOULD_FAIL_CREDENTIAL_CHAIN);
      }
      const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope } = {} } = ssoResp;
      if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
        throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", SHOULD_FAIL_CREDENTIAL_CHAIN);
      }
      return { accessKeyId, secretAccessKey, sessionToken, expiration: new Date(expiration), credentialScope };
    }, "resolveSSOCredentials");
    var validateSsoProfile = /* @__PURE__ */ __name((profile) => {
      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 import_property_provider.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`,
          false
        );
      }
      return profile;
    }, "validateSsoProfile");
    var fromSSO = /* @__PURE__ */ __name((init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-sso", "fromSSO");
      const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
      const { ssoClient } = init2;
      const profileName = (0, import_shared_ini_file_loader.getProfileName)(init2);
      if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
        const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
        const profile = profiles[profileName];
        if (!profile) {
          throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`);
        }
        if (!isSsoProfile(profile)) {
          throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`);
        }
        if (profile == null ? void 0 : profile.sso_session) {
          const ssoSessions = await (0, import_shared_ini_file_loader.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 import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, false);
          }
          if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
            throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, false);
          }
          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);
        return resolveSSOCredentials({
          ssoStartUrl: sso_start_url,
          ssoSession: sso_session,
          ssoAccountId: sso_account_id,
          ssoRegion: sso_region,
          ssoRoleName: sso_role_name,
          ssoClient,
          clientConfig: init2.clientConfig,
          profile: profileName
        });
      } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
        throw new import_property_provider.CredentialsProviderError(
          'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"'
        );
      } else {
        return resolveSSOCredentials({
          ssoStartUrl,
          ssoSession,
          ssoAccountId,
          ssoRegion,
          ssoRoleName,
          ssoClient,
          clientConfig: init2.clientConfig,
          profile: profileName
        });
      }
    }, "fromSSO");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.577.0/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js
var require_dist_cjs53 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.577.0/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromProcess: () => fromProcess
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_shared_ini_file_loader = require_dist_cjs13();
    var import_property_provider = require_dist_cjs12();
    var import_child_process = require("child_process");
    var import_util5 = require("util");
    var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data) => {
      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.`);
        }
      }
      return {
        accessKeyId: data.AccessKeyId,
        secretAccessKey: data.SecretAccessKey,
        ...data.SessionToken && { sessionToken: data.SessionToken },
        ...data.Expiration && { expiration: new Date(data.Expiration) },
        ...data.CredentialScope && { credentialScope: data.CredentialScope }
      };
    }, "getValidatedProcessCredentials");
    var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles) => {
      const profile = profiles[profileName];
      if (profiles[profileName]) {
        const credentialProcess = profile["credential_process"];
        if (credentialProcess !== void 0) {
          const execPromise = (0, import_util5.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);
          } catch (error2) {
            throw new import_property_provider.CredentialsProviderError(error2.message);
          }
        } else {
          throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`);
        }
      } else {
        throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`);
      }
    }, "resolveProcessCredentials");
    var fromProcess = /* @__PURE__ */ __name((init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-process", "fromProcess");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      return resolveProcessCredentials((0, import_shared_ini_file_loader.getProfileName)(init2), profiles);
    }, "fromProcess");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.577.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js
var require_fromWebToken = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.577.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js"(exports2) {
    "use strict";
    var __createBinding3 = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k, k2) {
      if (k2 === void 0)
        k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m2, k);
      if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m2[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m2, k, k2) {
      if (k2 === void 0)
        k2 = k;
      o[k2] = m2[k];
    });
    var __setModuleDefault3 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar3 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod)
          if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
            __createBinding3(result, mod, k);
      }
      __setModuleDefault3(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromWebToken = void 0;
    var fromWebToken2 = (init2) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-web-identity", "fromWebToken");
      const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy4, durationSeconds } = init2;
      let { roleAssumerWithWebIdentity } = init2;
      if (!roleAssumerWithWebIdentity) {
        const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar3(require_dist_cjs57()));
        roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({
          ...init2.clientConfig,
          credentialProviderLogger: init2.logger,
          parentClientConfig: init2.parentClientConfig
        }, init2.clientPlugins);
      }
      return roleAssumerWithWebIdentity({
        RoleArn: roleArn,
        RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
        WebIdentityToken: webIdentityToken,
        ProviderId: providerId,
        PolicyArns: policyArns,
        Policy: policy4,
        DurationSeconds: durationSeconds
      });
    };
    exports2.fromWebToken = fromWebToken2;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.577.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js
var require_fromTokenFile = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.577.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fromTokenFile = void 0;
    var property_provider_1 = require_dist_cjs12();
    var fs_1 = require("fs");
    var fromWebToken_1 = require_fromWebToken();
    var ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
    var ENV_ROLE_ARN = "AWS_ROLE_ARN";
    var ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
    var fromTokenFile2 = (init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-web-identity", "fromTokenFile");
      const webIdentityTokenFile = (init2 == null ? void 0 : init2.webIdentityTokenFile) ?? process.env[ENV_TOKEN_FILE];
      const roleArn = (init2 == null ? void 0 : init2.roleArn) ?? process.env[ENV_ROLE_ARN];
      const roleSessionName = (init2 == null ? void 0 : init2.roleSessionName) ?? process.env[ENV_ROLE_SESSION_NAME];
      if (!webIdentityTokenFile || !roleArn) {
        throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified");
      }
      return (0, fromWebToken_1.fromWebToken)({
        ...init2,
        webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }),
        roleArn,
        roleSessionName
      })();
    };
    exports2.fromTokenFile = fromTokenFile2;
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.577.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js
var require_dist_cjs54 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.577.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    module2.exports = __toCommonJS2(src_exports);
    __reExport(src_exports, require_fromTokenFile(), module2.exports);
    __reExport(src_exports, require_fromWebToken(), module2.exports);
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts_n4voux45fymjghrdt4o3r57x4m/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js
var require_dist_cjs55 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts_n4voux45fymjghrdt4o3r57x4m/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromIni: () => fromIni
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_shared_ini_file_loader = require_dist_cjs13();
    var import_property_provider = require_dist_cjs12();
    var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName) => {
      const sourceProvidersMap = {
        EcsContainer: (options) => Promise.resolve().then(() => __toESM3(require_dist_cjs39())).then(({ fromContainerMetadata }) => fromContainerMetadata(options)),
        Ec2InstanceMetadata: (options) => Promise.resolve().then(() => __toESM3(require_dist_cjs39())).then(({ fromInstanceMetadata }) => fromInstanceMetadata(options)),
        Environment: (options) => Promise.resolve().then(() => __toESM3(require_dist_cjs38())).then(({ fromEnv }) => fromEnv(options))
      };
      if (credentialSource in sourceProvidersMap) {
        return sourceProvidersMap[credentialSource];
      } else {
        throw new import_property_provider.CredentialsProviderError(
          `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`
        );
      }
    }, "resolveCredentialSource");
    var isAssumeRoleProfile = /* @__PURE__ */ __name((arg) => 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) || isAssumeRoleWithProviderProfile(arg)), "isAssumeRoleProfile");
    var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg) => typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined", "isAssumeRoleWithSourceProfile");
    var isAssumeRoleWithProviderProfile = /* @__PURE__ */ __name((arg) => typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined", "isAssumeRoleWithProviderProfile");
    var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => {
      var _a;
      (_a = options.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-ini", "resolveAssumeRoleCredentials (STS)");
      const data = profiles[profileName];
      if (!options.roleAssumer) {
        const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM3(require_dist_cjs57()));
        options.roleAssumer = getDefaultRoleAssumer(
          {
            ...options.clientConfig,
            credentialProviderLogger: options.logger,
            parentClientConfig: options == null ? void 0 : options.parentClientConfig
          },
          options.clientPlugins
        );
      }
      const { source_profile } = data;
      if (source_profile && source_profile in visitedProfiles) {
        throw new import_property_provider.CredentialsProviderError(
          `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "),
          false
        );
      }
      const sourceCredsProvider = source_profile ? resolveProfileData(source_profile, profiles, options, {
        ...visitedProfiles,
        [source_profile]: true
      }) : (await resolveCredentialSource(data.credential_source, profileName)(options))();
      const params = {
        RoleArn: data.role_arn,
        RoleSessionName: data.role_session_name || `aws-sdk-js-${Date.now()}`,
        ExternalId: data.external_id,
        DurationSeconds: parseInt(data.duration_seconds || "3600", 10)
      };
      const { mfa_serial } = data;
      if (mfa_serial) {
        if (!options.mfaCodeProvider) {
          throw new import_property_provider.CredentialsProviderError(
            `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`,
            false
          );
        }
        params.SerialNumber = mfa_serial;
        params.TokenCode = await options.mfaCodeProvider(mfa_serial);
      }
      const sourceCreds = await sourceCredsProvider;
      return options.roleAssumer(sourceCreds, params);
    }, "resolveAssumeRoleCredentials");
    var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile");
    var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM3(require_dist_cjs53())).then(
      ({ fromProcess }) => fromProcess({
        ...options,
        profile
      })()
    ), "resolveProcessCredentials");
    var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, options = {}) => {
      const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs52()));
      return fromSSO({
        profile,
        logger: options.logger
      })();
    }, "resolveSsoCredentials");
    var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile");
    var isStaticCredsProfile = /* @__PURE__ */ __name((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, "isStaticCredsProfile");
    var resolveStaticCredentials = /* @__PURE__ */ __name((profile, options) => {
      var _a;
      (_a = options == null ? void 0 : options.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-ini", "resolveStaticCredentials");
      return Promise.resolve({
        accessKeyId: profile.aws_access_key_id,
        secretAccessKey: profile.aws_secret_access_key,
        sessionToken: profile.aws_session_token,
        credentialScope: profile.aws_credential_scope
      });
    }, "resolveStaticCredentials");
    var isWebIdentityProfile = /* @__PURE__ */ __name((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, "isWebIdentityProfile");
    var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM3(require_dist_cjs54())).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
      })()
    ), "resolveWebIdentityCredentials");
    var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => {
      const data = profiles[profileName];
      if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isAssumeRoleProfile(data)) {
        return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles);
      }
      if (isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isWebIdentityProfile(data)) {
        return resolveWebIdentityCredentials(data, options);
      }
      if (isProcessProfile(data)) {
        return resolveProcessCredentials(options, profileName);
      }
      if (isSsoProfile(data)) {
        return await resolveSsoCredentials(profileName, options);
      }
      throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found or parsed in shared credentials file.`);
    }, "resolveProfileData");
    var fromIni = /* @__PURE__ */ __name((init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-ini", "fromIni");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      return resolveProfileData((0, import_shared_ini_file_loader.getProfileName)(init2), profiles, init2);
    }, "fromIni");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-st_qaylqvuvqkdeetlwmxiq34v6lq/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js
var require_dist_cjs56 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-st_qaylqvuvqkdeetlwmxiq34v6lq/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      credentialsTreatedAsExpired: () => credentialsTreatedAsExpired,
      credentialsWillNeedRefresh: () => credentialsWillNeedRefresh,
      defaultProvider: () => defaultProvider
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_credential_provider_env = require_dist_cjs38();
    var import_shared_ini_file_loader = require_dist_cjs13();
    var import_property_provider = require_dist_cjs12();
    var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
    var remoteProvider = /* @__PURE__ */ __name(async (init2) => {
      var _a, _b;
      const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs39()));
      if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {
        (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "remoteProvider::fromHttp/fromContainerMetadata");
        const { fromHttp } = await Promise.resolve().then(() => __toESM3(require_dist_cjs40()));
        return (0, import_property_provider.chain)(fromHttp(init2), fromContainerMetadata(init2));
      }
      if (process.env[ENV_IMDS_DISABLED]) {
        return async () => {
          throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled");
        };
      }
      (_b = init2.logger) == null ? void 0 : _b.debug("@aws-sdk/credential-provider-node", "remoteProvider::fromInstanceMetadata");
      return fromInstanceMetadata(init2);
    }, "remoteProvider");
    var defaultProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider.memoize)(
      (0, import_property_provider.chain)(
        ...init2.profile || process.env[import_shared_ini_file_loader.ENV_PROFILE] ? [] : [
          async () => {
            var _a;
            (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromEnv");
            return (0, import_credential_provider_env.fromEnv)(init2)();
          }
        ],
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromSSO");
          const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
          if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
            throw new import_property_provider.CredentialsProviderError(
              "Skipping SSO provider in default chain (inputs do not include SSO fields)."
            );
          }
          const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs52()));
          return fromSSO(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromIni");
          const { fromIni } = await Promise.resolve().then(() => __toESM3(require_dist_cjs55()));
          return fromIni(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromProcess");
          const { fromProcess } = await Promise.resolve().then(() => __toESM3(require_dist_cjs53()));
          return fromProcess(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromTokenFile");
          const { fromTokenFile: fromTokenFile2 } = await Promise.resolve().then(() => __toESM3(require_dist_cjs54()));
          return fromTokenFile2(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::remoteProvider");
          return (await remoteProvider(init2))();
        },
        async () => {
          throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", false);
        }
      ),
      credentialsTreatedAsExpired,
      credentialsWillNeedRefresh
    ), "defaultProvider");
    var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0, "credentialsWillNeedRefresh");
    var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0 && credentials2.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js
var require_ruleset4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ruleSet = void 0;
    var F2 = "required";
    var G = "type";
    var H = "fn";
    var I = "argv";
    var J = "ref";
    var a = false;
    var b = true;
    var c = "booleanEquals";
    var d = "stringEquals";
    var e2 = "sigv4";
    var f3 = "sts";
    var g = "us-east-1";
    var h2 = "endpoint";
    var i2 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
    var j = "tree";
    var k = "error";
    var l = "getAttr";
    var m2 = { [F2]: false, [G]: "String" };
    var n = { [F2]: true, "default": false, [G]: "Boolean" };
    var o = { [J]: "Endpoint" };
    var p = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
    var q = { [J]: "Region" };
    var r2 = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" };
    var s2 = { [J]: "UseFIPS" };
    var t2 = { [J]: "UseDualStack" };
    var u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e2, "signingName": f3, "signingRegion": g }] }, "headers": {} };
    var v = {};
    var w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h2]: u, [G]: h2 };
    var x2 = { [H]: c, [I]: [s2, true] };
    var y = { [H]: c, [I]: [t2, true] };
    var z2 = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
    var A2 = { [J]: "PartitionResult" };
    var B = { [H]: c, [I]: [true, { [H]: l, [I]: [A2, "supportsDualStack"] }] };
    var C = [{ [H]: "isSet", [I]: [o] }];
    var D = [x2];
    var E = [y];
    var _data = { version: "1.0", parameters: { Region: m2, UseDualStack: n, UseFIPS: n, Endpoint: m2, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r2, { [H]: c, [I]: [s2, a] }, { [H]: c, [I]: [t2, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h2 }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h2 }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h2 }, { endpoint: { url: i2, properties: { authSchemes: [{ name: e2, signingName: f3, signingRegion: "{Region}" }] }, headers: v }, [G]: h2 }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h2 }], [G]: j }, { conditions: [p], rules: [{ conditions: [r2], rules: [{ conditions: [x2, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z2] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h2 }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z2, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h2 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h2 }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h2 }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i2, properties: v, headers: v }, [G]: h2 }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] };
    exports2.ruleSet = _data;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js
var require_endpointResolver4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultEndpointResolver = void 0;
    var util_endpoints_1 = require_dist_cjs7();
    var util_endpoints_2 = require_dist_cjs6();
    var ruleset_1 = require_ruleset4();
    var defaultEndpointResolver = (endpointParams, context = {}) => {
      return (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
        endpointParams,
        logger: context.logger
      });
    };
    exports2.defaultEndpointResolver = defaultEndpointResolver;
    util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js
var require_runtimeConfig_shared4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var core_1 = require_dist_cjs37();
    var core_2 = require_dist_cjs34();
    var smithy_client_1 = require_dist_cjs32();
    var url_parser_1 = require_dist_cjs16();
    var util_base64_1 = require_dist_cjs25();
    var util_utf8_1 = require_dist_cjs24();
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider4();
    var endpointResolver_1 = require_endpointResolver4();
    var getRuntimeConfig = (config) => {
      return {
        apiVersion: "2011-06-15",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new core_1.AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new core_2.NoAuthSigner()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "STS",
        urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js
var require_runtimeConfig4 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var package_json_1 = tslib_1.__importDefault(require_package5());
    var core_1 = require_dist_cjs37();
    var credential_provider_node_1 = require_dist_cjs56();
    var util_user_agent_node_1 = require_dist_cjs41();
    var config_resolver_1 = require_dist_cjs11();
    var core_2 = require_dist_cjs34();
    var hash_node_1 = require_dist_cjs42();
    var middleware_retry_1 = require_dist_cjs33();
    var node_config_provider_1 = require_dist_cjs14();
    var node_http_handler_1 = require_dist_cjs28();
    var util_body_length_node_1 = require_dist_cjs43();
    var util_retry_1 = require_dist_cjs20();
    var runtimeConfig_shared_1 = require_runtimeConfig_shared4();
    var smithy_client_1 = require_dist_cjs32();
    var util_defaults_mode_node_1 = require_dist_cjs44();
    var smithy_client_2 = require_dist_cjs32();
    var getRuntimeConfig = (config) => {
      (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
      const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
      (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
        credentialDefaultProvider: (config == null ? void 0 : config.credentialDefaultProvider) ?? credential_provider_node_1.defaultProvider,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await (0, credential_provider_node_1.defaultProvider)((idProps == null ? void 0 : idProps.__config) || {})()),
            signer: new core_1.AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new core_2.NoAuthSigner()
          }
        ],
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS),
        region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS),
        requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
          ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
        }),
        sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS)
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js
var require_httpAuthExtensionConfiguration = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveHttpAuthRuntimeConfig = exports2.getHttpAuthExtensionConfiguration = void 0;
    var getHttpAuthExtensionConfiguration = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index5 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index5 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index5, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    exports2.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration;
    var resolveHttpAuthRuntimeConfig = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
    exports2.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js
var require_runtimeExtensions = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveRuntimeExtensions = void 0;
    var region_config_resolver_1 = require_dist_cjs45();
    var protocol_http_1 = require_dist_cjs2();
    var smithy_client_1 = require_dist_cjs32();
    var httpAuthExtensionConfiguration_1 = require_httpAuthExtensionConfiguration();
    var asPartial = (t2) => t2;
    var resolveRuntimeExtensions = (runtimeConfig, extensions) => {
      const extensionConfiguration = {
        ...asPartial((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig))
      };
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return {
        ...runtimeConfig,
        ...(0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
        ...(0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration),
        ...(0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
        ...(0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)
      };
    };
    exports2.resolveRuntimeExtensions = resolveRuntimeExtensions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js
var require_STSClient = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.STSClient = exports2.__Client = void 0;
    var middleware_host_header_1 = require_dist_cjs3();
    var middleware_logger_1 = require_dist_cjs4();
    var middleware_recursion_detection_1 = require_dist_cjs5();
    var middleware_user_agent_1 = require_dist_cjs8();
    var config_resolver_1 = require_dist_cjs11();
    var core_1 = require_dist_cjs34();
    var middleware_content_length_1 = require_dist_cjs35();
    var middleware_endpoint_1 = require_dist_cjs18();
    var middleware_retry_1 = require_dist_cjs33();
    var smithy_client_1 = require_dist_cjs32();
    Object.defineProperty(exports2, "__Client", { enumerable: true, get: function() {
      return smithy_client_1.Client;
    } });
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider4();
    var EndpointParameters_1 = require_EndpointParameters();
    var runtimeConfig_1 = require_runtimeConfig4();
    var runtimeExtensions_1 = require_runtimeExtensions();
    var STSClient2 = class extends smithy_client_1.Client {
      constructor(...[configuration]) {
        const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {});
        const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0);
        const _config_2 = (0, config_resolver_1.resolveRegionConfig)(_config_1);
        const _config_3 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_2);
        const _config_4 = (0, middleware_retry_1.resolveRetryConfig)(_config_3);
        const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_5);
        const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6);
        const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        super(_config_8);
        this.config = _config_8;
        this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config));
        this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
          httpAuthSchemeParametersProvider: this.getDefaultHttpAuthSchemeParametersProvider(),
          identityProviderConfigProvider: this.getIdentityProviderConfigProvider()
        }));
        this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config));
      }
      destroy() {
        super.destroy();
      }
      getDefaultHttpAuthSchemeParametersProvider() {
        return httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider;
      }
      getIdentityProviderConfigProvider() {
        return async (config) => new core_1.DefaultIdentityProviderConfig({
          "aws.auth#sigv4": config.credentials
        });
      }
    };
    exports2.STSClient = STSClient2;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/index.js
var require_dist_cjs57 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/client-sts/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AssumeRoleCommand: () => AssumeRoleCommand,
      AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog,
      AssumeRoleWithSAMLCommand: () => AssumeRoleWithSAMLCommand,
      AssumeRoleWithSAMLRequestFilterSensitiveLog: () => AssumeRoleWithSAMLRequestFilterSensitiveLog,
      AssumeRoleWithSAMLResponseFilterSensitiveLog: () => AssumeRoleWithSAMLResponseFilterSensitiveLog,
      AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
      AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog,
      AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog,
      ClientInputEndpointParameters: () => import_EndpointParameters9.ClientInputEndpointParameters,
      CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog,
      DecodeAuthorizationMessageCommand: () => DecodeAuthorizationMessageCommand,
      ExpiredTokenException: () => ExpiredTokenException,
      GetAccessKeyInfoCommand: () => GetAccessKeyInfoCommand,
      GetCallerIdentityCommand: () => GetCallerIdentityCommand,
      GetFederationTokenCommand: () => GetFederationTokenCommand,
      GetFederationTokenResponseFilterSensitiveLog: () => GetFederationTokenResponseFilterSensitiveLog,
      GetSessionTokenCommand: () => GetSessionTokenCommand,
      GetSessionTokenResponseFilterSensitiveLog: () => GetSessionTokenResponseFilterSensitiveLog,
      IDPCommunicationErrorException: () => IDPCommunicationErrorException,
      IDPRejectedClaimException: () => IDPRejectedClaimException,
      InvalidAuthorizationMessageException: () => InvalidAuthorizationMessageException,
      InvalidIdentityTokenException: () => InvalidIdentityTokenException,
      MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
      PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
      RegionDisabledException: () => RegionDisabledException,
      RuntimeExtension: () => import_runtimeExtensions.RuntimeExtension,
      STS: () => STS,
      STSServiceException: () => STSServiceException,
      decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
      getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
      getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2
    });
    module2.exports = __toCommonJS2(src_exports);
    __reExport(src_exports, require_STSClient(), module2.exports);
    var import_middleware_endpoint = require_dist_cjs18();
    var import_middleware_serde = require_dist_cjs17();
    var import_types = require_dist_cjs();
    var import_EndpointParameters = require_EndpointParameters();
    var import_smithy_client = require_dist_cjs32();
    var _STSServiceException = class _STSServiceException2 extends import_smithy_client.ServiceException {
      /**
       * @internal
       */
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _STSServiceException2.prototype);
      }
    };
    __name(_STSServiceException, "STSServiceException");
    var STSServiceException = _STSServiceException;
    var _ExpiredTokenException = class _ExpiredTokenException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        this.name = "ExpiredTokenException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _ExpiredTokenException2.prototype);
      }
    };
    __name(_ExpiredTokenException, "ExpiredTokenException");
    var ExpiredTokenException = _ExpiredTokenException;
    var _MalformedPolicyDocumentException = class _MalformedPolicyDocumentException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "MalformedPolicyDocumentException",
          $fault: "client",
          ...opts
        });
        this.name = "MalformedPolicyDocumentException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _MalformedPolicyDocumentException2.prototype);
      }
    };
    __name(_MalformedPolicyDocumentException, "MalformedPolicyDocumentException");
    var MalformedPolicyDocumentException = _MalformedPolicyDocumentException;
    var _PackedPolicyTooLargeException = class _PackedPolicyTooLargeException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "PackedPolicyTooLargeException",
          $fault: "client",
          ...opts
        });
        this.name = "PackedPolicyTooLargeException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _PackedPolicyTooLargeException2.prototype);
      }
    };
    __name(_PackedPolicyTooLargeException, "PackedPolicyTooLargeException");
    var PackedPolicyTooLargeException = _PackedPolicyTooLargeException;
    var _RegionDisabledException = class _RegionDisabledException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "RegionDisabledException",
          $fault: "client",
          ...opts
        });
        this.name = "RegionDisabledException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _RegionDisabledException2.prototype);
      }
    };
    __name(_RegionDisabledException, "RegionDisabledException");
    var RegionDisabledException = _RegionDisabledException;
    var _IDPRejectedClaimException = class _IDPRejectedClaimException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "IDPRejectedClaimException",
          $fault: "client",
          ...opts
        });
        this.name = "IDPRejectedClaimException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _IDPRejectedClaimException2.prototype);
      }
    };
    __name(_IDPRejectedClaimException, "IDPRejectedClaimException");
    var IDPRejectedClaimException = _IDPRejectedClaimException;
    var _InvalidIdentityTokenException = class _InvalidIdentityTokenException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidIdentityTokenException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidIdentityTokenException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidIdentityTokenException2.prototype);
      }
    };
    __name(_InvalidIdentityTokenException, "InvalidIdentityTokenException");
    var InvalidIdentityTokenException = _InvalidIdentityTokenException;
    var _IDPCommunicationErrorException = class _IDPCommunicationErrorException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "IDPCommunicationErrorException",
          $fault: "client",
          ...opts
        });
        this.name = "IDPCommunicationErrorException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _IDPCommunicationErrorException2.prototype);
      }
    };
    __name(_IDPCommunicationErrorException, "IDPCommunicationErrorException");
    var IDPCommunicationErrorException = _IDPCommunicationErrorException;
    var _InvalidAuthorizationMessageException = class _InvalidAuthorizationMessageException2 extends STSServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidAuthorizationMessageException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidAuthorizationMessageException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidAuthorizationMessageException2.prototype);
      }
    };
    __name(_InvalidAuthorizationMessageException, "InvalidAuthorizationMessageException");
    var InvalidAuthorizationMessageException = _InvalidAuthorizationMessageException;
    var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client.SENSITIVE_STRING }
    }), "CredentialsFilterSensitiveLog");
    var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    }), "AssumeRoleResponseFilterSensitiveLog");
    var AssumeRoleWithSAMLRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.SAMLAssertion && { SAMLAssertion: import_smithy_client.SENSITIVE_STRING }
    }), "AssumeRoleWithSAMLRequestFilterSensitiveLog");
    var AssumeRoleWithSAMLResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    }), "AssumeRoleWithSAMLResponseFilterSensitiveLog");
    var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client.SENSITIVE_STRING }
    }), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog");
    var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    }), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog");
    var GetFederationTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    }), "GetFederationTokenResponseFilterSensitiveLog");
    var GetSessionTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    }), "GetSessionTokenResponseFilterSensitiveLog");
    var import_core = require_dist_cjs37();
    var import_protocol_http = require_dist_cjs2();
    var se_AssumeRoleCommand = /* @__PURE__ */ __name(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_AssumeRoleCommand");
    var se_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleWithSAMLRequest(input, context),
        [_A]: _ARWSAML,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    }, "se_AssumeRoleWithSAMLCommand");
    var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(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);
    }, "se_AssumeRoleWithWebIdentityCommand");
    var se_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_DecodeAuthorizationMessageRequest(input, context),
        [_A]: _DAM,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    }, "se_DecodeAuthorizationMessageCommand");
    var se_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetAccessKeyInfoRequest(input, context),
        [_A]: _GAKI,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    }, "se_GetAccessKeyInfoCommand");
    var se_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetCallerIdentityRequest(input, context),
        [_A]: _GCI,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    }, "se_GetCallerIdentityCommand");
    var se_GetFederationTokenCommand = /* @__PURE__ */ __name(async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetFederationTokenRequest(input, context),
        [_A]: _GFT,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    }, "se_GetFederationTokenCommand");
    var se_GetSessionTokenCommand = /* @__PURE__ */ __name(async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetSessionTokenRequest(input, context),
        [_A]: _GST,
        [_V]: _2
      });
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    }, "se_GetSessionTokenCommand");
    var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_AssumeRoleResponse(data.AssumeRoleResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_AssumeRoleCommand");
    var de_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_AssumeRoleWithSAMLResponse(data.AssumeRoleWithSAMLResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_AssumeRoleWithSAMLCommand");
    var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_AssumeRoleWithWebIdentityCommand");
    var de_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_DecodeAuthorizationMessageResponse(data.DecodeAuthorizationMessageResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_DecodeAuthorizationMessageCommand");
    var de_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_GetAccessKeyInfoResponse(data.GetAccessKeyInfoResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_GetAccessKeyInfoCommand");
    var de_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_GetCallerIdentityResponse(data.GetCallerIdentityResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_GetCallerIdentityCommand");
    var de_GetFederationTokenCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_GetFederationTokenResponse(data.GetFederationTokenResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_GetFederationTokenCommand");
    var de_GetSessionTokenCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await (0, import_core.parseXmlBody)(output.body, context);
      let contents = {};
      contents = de_GetSessionTokenResponse(data.GetSessionTokenResult, context);
      const response = {
        $metadata: deserializeMetadata(output),
        ...contents
      };
      return response;
    }, "de_GetSessionTokenCommand");
    var de_CommandError = /* @__PURE__ */ __name(async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await (0, import_core.parseXmlErrorBody)(output.body, context)
      };
      const errorCode = loadQueryErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "ExpiredTokenException":
        case "com.amazonaws.sts#ExpiredTokenException":
          throw await de_ExpiredTokenExceptionRes(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 "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);
        case "IDPCommunicationError":
        case "com.amazonaws.sts#IDPCommunicationErrorException":
          throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context);
        case "InvalidAuthorizationMessageException":
        case "com.amazonaws.sts#InvalidAuthorizationMessageException":
          throw await de_InvalidAuthorizationMessageExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError({
            output,
            parsedBody: parsedBody.Error,
            errorCode
          });
      }
    }, "de_CommandError");
    var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_ExpiredTokenException(body.Error, context);
      const exception = new ExpiredTokenException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_ExpiredTokenExceptionRes");
    var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPCommunicationErrorException(body.Error, context);
      const exception = new IDPCommunicationErrorException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_IDPCommunicationErrorExceptionRes");
    var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPRejectedClaimException(body.Error, context);
      const exception = new IDPRejectedClaimException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_IDPRejectedClaimExceptionRes");
    var de_InvalidAuthorizationMessageExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_InvalidAuthorizationMessageException(body.Error, context);
      const exception = new InvalidAuthorizationMessageException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_InvalidAuthorizationMessageExceptionRes");
    var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_InvalidIdentityTokenException(body.Error, context);
      const exception = new InvalidIdentityTokenException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_InvalidIdentityTokenExceptionRes");
    var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_MalformedPolicyDocumentException(body.Error, context);
      const exception = new MalformedPolicyDocumentException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_MalformedPolicyDocumentExceptionRes");
    var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_PackedPolicyTooLargeException(body.Error, context);
      const exception = new PackedPolicyTooLargeException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_PackedPolicyTooLargeExceptionRes");
    var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_RegionDisabledException(body.Error, context);
      const exception = new RegionDisabledException({
        $metadata: deserializeMetadata(parsedOutput),
        ...deserialized
      });
      return (0, import_smithy_client.decorateServiceException)(exception, body);
    }, "de_RegionDisabledExceptionRes");
    var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => {
      var _a2, _b, _c, _d;
      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 (((_a2 = input[_PA]) == null ? void 0 : _a2.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 (((_b = input[_T]) == null ? void 0 : _b.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 (((_c = input[_TTK]) == null ? void 0 : _c.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 (((_d = input[_PC]) == null ? void 0 : _d.length) === 0) {
          entries.ProvidedContexts = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `ProvidedContexts.${key}`;
          entries[loc] = value;
        });
      }
      return entries;
    }, "se_AssumeRoleRequest");
    var se_AssumeRoleWithSAMLRequest = /* @__PURE__ */ __name((input, context) => {
      var _a2;
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_PAr] != null) {
        entries[_PAr] = input[_PAr];
      }
      if (input[_SAMLA] != null) {
        entries[_SAMLA] = input[_SAMLA];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (((_a2 = input[_PA]) == null ? void 0 : _a2.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_AssumeRoleWithSAMLRequest");
    var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => {
      var _a2;
      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 (((_a2 = input[_PA]) == null ? void 0 : _a2.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_AssumeRoleWithWebIdentityRequest");
    var se_DecodeAuthorizationMessageRequest = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      if (input[_EM] != null) {
        entries[_EM] = input[_EM];
      }
      return entries;
    }, "se_DecodeAuthorizationMessageRequest");
    var se_GetAccessKeyInfoRequest = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      if (input[_AKI] != null) {
        entries[_AKI] = input[_AKI];
      }
      return entries;
    }, "se_GetAccessKeyInfoRequest");
    var se_GetCallerIdentityRequest = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      return entries;
    }, "se_GetCallerIdentityRequest");
    var se_GetFederationTokenRequest = /* @__PURE__ */ __name((input, context) => {
      var _a2, _b;
      const entries = {};
      if (input[_N] != null) {
        entries[_N] = input[_N];
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (((_a2 = input[_PA]) == null ? void 0 : _a2.length) === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      if (input[_T] != null) {
        const memberEntries = se_tagListType(input[_T], context);
        if (((_b = input[_T]) == null ? void 0 : _b.length) === 0) {
          entries.Tags = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `Tags.${key}`;
          entries[loc] = value;
        });
      }
      return entries;
    }, "se_GetFederationTokenRequest");
    var se_GetSessionTokenRequest = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      if (input[_SN] != null) {
        entries[_SN] = input[_SN];
      }
      if (input[_TC] != null) {
        entries[_TC] = input[_TC];
      }
      return entries;
    }, "se_GetSessionTokenRequest");
    var se_policyDescriptorListType = /* @__PURE__ */ __name((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_policyDescriptorListType");
    var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      if (input[_a] != null) {
        entries[_a] = input[_a];
      }
      return entries;
    }, "se_PolicyDescriptorType");
    var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      if (input[_PAro] != null) {
        entries[_PAro] = input[_PAro];
      }
      if (input[_CA] != null) {
        entries[_CA] = input[_CA];
      }
      return entries;
    }, "se_ProvidedContext");
    var se_ProvidedContextsListType = /* @__PURE__ */ __name((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_ProvidedContextsListType");
    var se_Tag = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      if (input[_K] != null) {
        entries[_K] = input[_K];
      }
      if (input[_Va] != null) {
        entries[_Va] = input[_Va];
      }
      return entries;
    }, "se_Tag");
    var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        entries[`member.${counter}`] = entry;
        counter++;
      }
      return entries;
    }, "se_tagKeyListType");
    var se_tagListType = /* @__PURE__ */ __name((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;
    }, "se_tagListType");
    var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_ARI] != null) {
        contents[_ARI] = (0, import_smithy_client.expectString)(output[_ARI]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]);
      }
      return contents;
    }, "de_AssumedRoleUser");
    var de_AssumeRoleResponse = /* @__PURE__ */ __name((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] = (0, import_smithy_client.strictParseInt32)(output[_PPS]);
      }
      if (output[_SI] != null) {
        contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]);
      }
      return contents;
    }, "de_AssumeRoleResponse");
    var de_AssumeRoleWithSAMLResponse = /* @__PURE__ */ __name((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] = (0, import_smithy_client.strictParseInt32)(output[_PPS]);
      }
      if (output[_S] != null) {
        contents[_S] = (0, import_smithy_client.expectString)(output[_S]);
      }
      if (output[_ST] != null) {
        contents[_ST] = (0, import_smithy_client.expectString)(output[_ST]);
      }
      if (output[_I] != null) {
        contents[_I] = (0, import_smithy_client.expectString)(output[_I]);
      }
      if (output[_Au] != null) {
        contents[_Au] = (0, import_smithy_client.expectString)(output[_Au]);
      }
      if (output[_NQ] != null) {
        contents[_NQ] = (0, import_smithy_client.expectString)(output[_NQ]);
      }
      if (output[_SI] != null) {
        contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]);
      }
      return contents;
    }, "de_AssumeRoleWithSAMLResponse");
    var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials(output[_C], context);
      }
      if (output[_SFWIT] != null) {
        contents[_SFWIT] = (0, import_smithy_client.expectString)(output[_SFWIT]);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]);
      }
      if (output[_Pr] != null) {
        contents[_Pr] = (0, import_smithy_client.expectString)(output[_Pr]);
      }
      if (output[_Au] != null) {
        contents[_Au] = (0, import_smithy_client.expectString)(output[_Au]);
      }
      if (output[_SI] != null) {
        contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]);
      }
      return contents;
    }, "de_AssumeRoleWithWebIdentityResponse");
    var de_Credentials = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_AKI] != null) {
        contents[_AKI] = (0, import_smithy_client.expectString)(output[_AKI]);
      }
      if (output[_SAK] != null) {
        contents[_SAK] = (0, import_smithy_client.expectString)(output[_SAK]);
      }
      if (output[_STe] != null) {
        contents[_STe] = (0, import_smithy_client.expectString)(output[_STe]);
      }
      if (output[_E] != null) {
        contents[_E] = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseRfc3339DateTimeWithOffset)(output[_E]));
      }
      return contents;
    }, "de_Credentials");
    var de_DecodeAuthorizationMessageResponse = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_DM] != null) {
        contents[_DM] = (0, import_smithy_client.expectString)(output[_DM]);
      }
      return contents;
    }, "de_DecodeAuthorizationMessageResponse");
    var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_ExpiredTokenException");
    var de_FederatedUser = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_FUI] != null) {
        contents[_FUI] = (0, import_smithy_client.expectString)(output[_FUI]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]);
      }
      return contents;
    }, "de_FederatedUser");
    var de_GetAccessKeyInfoResponse = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_Ac] != null) {
        contents[_Ac] = (0, import_smithy_client.expectString)(output[_Ac]);
      }
      return contents;
    }, "de_GetAccessKeyInfoResponse");
    var de_GetCallerIdentityResponse = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_UI] != null) {
        contents[_UI] = (0, import_smithy_client.expectString)(output[_UI]);
      }
      if (output[_Ac] != null) {
        contents[_Ac] = (0, import_smithy_client.expectString)(output[_Ac]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]);
      }
      return contents;
    }, "de_GetCallerIdentityResponse");
    var de_GetFederationTokenResponse = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials(output[_C], context);
      }
      if (output[_FU] != null) {
        contents[_FU] = de_FederatedUser(output[_FU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]);
      }
      return contents;
    }, "de_GetFederationTokenResponse");
    var de_GetSessionTokenResponse = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials(output[_C], context);
      }
      return contents;
    }, "de_GetSessionTokenResponse");
    var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_IDPCommunicationErrorException");
    var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_IDPRejectedClaimException");
    var de_InvalidAuthorizationMessageException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_InvalidAuthorizationMessageException");
    var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_InvalidIdentityTokenException");
    var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_MalformedPolicyDocumentException");
    var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_PackedPolicyTooLargeException");
    var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = (0, import_smithy_client.expectString)(output[_m]);
      }
      return contents;
    }, "de_RegionDisabledException");
    var deserializeMetadata = /* @__PURE__ */ __name((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"]
    }), "deserializeMetadata");
    var throwDefaultError = (0, import_smithy_client.withBaseException)(STSServiceException);
    var buildHttpRpcRequest = /* @__PURE__ */ __name(async (context, headers, path4, 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) + path4 : basePath + path4,
        headers
      };
      if (resolvedHostname !== void 0) {
        contents.hostname = resolvedHostname;
      }
      if (body !== void 0) {
        contents.body = body;
      }
      return new import_protocol_http.HttpRequest(contents);
    }, "buildHttpRpcRequest");
    var SHARED_HEADERS = {
      "content-type": "application/x-www-form-urlencoded"
    };
    var _2 = "2011-06-15";
    var _A = "Action";
    var _AKI = "AccessKeyId";
    var _AR = "AssumeRole";
    var _ARI = "AssumedRoleId";
    var _ARU = "AssumedRoleUser";
    var _ARWSAML = "AssumeRoleWithSAML";
    var _ARWWI = "AssumeRoleWithWebIdentity";
    var _Ac = "Account";
    var _Ar = "Arn";
    var _Au = "Audience";
    var _C = "Credentials";
    var _CA = "ContextAssertion";
    var _DAM = "DecodeAuthorizationMessage";
    var _DM = "DecodedMessage";
    var _DS = "DurationSeconds";
    var _E = "Expiration";
    var _EI = "ExternalId";
    var _EM = "EncodedMessage";
    var _FU = "FederatedUser";
    var _FUI = "FederatedUserId";
    var _GAKI = "GetAccessKeyInfo";
    var _GCI = "GetCallerIdentity";
    var _GFT = "GetFederationToken";
    var _GST = "GetSessionToken";
    var _I = "Issuer";
    var _K = "Key";
    var _N = "Name";
    var _NQ = "NameQualifier";
    var _P = "Policy";
    var _PA = "PolicyArns";
    var _PAr = "PrincipalArn";
    var _PAro = "ProviderArn";
    var _PC = "ProvidedContexts";
    var _PI = "ProviderId";
    var _PPS = "PackedPolicySize";
    var _Pr = "Provider";
    var _RA = "RoleArn";
    var _RSN = "RoleSessionName";
    var _S = "Subject";
    var _SAK = "SecretAccessKey";
    var _SAMLA = "SAMLAssertion";
    var _SFWIT = "SubjectFromWebIdentityToken";
    var _SI = "SourceIdentity";
    var _SN = "SerialNumber";
    var _ST = "SubjectType";
    var _STe = "SessionToken";
    var _T = "Tags";
    var _TC = "TokenCode";
    var _TTK = "TransitiveTagKeys";
    var _UI = "UserId";
    var _V = "Version";
    var _Va = "Value";
    var _WIT = "WebIdentityToken";
    var _a = "arn";
    var _m = "message";
    var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString");
    var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => {
      var _a2;
      if (((_a2 = data.Error) == null ? void 0 : _a2.Code) !== void 0) {
        return data.Error.Code;
      }
      if (output.statusCode == 404) {
        return "NotFound";
      }
    }, "loadQueryErrorCode");
    var _AssumeRoleCommand = class _AssumeRoleCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() {
    };
    __name(_AssumeRoleCommand, "AssumeRoleCommand");
    var AssumeRoleCommand = _AssumeRoleCommand;
    var import_EndpointParameters2 = require_EndpointParameters();
    var _AssumeRoleWithSAMLCommand = class _AssumeRoleWithSAMLCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters2.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}).n("STSClient", "AssumeRoleWithSAMLCommand").f(AssumeRoleWithSAMLRequestFilterSensitiveLog, AssumeRoleWithSAMLResponseFilterSensitiveLog).ser(se_AssumeRoleWithSAMLCommand).de(de_AssumeRoleWithSAMLCommand).build() {
    };
    __name(_AssumeRoleWithSAMLCommand, "AssumeRoleWithSAMLCommand");
    var AssumeRoleWithSAMLCommand = _AssumeRoleWithSAMLCommand;
    var import_EndpointParameters3 = require_EndpointParameters();
    var _AssumeRoleWithWebIdentityCommand = class _AssumeRoleWithWebIdentityCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters3.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() {
    };
    __name(_AssumeRoleWithWebIdentityCommand, "AssumeRoleWithWebIdentityCommand");
    var AssumeRoleWithWebIdentityCommand = _AssumeRoleWithWebIdentityCommand;
    var import_EndpointParameters4 = require_EndpointParameters();
    var _DecodeAuthorizationMessageCommand = class _DecodeAuthorizationMessageCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters4.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}).n("STSClient", "DecodeAuthorizationMessageCommand").f(void 0, void 0).ser(se_DecodeAuthorizationMessageCommand).de(de_DecodeAuthorizationMessageCommand).build() {
    };
    __name(_DecodeAuthorizationMessageCommand, "DecodeAuthorizationMessageCommand");
    var DecodeAuthorizationMessageCommand = _DecodeAuthorizationMessageCommand;
    var import_EndpointParameters5 = require_EndpointParameters();
    var _GetAccessKeyInfoCommand = class _GetAccessKeyInfoCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters5.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}).n("STSClient", "GetAccessKeyInfoCommand").f(void 0, void 0).ser(se_GetAccessKeyInfoCommand).de(de_GetAccessKeyInfoCommand).build() {
    };
    __name(_GetAccessKeyInfoCommand, "GetAccessKeyInfoCommand");
    var GetAccessKeyInfoCommand = _GetAccessKeyInfoCommand;
    var import_EndpointParameters6 = require_EndpointParameters();
    var _GetCallerIdentityCommand = class _GetCallerIdentityCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters6.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}).n("STSClient", "GetCallerIdentityCommand").f(void 0, void 0).ser(se_GetCallerIdentityCommand).de(de_GetCallerIdentityCommand).build() {
    };
    __name(_GetCallerIdentityCommand, "GetCallerIdentityCommand");
    var GetCallerIdentityCommand = _GetCallerIdentityCommand;
    var import_EndpointParameters7 = require_EndpointParameters();
    var _GetFederationTokenCommand = class _GetFederationTokenCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters7.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}).n("STSClient", "GetFederationTokenCommand").f(void 0, GetFederationTokenResponseFilterSensitiveLog).ser(se_GetFederationTokenCommand).de(de_GetFederationTokenCommand).build() {
    };
    __name(_GetFederationTokenCommand, "GetFederationTokenCommand");
    var GetFederationTokenCommand = _GetFederationTokenCommand;
    var import_EndpointParameters8 = require_EndpointParameters();
    var _GetSessionTokenCommand = class _GetSessionTokenCommand extends import_smithy_client.Command.classBuilder().ep({
      ...import_EndpointParameters8.commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}).n("STSClient", "GetSessionTokenCommand").f(void 0, GetSessionTokenResponseFilterSensitiveLog).ser(se_GetSessionTokenCommand).de(de_GetSessionTokenCommand).build() {
    };
    __name(_GetSessionTokenCommand, "GetSessionTokenCommand");
    var GetSessionTokenCommand = _GetSessionTokenCommand;
    var import_STSClient = require_STSClient();
    var commands = {
      AssumeRoleCommand,
      AssumeRoleWithSAMLCommand,
      AssumeRoleWithWebIdentityCommand,
      DecodeAuthorizationMessageCommand,
      GetAccessKeyInfoCommand,
      GetCallerIdentityCommand,
      GetFederationTokenCommand,
      GetSessionTokenCommand
    };
    var _STS = class _STS extends import_STSClient.STSClient {
    };
    __name(_STS, "STS");
    var STS = _STS;
    (0, import_smithy_client.createAggregatedClient)(commands, STS);
    var import_EndpointParameters9 = require_EndpointParameters();
    var import_runtimeExtensions = require_runtimeExtensions();
    var ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
    var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => {
      var _a2;
      const region = typeof _region === "function" ? await _region() : _region;
      const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
      (_a2 = credentialProviderLogger == null ? void 0 : credentialProviderLogger.debug) == null ? void 0 : _a2.call(
        credentialProviderLogger,
        "@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;
    }, "resolveRegion");
    var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, stsClientCtor) => {
      let stsClient;
      let closureSourceCreds;
      return async (sourceCreds, params) => {
        var _a2, _b, _c;
        closureSourceCreds = sourceCreds;
        if (!stsClient) {
          const {
            logger = (_a2 = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _a2.logger,
            region,
            requestHandler = (_b = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _b.requestHandler,
            credentialProviderLogger
          } = stsOptions;
          const resolvedRegion = await resolveRegion(
            region,
            (_c = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _c.region,
            credentialProviderLogger
          );
          stsClient = new stsClientCtor({
            // A hack to make sts client uses the credential in current closure.
            credentialDefaultProvider: () => async () => closureSourceCreds,
            region: resolvedRegion,
            requestHandler,
            logger
          });
        }
        const { Credentials: Credentials2 } = await stsClient.send(new AssumeRoleCommand(params));
        if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
        }
        return {
          accessKeyId: Credentials2.AccessKeyId,
          secretAccessKey: Credentials2.SecretAccessKey,
          sessionToken: Credentials2.SessionToken,
          expiration: Credentials2.Expiration,
          // TODO(credentialScope): access normally when shape is updated.
          credentialScope: Credentials2.CredentialScope
        };
      };
    }, "getDefaultRoleAssumer");
    var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, stsClientCtor) => {
      let stsClient;
      return async (params) => {
        var _a2, _b, _c;
        if (!stsClient) {
          const {
            logger = (_a2 = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _a2.logger,
            region,
            requestHandler = (_b = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _b.requestHandler,
            credentialProviderLogger
          } = stsOptions;
          const resolvedRegion = await resolveRegion(
            region,
            (_c = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _c.region,
            credentialProviderLogger
          );
          stsClient = new stsClientCtor({
            region: resolvedRegion,
            requestHandler,
            logger
          });
        }
        const { Credentials: Credentials2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
        if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
        }
        return {
          accessKeyId: Credentials2.AccessKeyId,
          secretAccessKey: Credentials2.SecretAccessKey,
          sessionToken: Credentials2.SessionToken,
          expiration: Credentials2.Expiration,
          // TODO(credentialScope): access normally when shape is updated.
          credentialScope: Credentials2.CredentialScope
        };
      };
    }, "getDefaultRoleAssumerWithWebIdentity");
    var import_STSClient2 = require_STSClient();
    var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => {
      var _a2;
      if (!customizations)
        return baseCtor;
      else
        return _a2 = class extends baseCtor {
          constructor(config) {
            super(config);
            for (const customization of customizations) {
              this.middlewareStack.use(customization);
            }
          }
        }, __name(_a2, "CustomizableSTSClient"), _a2;
    }, "getCustomizableStsClientCtor");
    var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer");
    var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity");
    var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({
      roleAssumer: getDefaultRoleAssumer2(input),
      roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
      ...input
    }), "decorateDefaultCredentialProvider");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js
var require_dist_cjs58 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromIni: () => fromIni
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_shared_ini_file_loader = require_dist_cjs13();
    var import_property_provider = require_dist_cjs12();
    var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName) => {
      const sourceProvidersMap = {
        EcsContainer: (options) => Promise.resolve().then(() => __toESM3(require_dist_cjs39())).then(({ fromContainerMetadata }) => fromContainerMetadata(options)),
        Ec2InstanceMetadata: (options) => Promise.resolve().then(() => __toESM3(require_dist_cjs39())).then(({ fromInstanceMetadata }) => fromInstanceMetadata(options)),
        Environment: (options) => Promise.resolve().then(() => __toESM3(require_dist_cjs38())).then(({ fromEnv }) => fromEnv(options))
      };
      if (credentialSource in sourceProvidersMap) {
        return sourceProvidersMap[credentialSource];
      } else {
        throw new import_property_provider.CredentialsProviderError(
          `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`
        );
      }
    }, "resolveCredentialSource");
    var isAssumeRoleProfile = /* @__PURE__ */ __name((arg) => 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) || isAssumeRoleWithProviderProfile(arg)), "isAssumeRoleProfile");
    var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg) => typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined", "isAssumeRoleWithSourceProfile");
    var isAssumeRoleWithProviderProfile = /* @__PURE__ */ __name((arg) => typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined", "isAssumeRoleWithProviderProfile");
    var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => {
      var _a;
      (_a = options.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-ini", "resolveAssumeRoleCredentials (STS)");
      const data = profiles[profileName];
      if (!options.roleAssumer) {
        const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM3(require_dist_cjs57()));
        options.roleAssumer = getDefaultRoleAssumer(
          {
            ...options.clientConfig,
            credentialProviderLogger: options.logger,
            parentClientConfig: options == null ? void 0 : options.parentClientConfig
          },
          options.clientPlugins
        );
      }
      const { source_profile } = data;
      if (source_profile && source_profile in visitedProfiles) {
        throw new import_property_provider.CredentialsProviderError(
          `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "),
          false
        );
      }
      const sourceCredsProvider = source_profile ? resolveProfileData(source_profile, profiles, options, {
        ...visitedProfiles,
        [source_profile]: true
      }) : (await resolveCredentialSource(data.credential_source, profileName)(options))();
      const params = {
        RoleArn: data.role_arn,
        RoleSessionName: data.role_session_name || `aws-sdk-js-${Date.now()}`,
        ExternalId: data.external_id,
        DurationSeconds: parseInt(data.duration_seconds || "3600", 10)
      };
      const { mfa_serial } = data;
      if (mfa_serial) {
        if (!options.mfaCodeProvider) {
          throw new import_property_provider.CredentialsProviderError(
            `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`,
            false
          );
        }
        params.SerialNumber = mfa_serial;
        params.TokenCode = await options.mfaCodeProvider(mfa_serial);
      }
      const sourceCreds = await sourceCredsProvider;
      return options.roleAssumer(sourceCreds, params);
    }, "resolveAssumeRoleCredentials");
    var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile");
    var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM3(require_dist_cjs53())).then(
      ({ fromProcess }) => fromProcess({
        ...options,
        profile
      })()
    ), "resolveProcessCredentials");
    var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, options = {}) => {
      const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs49()));
      return fromSSO({
        profile,
        logger: options.logger
      })();
    }, "resolveSsoCredentials");
    var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile");
    var isStaticCredsProfile = /* @__PURE__ */ __name((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, "isStaticCredsProfile");
    var resolveStaticCredentials = /* @__PURE__ */ __name((profile, options) => {
      var _a;
      (_a = options == null ? void 0 : options.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-ini", "resolveStaticCredentials");
      return Promise.resolve({
        accessKeyId: profile.aws_access_key_id,
        secretAccessKey: profile.aws_secret_access_key,
        sessionToken: profile.aws_session_token,
        credentialScope: profile.aws_credential_scope
      });
    }, "resolveStaticCredentials");
    var isWebIdentityProfile = /* @__PURE__ */ __name((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, "isWebIdentityProfile");
    var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM3(require_dist_cjs54())).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
      })()
    ), "resolveWebIdentityCredentials");
    var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => {
      const data = profiles[profileName];
      if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isAssumeRoleProfile(data)) {
        return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles);
      }
      if (isStaticCredsProfile(data)) {
        return resolveStaticCredentials(data, options);
      }
      if (isWebIdentityProfile(data)) {
        return resolveWebIdentityCredentials(data, options);
      }
      if (isProcessProfile(data)) {
        return resolveProcessCredentials(options, profileName);
      }
      if (isSsoProfile(data)) {
        return await resolveSsoCredentials(profileName, options);
      }
      throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found or parsed in shared credentials file.`);
    }, "resolveProfileData");
    var fromIni = /* @__PURE__ */ __name((init2 = {}) => async () => {
      var _a;
      (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-ini", "fromIni");
      const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
      return resolveProfileData((0, import_shared_ini_file_loader.getProfileName)(init2), profiles, init2);
    }, "fromIni");
  }
});

// ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js
var require_dist_cjs59 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.583.0_@aws-sdk+client-sso-oidc@3.583.0_@aws-sdk+client-sts@3.583.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __create3 = Object.create;
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf3 = Object.getPrototypeOf;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
      // 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 ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      credentialsTreatedAsExpired: () => credentialsTreatedAsExpired,
      credentialsWillNeedRefresh: () => credentialsWillNeedRefresh,
      defaultProvider: () => defaultProvider
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_credential_provider_env = require_dist_cjs38();
    var import_shared_ini_file_loader = require_dist_cjs13();
    var import_property_provider = require_dist_cjs12();
    var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
    var remoteProvider = /* @__PURE__ */ __name(async (init2) => {
      var _a, _b;
      const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs39()));
      if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {
        (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "remoteProvider::fromHttp/fromContainerMetadata");
        const { fromHttp } = await Promise.resolve().then(() => __toESM3(require_dist_cjs40()));
        return (0, import_property_provider.chain)(fromHttp(init2), fromContainerMetadata(init2));
      }
      if (process.env[ENV_IMDS_DISABLED]) {
        return async () => {
          throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled");
        };
      }
      (_b = init2.logger) == null ? void 0 : _b.debug("@aws-sdk/credential-provider-node", "remoteProvider::fromInstanceMetadata");
      return fromInstanceMetadata(init2);
    }, "remoteProvider");
    var defaultProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider.memoize)(
      (0, import_property_provider.chain)(
        ...init2.profile || process.env[import_shared_ini_file_loader.ENV_PROFILE] ? [] : [
          async () => {
            var _a;
            (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromEnv");
            return (0, import_credential_provider_env.fromEnv)(init2)();
          }
        ],
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromSSO");
          const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
          if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
            throw new import_property_provider.CredentialsProviderError(
              "Skipping SSO provider in default chain (inputs do not include SSO fields)."
            );
          }
          const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs49()));
          return fromSSO(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromIni");
          const { fromIni } = await Promise.resolve().then(() => __toESM3(require_dist_cjs58()));
          return fromIni(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromProcess");
          const { fromProcess } = await Promise.resolve().then(() => __toESM3(require_dist_cjs53()));
          return fromProcess(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::fromTokenFile");
          const { fromTokenFile: fromTokenFile2 } = await Promise.resolve().then(() => __toESM3(require_dist_cjs54()));
          return fromTokenFile2(init2)();
        },
        async () => {
          var _a;
          (_a = init2.logger) == null ? void 0 : _a.debug("@aws-sdk/credential-provider-node", "defaultProvider::remoteProvider");
          return (await remoteProvider(init2))();
        },
        async () => {
          throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", false);
        }
      ),
      credentialsTreatedAsExpired,
      credentialsWillNeedRefresh
    ), "defaultProvider");
    var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0, "credentialsWillNeedRefresh");
    var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0 && credentials2.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired");
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/ruleset.js
var require_ruleset5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/ruleset.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ruleSet = void 0;
    var s2 = "required";
    var t2 = "fn";
    var u = "argv";
    var v = "ref";
    var a = true;
    var b = "isSet";
    var c = "booleanEquals";
    var d = "error";
    var e2 = "endpoint";
    var f3 = "tree";
    var g = "PartitionResult";
    var h2 = { [s2]: false, "type": "String" };
    var i2 = { [s2]: true, "default": false, "type": "Boolean" };
    var j = { [v]: "Endpoint" };
    var k = { [t2]: c, [u]: [{ [v]: "UseFIPS" }, true] };
    var l = { [t2]: c, [u]: [{ [v]: "UseDualStack" }, true] };
    var m2 = {};
    var n = { [t2]: "getAttr", [u]: [{ [v]: g }, "supportsFIPS"] };
    var o = { [t2]: c, [u]: [true, { [t2]: "getAttr", [u]: [{ [v]: g }, "supportsDualStack"] }] };
    var p = [k];
    var q = [l];
    var r2 = [{ [v]: "Region" }];
    var _data = { version: "1.0", parameters: { Region: h2, UseDualStack: i2, UseFIPS: i2, Endpoint: h2 }, rules: [{ conditions: [{ [t2]: b, [u]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m2, headers: m2 }, type: e2 }], type: f3 }, { conditions: [{ [t2]: b, [u]: r2 }], rules: [{ conditions: [{ [t2]: "aws.partition", [u]: r2, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t2]: c, [u]: [a, n] }, o], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f3 }, { conditions: p, rules: [{ conditions: [{ [t2]: c, [u]: [n, a] }], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f3 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f3 }, { conditions: q, rules: [{ conditions: [o], rules: [{ endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f3 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f3 }, { endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dnsSuffix}", properties: m2, headers: m2 }, type: e2 }], type: f3 }], type: f3 }, { error: "Invalid Configuration: Missing Region", type: d }] };
    exports2.ruleSet = _data;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/endpointResolver.js
var require_endpointResolver5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/endpointResolver.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultEndpointResolver = void 0;
    var util_endpoints_1 = require_dist_cjs7();
    var util_endpoints_2 = require_dist_cjs6();
    var ruleset_1 = require_ruleset5();
    var defaultEndpointResolver = (endpointParams, context = {}) => {
      return (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
        endpointParams,
        logger: context.logger
      });
    };
    exports2.defaultEndpointResolver = defaultEndpointResolver;
    util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.shared.js
var require_runtimeConfig_shared5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.shared.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var core_1 = require_dist_cjs37();
    var smithy_client_1 = require_dist_cjs32();
    var url_parser_1 = require_dist_cjs16();
    var util_base64_1 = require_dist_cjs25();
    var util_utf8_1 = require_dist_cjs24();
    var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider();
    var endpointResolver_1 = require_endpointResolver5();
    var getRuntimeConfig = (config) => {
      return {
        apiVersion: "2018-08-01",
        base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
        base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
        disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
        endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
        extensions: (config == null ? void 0 : config.extensions) ?? [],
        httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultRDSDataHttpAuthSchemeProvider,
        httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new core_1.AwsSdkSigV4Signer()
          }
        ],
        logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
        serviceId: (config == null ? void 0 : config.serviceId) ?? "RDS Data",
        urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
        utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
        utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.js
var require_runtimeConfig5 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getRuntimeConfig = void 0;
    var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2));
    var package_json_1 = tslib_1.__importDefault(require_package2());
    var core_1 = require_dist_cjs37();
    var credential_provider_node_1 = require_dist_cjs59();
    var util_user_agent_node_1 = require_dist_cjs41();
    var config_resolver_1 = require_dist_cjs11();
    var hash_node_1 = require_dist_cjs42();
    var middleware_retry_1 = require_dist_cjs33();
    var node_config_provider_1 = require_dist_cjs14();
    var node_http_handler_1 = require_dist_cjs28();
    var util_body_length_node_1 = require_dist_cjs43();
    var util_retry_1 = require_dist_cjs20();
    var runtimeConfig_shared_1 = require_runtimeConfig_shared5();
    var smithy_client_1 = require_dist_cjs32();
    var util_defaults_mode_node_1 = require_dist_cjs44();
    var smithy_client_2 = require_dist_cjs32();
    var getRuntimeConfig = (config) => {
      (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
      const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
      const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
      const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
      (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
      return {
        ...clientSharedValues,
        ...config,
        runtime: "node",
        defaultsMode,
        bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
        credentialDefaultProvider: (config == null ? void 0 : config.credentialDefaultProvider) ?? credential_provider_node_1.defaultProvider,
        defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.defaultUserAgent)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
        maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS),
        region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS),
        requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
        retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
          ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
          default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
        }),
        sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
        streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
        useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS),
        useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS)
      };
    };
    exports2.getRuntimeConfig = getRuntimeConfig;
  }
});

// ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/index.js
var require_dist_cjs60 = __commonJS({
  "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.583.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/index.js"(exports2, module2) {
    "use strict";
    var __defProp3 = Object.defineProperty;
    var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp3 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp3(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps3 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp3.call(to, key) && key !== except)
            __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      AccessDeniedException: () => AccessDeniedException,
      ArrayValue: () => ArrayValue,
      BadRequestException: () => BadRequestException,
      BatchExecuteStatementCommand: () => BatchExecuteStatementCommand,
      BeginTransactionCommand: () => BeginTransactionCommand,
      CommitTransactionCommand: () => CommitTransactionCommand,
      DatabaseErrorException: () => DatabaseErrorException,
      DatabaseNotFoundException: () => DatabaseNotFoundException,
      DatabaseUnavailableException: () => DatabaseUnavailableException,
      DecimalReturnType: () => DecimalReturnType,
      ExecuteSqlCommand: () => ExecuteSqlCommand,
      ExecuteStatementCommand: () => ExecuteStatementCommand,
      Field: () => Field,
      ForbiddenException: () => ForbiddenException,
      HttpEndpointNotEnabledException: () => HttpEndpointNotEnabledException,
      InternalServerErrorException: () => InternalServerErrorException,
      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: () => import_smithy_client.Client
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_middleware_host_header = require_dist_cjs3();
    var import_middleware_logger = require_dist_cjs4();
    var import_middleware_recursion_detection = require_dist_cjs5();
    var import_middleware_user_agent = require_dist_cjs8();
    var import_config_resolver = require_dist_cjs11();
    var import_core = require_dist_cjs34();
    var import_middleware_content_length = require_dist_cjs35();
    var import_middleware_endpoint = require_dist_cjs18();
    var import_middleware_retry = require_dist_cjs33();
    var import_httpAuthSchemeProvider = require_httpAuthSchemeProvider();
    var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => {
      return {
        ...options,
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "rds-data"
      };
    }, "resolveClientEndpointParameters");
    var commonParams = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
    var import_runtimeConfig = require_runtimeConfig5();
    var import_region_config_resolver = require_dist_cjs45();
    var import_protocol_http = require_dist_cjs2();
    var import_smithy_client = require_dist_cjs32();
    var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index5 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index5 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index5, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials2) {
          _credentials = credentials2;
        },
        credentials() {
          return _credentials;
        }
      };
    }, "getHttpAuthExtensionConfiguration");
    var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    }, "resolveHttpAuthRuntimeConfig");
    var asPartial = /* @__PURE__ */ __name((t2) => t2, "asPartial");
    var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
      const extensionConfiguration = {
        ...asPartial((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig)),
        ...asPartial((0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig)),
        ...asPartial(getHttpAuthExtensionConfiguration(runtimeConfig))
      };
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return {
        ...runtimeConfig,
        ...(0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
        ...(0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration),
        ...(0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
        ...resolveHttpAuthRuntimeConfig(extensionConfiguration)
      };
    }, "resolveRuntimeExtensions");
    var _RDSDataClient = class _RDSDataClient extends import_smithy_client.Client {
      constructor(...[configuration]) {
        const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {});
        const _config_1 = resolveClientEndpointParameters(_config_0);
        const _config_2 = (0, import_config_resolver.resolveRegionConfig)(_config_1);
        const _config_3 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_2);
        const _config_4 = (0, import_middleware_retry.resolveRetryConfig)(_config_3);
        const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4);
        const _config_6 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_5);
        const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6);
        const _config_8 = resolveRuntimeExtensions(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
        super(_config_8);
        this.config = _config_8;
        this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config));
        this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config));
        this.middlewareStack.use(
          (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
            httpAuthSchemeParametersProvider: this.getDefaultHttpAuthSchemeParametersProvider(),
            identityProviderConfigProvider: this.getIdentityProviderConfigProvider()
          })
        );
        this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config));
      }
      /**
       * Destroy underlying resources, like sockets. It's usually not necessary to do this.
       * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
       * Otherwise, sockets might stay open for quite a long time before the server terminates them.
       */
      destroy() {
        super.destroy();
      }
      getDefaultHttpAuthSchemeParametersProvider() {
        return import_httpAuthSchemeProvider.defaultRDSDataHttpAuthSchemeParametersProvider;
      }
      getIdentityProviderConfigProvider() {
        return async (config) => new import_core.DefaultIdentityProviderConfig({
          "aws.auth#sigv4": config.credentials
        });
      }
    };
    __name(_RDSDataClient, "RDSDataClient");
    var RDSDataClient = _RDSDataClient;
    var import_middleware_serde = require_dist_cjs17();
    var import_types = require_dist_cjs();
    var import_core2 = require_dist_cjs37();
    var _RDSDataServiceException = class _RDSDataServiceException2 extends import_smithy_client.ServiceException {
      /**
       * @internal
       */
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, _RDSDataServiceException2.prototype);
      }
    };
    __name(_RDSDataServiceException, "RDSDataServiceException");
    var RDSDataServiceException = _RDSDataServiceException;
    var _AccessDeniedException = class _AccessDeniedException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "AccessDeniedException",
          $fault: "client",
          ...opts
        });
        this.name = "AccessDeniedException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _AccessDeniedException2.prototype);
      }
    };
    __name(_AccessDeniedException, "AccessDeniedException");
    var AccessDeniedException = _AccessDeniedException;
    var _BadRequestException = class _BadRequestException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "BadRequestException",
          $fault: "client",
          ...opts
        });
        this.name = "BadRequestException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _BadRequestException2.prototype);
      }
    };
    __name(_BadRequestException, "BadRequestException");
    var BadRequestException = _BadRequestException;
    var TypeHint = {
      DATE: "DATE",
      DECIMAL: "DECIMAL",
      JSON: "JSON",
      TIME: "TIME",
      TIMESTAMP: "TIMESTAMP",
      UUID: "UUID"
    };
    var _DatabaseErrorException = class _DatabaseErrorException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "DatabaseErrorException",
          $fault: "client",
          ...opts
        });
        this.name = "DatabaseErrorException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _DatabaseErrorException2.prototype);
      }
    };
    __name(_DatabaseErrorException, "DatabaseErrorException");
    var DatabaseErrorException = _DatabaseErrorException;
    var _DatabaseNotFoundException = class _DatabaseNotFoundException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "DatabaseNotFoundException",
          $fault: "client",
          ...opts
        });
        this.name = "DatabaseNotFoundException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _DatabaseNotFoundException2.prototype);
      }
    };
    __name(_DatabaseNotFoundException, "DatabaseNotFoundException");
    var DatabaseNotFoundException = _DatabaseNotFoundException;
    var _DatabaseUnavailableException = class _DatabaseUnavailableException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "DatabaseUnavailableException",
          $fault: "server",
          ...opts
        });
        this.name = "DatabaseUnavailableException";
        this.$fault = "server";
        Object.setPrototypeOf(this, _DatabaseUnavailableException2.prototype);
      }
    };
    __name(_DatabaseUnavailableException, "DatabaseUnavailableException");
    var DatabaseUnavailableException = _DatabaseUnavailableException;
    var _ForbiddenException = class _ForbiddenException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ForbiddenException",
          $fault: "client",
          ...opts
        });
        this.name = "ForbiddenException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _ForbiddenException2.prototype);
      }
    };
    __name(_ForbiddenException, "ForbiddenException");
    var ForbiddenException = _ForbiddenException;
    var _HttpEndpointNotEnabledException = class _HttpEndpointNotEnabledException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "HttpEndpointNotEnabledException",
          $fault: "client",
          ...opts
        });
        this.name = "HttpEndpointNotEnabledException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _HttpEndpointNotEnabledException2.prototype);
      }
    };
    __name(_HttpEndpointNotEnabledException, "HttpEndpointNotEnabledException");
    var HttpEndpointNotEnabledException = _HttpEndpointNotEnabledException;
    var _InternalServerErrorException = class _InternalServerErrorException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InternalServerErrorException",
          $fault: "server",
          ...opts
        });
        this.name = "InternalServerErrorException";
        this.$fault = "server";
        Object.setPrototypeOf(this, _InternalServerErrorException2.prototype);
      }
    };
    __name(_InternalServerErrorException, "InternalServerErrorException");
    var InternalServerErrorException = _InternalServerErrorException;
    var _InvalidSecretException = class _InvalidSecretException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "InvalidSecretException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidSecretException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _InvalidSecretException2.prototype);
      }
    };
    __name(_InvalidSecretException, "InvalidSecretException");
    var InvalidSecretException = _InvalidSecretException;
    var _SecretsErrorException = class _SecretsErrorException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "SecretsErrorException",
          $fault: "client",
          ...opts
        });
        this.name = "SecretsErrorException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _SecretsErrorException2.prototype);
      }
    };
    __name(_SecretsErrorException, "SecretsErrorException");
    var SecretsErrorException = _SecretsErrorException;
    var _ServiceUnavailableError = class _ServiceUnavailableError2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "ServiceUnavailableError",
          $fault: "server",
          ...opts
        });
        this.name = "ServiceUnavailableError";
        this.$fault = "server";
        Object.setPrototypeOf(this, _ServiceUnavailableError2.prototype);
      }
    };
    __name(_ServiceUnavailableError, "ServiceUnavailableError");
    var ServiceUnavailableError = _ServiceUnavailableError;
    var _StatementTimeoutException = class _StatementTimeoutException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "StatementTimeoutException",
          $fault: "client",
          ...opts
        });
        this.name = "StatementTimeoutException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _StatementTimeoutException2.prototype);
        this.dbConnectionId = opts.dbConnectionId;
      }
    };
    __name(_StatementTimeoutException, "StatementTimeoutException");
    var StatementTimeoutException = _StatementTimeoutException;
    var _TransactionNotFoundException = class _TransactionNotFoundException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "TransactionNotFoundException",
          $fault: "client",
          ...opts
        });
        this.name = "TransactionNotFoundException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _TransactionNotFoundException2.prototype);
      }
    };
    __name(_TransactionNotFoundException, "TransactionNotFoundException");
    var TransactionNotFoundException = _TransactionNotFoundException;
    var _NotFoundException = class _NotFoundException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "NotFoundException",
          $fault: "client",
          ...opts
        });
        this.name = "NotFoundException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _NotFoundException2.prototype);
      }
    };
    __name(_NotFoundException, "NotFoundException");
    var NotFoundException = _NotFoundException;
    var DecimalReturnType = {
      DOUBLE_OR_LONG: "DOUBLE_OR_LONG",
      STRING: "STRING"
    };
    var RecordsFormatType = {
      JSON: "JSON",
      NONE: "NONE"
    };
    var LongReturnType = {
      LONG: "LONG",
      STRING: "STRING"
    };
    var _UnsupportedResultException = class _UnsupportedResultException2 extends RDSDataServiceException {
      /**
       * @internal
       */
      constructor(opts) {
        super({
          name: "UnsupportedResultException",
          $fault: "client",
          ...opts
        });
        this.name = "UnsupportedResultException";
        this.$fault = "client";
        Object.setPrototypeOf(this, _UnsupportedResultException2.prototype);
      }
    };
    __name(_UnsupportedResultException, "UnsupportedResultException");
    var UnsupportedResultException = _UnsupportedResultException;
    var ArrayValue;
    ((ArrayValue2) => {
      ArrayValue2.visit = /* @__PURE__ */ __name((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]);
      }, "visit");
    })(ArrayValue || (ArrayValue = {}));
    var Field;
    ((Field2) => {
      Field2.visit = /* @__PURE__ */ __name((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]);
      }, "visit");
    })(Field || (Field = {}));
    var Value;
    ((Value3) => {
      Value3.visit = /* @__PURE__ */ __name((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]);
      }, "visit");
    })(Value || (Value = {}));
    var se_BatchExecuteStatementCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/BatchExecute");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          database: [],
          parameterSets: (_2) => se_SqlParameterSets(_2, context),
          resourceArn: [],
          schema: [],
          secretArn: [],
          sql: [],
          transactionId: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_BatchExecuteStatementCommand");
    var se_BeginTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/BeginTransaction");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          database: [],
          resourceArn: [],
          schema: [],
          secretArn: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_BeginTransactionCommand");
    var se_CommitTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/CommitTransaction");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          resourceArn: [],
          secretArn: [],
          transactionId: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_CommitTransactionCommand");
    var se_ExecuteSqlCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/ExecuteSql");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          awsSecretStoreArn: [],
          database: [],
          dbClusterOrInstanceArn: [],
          schema: [],
          sqlStatements: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_ExecuteSqlCommand");
    var se_ExecuteStatementCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/Execute");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          continueAfterTimeout: [],
          database: [],
          formatRecordsAs: [],
          includeResultMetadata: [],
          parameters: (_2) => se_SqlParametersList(_2, context),
          resourceArn: [],
          resultSetOptions: (_2) => (0, import_smithy_client._json)(_2),
          schema: [],
          secretArn: [],
          sql: [],
          transactionId: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_ExecuteStatementCommand");
    var se_RollbackTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
      const b = (0, import_core.requestBuilder)(input, context);
      const headers = {
        "content-type": "application/json"
      };
      b.bp("/RollbackTransaction");
      let body;
      body = JSON.stringify(
        (0, import_smithy_client.take)(input, {
          resourceArn: [],
          secretArn: [],
          transactionId: []
        })
      );
      b.m("POST").h(headers).b(body);
      return b.build();
    }, "se_RollbackTransactionCommand");
    var de_BatchExecuteStatementCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        updateResults: (_2) => de_UpdateResults(_2, context)
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_BatchExecuteStatementCommand");
    var de_BeginTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        transactionId: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_BeginTransactionCommand");
    var de_CommitTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        transactionStatus: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_CommitTransactionCommand");
    var de_ExecuteSqlCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        sqlStatementResults: (_2) => de_SqlStatementResults(_2, context)
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ExecuteSqlCommand");
    var de_ExecuteStatementCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        columnMetadata: import_smithy_client._json,
        formattedRecords: import_smithy_client.expectString,
        generatedFields: (_2) => de_FieldList(_2, context),
        numberOfRecordsUpdated: import_smithy_client.expectLong,
        records: (_2) => de_SqlRecords(_2, context)
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_ExecuteStatementCommand");
    var de_RollbackTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
      if (output.statusCode !== 200 && output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const contents = (0, import_smithy_client.map)({
        $metadata: deserializeMetadata(output)
      });
      const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body");
      const doc = (0, import_smithy_client.take)(data, {
        transactionStatus: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      return contents;
    }, "de_RollbackTransactionCommand");
    var de_CommandError = /* @__PURE__ */ __name(async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await (0, import_core2.parseJsonErrorBody)(output.body, context)
      };
      const errorCode = (0, import_core2.loadRestJsonErrorCode)(output, parsedOutput.body);
      switch (errorCode) {
        case "AccessDeniedException":
        case "com.amazonaws.rdsdata#AccessDeniedException":
          throw await de_AccessDeniedExceptionRes(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 "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 "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 throwDefaultError({
            output,
            parsedBody,
            errorCode
          });
      }
    }, "de_CommandError");
    var throwDefaultError = (0, import_smithy_client.withBaseException)(RDSDataServiceException);
    var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new AccessDeniedException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_AccessDeniedExceptionRes");
    var de_BadRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new BadRequestException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_BadRequestExceptionRes");
    var de_DatabaseErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseErrorException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_DatabaseErrorExceptionRes");
    var de_DatabaseNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new DatabaseNotFoundException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_DatabaseNotFoundExceptionRes");
    var de_DatabaseUnavailableExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {});
      Object.assign(contents, doc);
      const exception = new DatabaseUnavailableException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_DatabaseUnavailableExceptionRes");
    var de_ForbiddenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new ForbiddenException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ForbiddenExceptionRes");
    var de_HttpEndpointNotEnabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new HttpEndpointNotEnabledException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_HttpEndpointNotEnabledExceptionRes");
    var de_InternalServerErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {});
      Object.assign(contents, doc);
      const exception = new InternalServerErrorException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InternalServerErrorExceptionRes");
    var de_InvalidSecretExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new InvalidSecretException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_InvalidSecretExceptionRes");
    var de_NotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new NotFoundException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_NotFoundExceptionRes");
    var de_SecretsErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new SecretsErrorException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_SecretsErrorExceptionRes");
    var de_ServiceUnavailableErrorRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {});
      Object.assign(contents, doc);
      const exception = new ServiceUnavailableError({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_ServiceUnavailableErrorRes");
    var de_StatementTimeoutExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        dbConnectionId: import_smithy_client.expectLong,
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new StatementTimeoutException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_StatementTimeoutExceptionRes");
    var de_TransactionNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new TransactionNotFoundException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_TransactionNotFoundExceptionRes");
    var de_UnsupportedResultExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
      const contents = (0, import_smithy_client.map)({});
      const data = parsedOutput.body;
      const doc = (0, import_smithy_client.take)(data, {
        message: import_smithy_client.expectString
      });
      Object.assign(contents, doc);
      const exception = new UnsupportedResultException({
        $metadata: deserializeMetadata(parsedOutput),
        ...contents
      });
      return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body);
    }, "de_UnsupportedResultExceptionRes");
    var se_ArrayOfArray = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e2) => e2 != null).map((entry) => {
        return se_ArrayValue(entry, context);
      });
    }, "se_ArrayOfArray");
    var se_ArrayValue = /* @__PURE__ */ __name((input, context) => {
      return ArrayValue.visit(input, {
        arrayValues: (value) => ({ arrayValues: se_ArrayOfArray(value, context) }),
        booleanValues: (value) => ({ booleanValues: (0, import_smithy_client._json)(value) }),
        doubleValues: (value) => ({ doubleValues: se_DoubleArray(value, context) }),
        longValues: (value) => ({ longValues: (0, import_smithy_client._json)(value) }),
        stringValues: (value) => ({ stringValues: (0, import_smithy_client._json)(value) }),
        _: (name, value) => ({ name: value })
      });
    }, "se_ArrayValue");
    var se_DoubleArray = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e2) => e2 != null).map((entry) => {
        return (0, import_smithy_client.serializeFloat)(entry);
      });
    }, "se_DoubleArray");
    var se_Field = /* @__PURE__ */ __name((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: (0, import_smithy_client.serializeFloat)(value) }),
        isNull: (value) => ({ isNull: value }),
        longValue: (value) => ({ longValue: value }),
        stringValue: (value) => ({ stringValue: value }),
        _: (name, value) => ({ name: value })
      });
    }, "se_Field");
    var se_SqlParameter = /* @__PURE__ */ __name((input, context) => {
      return (0, import_smithy_client.take)(input, {
        name: [],
        typeHint: [],
        value: (_2) => se_Field(_2, context)
      });
    }, "se_SqlParameter");
    var se_SqlParameterSets = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e2) => e2 != null).map((entry) => {
        return se_SqlParametersList(entry, context);
      });
    }, "se_SqlParameterSets");
    var se_SqlParametersList = /* @__PURE__ */ __name((input, context) => {
      return input.filter((e2) => e2 != null).map((entry) => {
        return se_SqlParameter(entry, context);
      });
    }, "se_SqlParametersList");
    var de_ArrayOfArray = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de_ArrayValue((0, import_core2.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_ArrayOfArray");
    var de_ArrayValue = /* @__PURE__ */ __name((output, context) => {
      if (output.arrayValues != null) {
        return {
          arrayValues: de_ArrayOfArray(output.arrayValues, context)
        };
      }
      if (output.booleanValues != null) {
        return {
          booleanValues: (0, import_smithy_client._json)(output.booleanValues)
        };
      }
      if (output.doubleValues != null) {
        return {
          doubleValues: de_DoubleArray(output.doubleValues, context)
        };
      }
      if (output.longValues != null) {
        return {
          longValues: (0, import_smithy_client._json)(output.longValues)
        };
      }
      if (output.stringValues != null) {
        return {
          stringValues: (0, import_smithy_client._json)(output.stringValues)
        };
      }
      return { $unknown: Object.entries(output)[0] };
    }, "de_ArrayValue");
    var de_ArrayValueList = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de_Value((0, import_core2.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_ArrayValueList");
    var de_DoubleArray = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return (0, import_smithy_client.limitedParseDouble)(entry);
      });
      return retVal;
    }, "de_DoubleArray");
    var de_Field = /* @__PURE__ */ __name((output, context) => {
      if (output.arrayValue != null) {
        return {
          arrayValue: de_ArrayValue((0, import_core2.awsExpectUnion)(output.arrayValue), context)
        };
      }
      if (output.blobValue != null) {
        return {
          blobValue: context.base64Decoder(output.blobValue)
        };
      }
      if ((0, import_smithy_client.expectBoolean)(output.booleanValue) !== void 0) {
        return { booleanValue: (0, import_smithy_client.expectBoolean)(output.booleanValue) };
      }
      if ((0, import_smithy_client.limitedParseDouble)(output.doubleValue) !== void 0) {
        return { doubleValue: (0, import_smithy_client.limitedParseDouble)(output.doubleValue) };
      }
      if ((0, import_smithy_client.expectBoolean)(output.isNull) !== void 0) {
        return { isNull: (0, import_smithy_client.expectBoolean)(output.isNull) };
      }
      if ((0, import_smithy_client.expectLong)(output.longValue) !== void 0) {
        return { longValue: (0, import_smithy_client.expectLong)(output.longValue) };
      }
      if ((0, import_smithy_client.expectString)(output.stringValue) !== void 0) {
        return { stringValue: (0, import_smithy_client.expectString)(output.stringValue) };
      }
      return { $unknown: Object.entries(output)[0] };
    }, "de_Field");
    var de_FieldList = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de_Field((0, import_core2.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_FieldList");
    var de__Record = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client.take)(output, {
        values: (_2) => de_Row(_2, context)
      });
    }, "de__Record");
    var de_Records = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de__Record(entry, context);
      });
      return retVal;
    }, "de_Records");
    var de_ResultFrame = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client.take)(output, {
        records: (_2) => de_Records(_2, context),
        resultSetMetadata: import_smithy_client._json
      });
    }, "de_ResultFrame");
    var de_Row = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de_Value((0, import_core2.awsExpectUnion)(entry), context);
      });
      return retVal;
    }, "de_Row");
    var de_SqlRecords = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de_FieldList(entry, context);
      });
      return retVal;
    }, "de_SqlRecords");
    var de_SqlStatementResult = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client.take)(output, {
        numberOfRecordsUpdated: import_smithy_client.expectLong,
        resultFrame: (_2) => de_ResultFrame(_2, context)
      });
    }, "de_SqlStatementResult");
    var de_SqlStatementResults = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de_SqlStatementResult(entry, context);
      });
      return retVal;
    }, "de_SqlStatementResults");
    var de_StructValue = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client.take)(output, {
        attributes: (_2) => de_ArrayValueList(_2, context)
      });
    }, "de_StructValue");
    var de_UpdateResult = /* @__PURE__ */ __name((output, context) => {
      return (0, import_smithy_client.take)(output, {
        generatedFields: (_2) => de_FieldList(_2, context)
      });
    }, "de_UpdateResult");
    var de_UpdateResults = /* @__PURE__ */ __name((output, context) => {
      const retVal = (output || []).filter((e2) => e2 != null).map((entry) => {
        return de_UpdateResult(entry, context);
      });
      return retVal;
    }, "de_UpdateResults");
    var de_Value = /* @__PURE__ */ __name((output, context) => {
      if (output.arrayValues != null) {
        return {
          arrayValues: de_ArrayValueList(output.arrayValues, context)
        };
      }
      if ((0, import_smithy_client.expectLong)(output.bigIntValue) !== void 0) {
        return { bigIntValue: (0, import_smithy_client.expectLong)(output.bigIntValue) };
      }
      if ((0, import_smithy_client.expectBoolean)(output.bitValue) !== void 0) {
        return { bitValue: (0, import_smithy_client.expectBoolean)(output.bitValue) };
      }
      if (output.blobValue != null) {
        return {
          blobValue: context.base64Decoder(output.blobValue)
        };
      }
      if ((0, import_smithy_client.limitedParseDouble)(output.doubleValue) !== void 0) {
        return { doubleValue: (0, import_smithy_client.limitedParseDouble)(output.doubleValue) };
      }
      if ((0, import_smithy_client.expectInt32)(output.intValue) !== void 0) {
        return { intValue: (0, import_smithy_client.expectInt32)(output.intValue) };
      }
      if ((0, import_smithy_client.expectBoolean)(output.isNull) !== void 0) {
        return { isNull: (0, import_smithy_client.expectBoolean)(output.isNull) };
      }
      if ((0, import_smithy_client.limitedParseFloat32)(output.realValue) !== void 0) {
        return { realValue: (0, import_smithy_client.limitedParseFloat32)(output.realValue) };
      }
      if ((0, import_smithy_client.expectString)(output.stringValue) !== void 0) {
        return { stringValue: (0, import_smithy_client.expectString)(output.stringValue) };
      }
      if (output.structValue != null) {
        return {
          structValue: de_StructValue(output.structValue, context)
        };
      }
      return { $unknown: Object.entries(output)[0] };
    }, "de_Value");
    var deserializeMetadata = /* @__PURE__ */ __name((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"]
    }), "deserializeMetadata");
    var _BatchExecuteStatementCommand = class _BatchExecuteStatementCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "BatchExecuteStatement", {}).n("RDSDataClient", "BatchExecuteStatementCommand").f(void 0, void 0).ser(se_BatchExecuteStatementCommand).de(de_BatchExecuteStatementCommand).build() {
    };
    __name(_BatchExecuteStatementCommand, "BatchExecuteStatementCommand");
    var BatchExecuteStatementCommand = _BatchExecuteStatementCommand;
    var _BeginTransactionCommand = class _BeginTransactionCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "BeginTransaction", {}).n("RDSDataClient", "BeginTransactionCommand").f(void 0, void 0).ser(se_BeginTransactionCommand).de(de_BeginTransactionCommand).build() {
    };
    __name(_BeginTransactionCommand, "BeginTransactionCommand");
    var BeginTransactionCommand = _BeginTransactionCommand;
    var _CommitTransactionCommand = class _CommitTransactionCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "CommitTransaction", {}).n("RDSDataClient", "CommitTransactionCommand").f(void 0, void 0).ser(se_CommitTransactionCommand).de(de_CommitTransactionCommand).build() {
    };
    __name(_CommitTransactionCommand, "CommitTransactionCommand");
    var CommitTransactionCommand = _CommitTransactionCommand;
    var _ExecuteSqlCommand = class _ExecuteSqlCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "ExecuteSql", {}).n("RDSDataClient", "ExecuteSqlCommand").f(void 0, void 0).ser(se_ExecuteSqlCommand).de(de_ExecuteSqlCommand).build() {
    };
    __name(_ExecuteSqlCommand, "ExecuteSqlCommand");
    var ExecuteSqlCommand = _ExecuteSqlCommand;
    var _ExecuteStatementCommand = class _ExecuteStatementCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "ExecuteStatement", {}).n("RDSDataClient", "ExecuteStatementCommand").f(void 0, void 0).ser(se_ExecuteStatementCommand).de(de_ExecuteStatementCommand).build() {
    };
    __name(_ExecuteStatementCommand, "ExecuteStatementCommand");
    var ExecuteStatementCommand = _ExecuteStatementCommand;
    var _RollbackTransactionCommand = class _RollbackTransactionCommand extends import_smithy_client.Command.classBuilder().ep({
      ...commonParams
    }).m(function(Command, cs, config, o) {
      return [
        (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize),
        (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
      ];
    }).s("RdsDataService", "RollbackTransaction", {}).n("RDSDataClient", "RollbackTransactionCommand").f(void 0, void 0).ser(se_RollbackTransactionCommand).de(de_RollbackTransactionCommand).build() {
    };
    __name(_RollbackTransactionCommand, "RollbackTransactionCommand");
    var RollbackTransactionCommand = _RollbackTransactionCommand;
    var commands = {
      BatchExecuteStatementCommand,
      BeginTransactionCommand,
      CommitTransactionCommand,
      ExecuteSqlCommand,
      ExecuteStatementCommand,
      RollbackTransactionCommand
    };
    var _RDSData = class _RDSData extends RDSDataClient {
    };
    __name(_RDSData, "RDSData");
    var RDSData = _RDSData;
    (0, import_smithy_client.createAggregatedClient)(commands, RDSData);
  }
});

// src/cli/connections.ts
var connections_exports = {};
__export(connections_exports, {
  connectToLibSQL: () => connectToLibSQL,
  connectToMySQL: () => connectToMySQL,
  connectToSQLite: () => connectToSQLite,
  connectToSingleStore: () => connectToSingleStore,
  preparePostgresDB: () => preparePostgresDB
});
var preparePostgresDB, 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_utils2();
    init_utils5();
    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, ExecuteStatementCommand, TypeHint } = await Promise.resolve().then(() => __toESM(require_dist_cjs60()));
          const { AwsDataApiSession, drizzle } = await import("drizzle-orm/aws-data-api/pg");
          const { migrate: migrate2 } = await import("drizzle-orm/aws-data-api/pg/migrator");
          const { PgDialect: PgDialect2 } = await import("drizzle-orm/pg-core");
          const config = {
            database: credentials2.database,
            resourceArn: credentials2.resourceArn,
            secretArn: credentials2.secretArn
          };
          const rdsClient = new RDSDataClient();
          const session = new AwsDataApiSession(
            rdsClient,
            new PgDialect2(),
            void 0,
            config,
            void 0
          );
          const db = drizzle(rdsClient, config);
          const migrateFn = async (config2) => {
            return migrate2(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;
          };
          return {
            query,
            proxy,
            migrate: migrateFn
          };
        }
        if (driver2 === "pglite") {
          assertPackages("@electric-sql/pglite");
          const { PGlite, types: types3 } = await import("@electric-sql/pglite");
          const { drizzle } = await import("drizzle-orm/pglite");
          const { migrate: migrate2 } = await import("drizzle-orm/pglite/migrator");
          const pglite = new PGlite(normalisePGliteUrl(credentials2.url));
          await pglite.waitReady;
          const drzl = drizzle(pglite);
          const migrateFn = async (config) => {
            return migrate2(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;
          };
          return { query, proxy, migrate: migrateFn };
        }
        assertUnreachable(driver2);
      }
      if (await checkPackage("pg")) {
        console.log(withStyle.info(`Using 'pg' driver for database querying`));
        const { default: pg } = await import("pg");
        const { drizzle } = await import("drizzle-orm/node-postgres");
        const { migrate: migrate2 } = await import("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 migrate2(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;
        };
        return { query, proxy, migrate: migrateFn };
      }
      if (await checkPackage("postgres")) {
        console.log(
          withStyle.info(`Using 'postgres' driver for database querying`)
        );
        const postgres = await import("postgres");
        const { drizzle } = await import("drizzle-orm/postgres-js");
        const { migrate: migrate2 } = await import("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 migrate2(db, config);
        };
        const query = async (sql, params) => {
          const result = await client.unsafe(sql, params ?? []);
          return result;
        };
        const proxy = async (params) => {
          if (params.mode === "object") {
            return await client.unsafe(params.sql, params.params);
          }
          return await client.unsafe(params.sql, params.params).values();
        };
        return { query, proxy, 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 } = await import("@vercel/postgres");
        const { drizzle } = await import("drizzle-orm/vercel-postgres");
        const { migrate: migrate2 } = await import("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 migrate2(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;
        };
        return { query, proxy, 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 } = await import("@neondatabase/serverless");
        const { drizzle } = await import("drizzle-orm/neon-serverless");
        const { migrate: migrate2 } = await import("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 migrate2(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;
        };
        return { query, proxy, migrate: migrateFn };
      }
      console.error(
        "To connect to Postgres database - please install either of 'pg', 'postgres', '@neondatabase/serverless' or '@vercel/postgres' drivers"
      );
      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 } = await import("mysql2/promise");
        const { drizzle } = await import("drizzle-orm/singlestore");
        const { migrate: migrate2 } = await import("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 migrate2(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];
        };
        return {
          db: { query },
          proxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      console.error(
        "To connect to SingleStore database - please install 'singlestore' 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 } = await import("mysql2/promise");
        const { drizzle } = await import("drizzle-orm/mysql2");
        const { migrate: migrate2 } = await import("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 migrate2(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];
        };
        return {
          db: { query },
          proxy,
          database: result.database,
          migrate: migrateFn
        };
      }
      if (await checkPackage("@planetscale/database")) {
        const { Client } = await import("@planetscale/database");
        const { drizzle } = await import("drizzle-orm/planetscale-serverless");
        const { migrate: migrate2 } = await import("drizzle-orm/planetscale-serverless/migrator");
        const connection = new Client(result);
        const db = drizzle(connection);
        const migrateFn = async (config) => {
          return migrate2(db, config);
        };
        const query = async (sql, params) => {
          const res = await connection.execute(sql, params);
          return res.rows;
        };
        const proxy = async (params) => {
          const result2 = params.mode === "object" ? await connection.execute(params.sql, params.params) : await connection.execute(params.sql, params.params, {
            as: "array"
          });
          return result2.rows;
        };
        return {
          db: { query },
          proxy,
          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 } = await import("drizzle-orm/sqlite-proxy");
          const { migrate: migrate2 } = await import("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 drzl = drizzle(remoteCallback);
          const migrateFn = async (config) => {
            return migrate2(
              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 = {
            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;
            }
          };
          return { ...db, ...proxy, migrate: migrateFn };
        } else {
          assertUnreachable(driver2);
        }
      }
      if (await checkPackage("@libsql/client")) {
        const { createClient } = await import("@libsql/client");
        const { drizzle } = await import("drizzle-orm/libsql");
        const { migrate: migrate2 } = await import("drizzle-orm/libsql/migrator");
        const client = createClient({
          url: normaliseSQLiteUrl(credentials2.url, "libsql")
        });
        const drzl = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(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 = {
          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;
            }
          }
        };
        return { ...db, ...proxy, migrate: migrateFn };
      }
      if (await checkPackage("better-sqlite3")) {
        const { default: Database } = await import("better-sqlite3");
        const { drizzle } = await import("drizzle-orm/better-sqlite3");
        const { migrate: migrate2 } = await import("drizzle-orm/better-sqlite3/migrator");
        const sqlite = new Database(
          normaliseSQLiteUrl(credentials2.url, "better-sqlite")
        );
        const drzl = drizzle(sqlite);
        const migrateFn = async (config) => {
          return migrate2(drzl, config);
        };
        const db = {
          query: async (sql, params = []) => {
            return sqlite.prepare(sql).bind(params).all();
          },
          run: async (query) => {
            sqlite.prepare(query).run();
          }
        };
        const proxy = {
          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);
            }
            return sqlite.prepare(params.sql).run(preparedParams);
          }
        };
        return { ...db, ...proxy, 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 } = await import("@libsql/client");
        const { drizzle } = await import("drizzle-orm/libsql");
        const { migrate: migrate2 } = await import("drizzle-orm/libsql/migrator");
        const client = createClient({
          url: normaliseSQLiteUrl(credentials2.url, "libsql"),
          authToken: credentials2.authToken
        });
        const drzl = drizzle(client);
        const migrateFn = async (config) => {
          return migrate2(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 = {
          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;
            }
          }
        };
        return { ...db, ...proxy, migrate: migrateFn };
      }
      console.log(
        "Please install '@libsql/client' for Drizzle Kit to connect to LibSQL databases"
      );
      process.exit(1);
    };
  }
});

// src/cli/selector-ui.ts
var import_hanji5, Select;
var init_selector_ui = __esm({
  "src/cli/selector-ui.ts"() {
    "use strict";
    init_source();
    import_hanji5 = __toESM(require_hanji());
    Select = class extends import_hanji5.Prompt {
      constructor(items) {
        super();
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.on("detach", (terminal) => terminal.toggleCursor("show"));
        this.data = new import_hanji5.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/cli/commands/libSqlPushUtils.ts
var getOldTableName2, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
var init_libSqlPushUtils = __esm({
  "src/cli/commands/libSqlPushUtils.ts"() {
    "use strict";
    init_source();
    init_utils2();
    init_sqliteSchema();
    init_sqlgenerator();
    getOldTableName2 = (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;
    };
    _moveDataStatements2 = (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 fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
      const mappedCheckConstraints = checkConstraints.map(
        (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
      );
      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(
          (c) => `"${c}"`
        );
        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;
    };
    libSqlLogSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      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], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "alter_table_drop_column") {
          const tableName = statement.tableName;
          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 delete ${source_default.underline(
                statement.columnName
              )} column in ${tableName} table with ${count} items`
            );
            columnsToRemove.push(`${tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "sqlite_alter_table_add_column" && statement.column.notNull && !statement.column.default) {
          const newTableName = statement.tableName;
          const res = await connection.query(
            `select count(*) as count from \`${newTableName}\``
          );
          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(newTableName);
            statementsToExecute.push(`delete from ${newTableName};`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          const tableName = statement.tableName;
          if (statement.type === "alter_table_alter_column_set_notnull" && typeof statement.columnDefault === "undefined") {
            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 constraint to ${source_default.underline(
                  statement.columnName
                )} column without default value, which contains ${count} items`
              );
              tablesToTruncate.push(tableName);
              statementsToExecute.push(`delete from \`${tableName}\``);
              shouldAskForApprove = true;
            }
          }
          const modifyStatements = new LibSQLModifyColumn().convert(statement, json2);
          statementsToExecute.push(
            ...Array.isArray(modifyStatements) ? modifyStatements : [modifyStatements]
          );
        } else if (statement.type === "recreate_table") {
          const tableName = statement.tableName;
          let dataLoss = false;
          const oldTableName = getOldTableName2(tableName, meta);
          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 table5 of Object.values(json2.tables)) {
            const tablesRefs = Object.values(json2.tables[table5.name].foreignKeys).filter((t2) => SQLiteSquasher.unsquashPushFK(t2).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
            tablesReferencingCurrent.push(...tablesRefs);
          }
          if (!tablesReferencingCurrent.length) {
            statementsToExecute.push(..._moveDataStatements2(tableName, json2, dataLoss));
            continue;
          }
          statementsToExecute.push(
            ..._moveDataStatements2(tableName, json2, dataLoss)
          );
        } else if (statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") {
          const tableName = statement.tableName;
          const res = await connection.query(
            `select count("${statement.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(
                statement.columnName
              )} column in ${tableName} table with ${count} items`
            );
            columnsToRemove.push(`${tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else {
          const fromJsonStatement = fromJson([statement], "turso", "push", json2);
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        }
      }
      return {
        statementsToExecute: [...new Set(statementsToExecute)],
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/mysqlPushUtils.ts
var import_hanji6, filterStatements, logSuggestionsAndReturn2;
var init_mysqlPushUtils = __esm({
  "src/cli/commands/mysqlPushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji6 = __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 == null ? void 0 : serialStatement.oldDataType.startsWith("bigint unsigned")) && (serialStatement == null ? void 0 : 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(
            (column9) => column9.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(
            (column9) => column9.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_hanji6.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if ((data == null ? void 0 : 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/pgPushUtils.ts
function concatSchemaAndTableName(schema6, table5) {
  return schema6 ? `"${schema6}"."${table5}"` : `"${table5}"`;
}
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 import_hanji7, pgSuggestions;
var init_pgPushUtils = __esm({
  "src/cli/commands/pgPushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji7 = __toESM(require_hanji());
    init_pgSchema();
    init_sqlgenerator();
    init_selector_ui();
    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_hanji7.render)(
              new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
            );
            if ((data == null ? void 0 : 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/singlestorePushUtils.ts
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_hanji8, filterStatements2, logSuggestionsAndReturn3;
var init_singlestorePushUtils = __esm({
  "src/cli/commands/singlestorePushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji8 = __toESM(require_hanji());
    init_sqlgenerator();
    init_singlestoreSchema();
    init_utils2();
    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 == null ? void 0 : serialStatement.oldDataType.startsWith("bigint unsigned")) && (serialStatement == null ? void 0 : 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(
            (column9) => column9.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(
            (column9) => column9.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_hanji8.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if ((data == null ? void 0 : 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 column9 of columnWithChangedType) {
            const [res] = await db.query(
              `select count(*) as count from \`${tableName}\` WHERE \`${tableName}\`.\`${column9}\` 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(
                  column9
                )} 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)]
      };
    };
  }
});

// ../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"() {
    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 = (s2) => s2.replace(/[[\]\\-]/g, "\\$&");
    regexpEscape = (s2) => s2.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 i2 = pos + 1;
      let sawStart = false;
      let uflag = false;
      let escaping = false;
      let negate = false;
      let endPos = pos;
      let rangeStart = "";
      WHILE:
        while (i2 < glob2.length) {
          const c = glob2.charAt(i2);
          if ((c === "!" || c === "^") && i2 === pos + 1) {
            negate = true;
            i2++;
            continue;
          }
          if (c === "]" && sawStart && !escaping) {
            endPos = i2 + 1;
            break;
          }
          sawStart = true;
          if (c === "\\") {
            if (!escaping) {
              escaping = true;
              i2++;
              continue;
            }
          }
          if (c === "[" && !escaping) {
            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
              if (glob2.startsWith(cls, i2)) {
                if (rangeStart) {
                  return ["$.", false, glob2.length - pos, true];
                }
                i2 += cls.length;
                if (neg)
                  negs.push(unip);
                else
                  ranges.push(unip);
                uflag = uflag || u;
                continue WHILE;
              }
            }
          }
          escaping = false;
          if (rangeStart) {
            if (c > rangeStart) {
              ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
            } else if (c === rangeStart) {
              ranges.push(braceEscape(c));
            }
            rangeStart = "";
            i2++;
            continue;
          }
          if (glob2.startsWith("-]", i2 + 1)) {
            ranges.push(braceEscape(c + "-"));
            i2 += 2;
            continue;
          }
          if (glob2.startsWith("-", i2 + 1)) {
            rangeStart = c;
            i2 += 2;
            continue;
          }
          ranges.push(braceEscape(c));
          i2++;
        }
      if (endPos < i2) {
        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]) && !negate) {
        const r2 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
        return [regexpEscape(r2), false, endPos - pos, false];
      }
      const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
      const snegs = "[" + (negate ? "" : "^") + 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"() {
    escape = (s2, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s2.replace(/[?*()[\]]/g, "[$&]") : s2.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"() {
    unescape2 = (s2, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s2.replace(/\[([^\/\\])\]/g, "$1") : s2.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, path3, 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"() {
    import_brace_expansion = __toESM(require_brace_expansion(), 1);
    init_brace_expressions();
    init_escape();
    init_unescape();
    init_escape();
    init_unescape();
    minimatch = (p, pattern, options = {}) => {
      assertValidPattern(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch(pattern, options).match(p);
    };
    starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
    starDotExtTest = (ext2) => (f3) => !f3.startsWith(".") && f3.endsWith(ext2);
    starDotExtTestDot = (ext2) => (f3) => f3.endsWith(ext2);
    starDotExtTestNocase = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f3) => !f3.startsWith(".") && f3.toLowerCase().endsWith(ext2);
    };
    starDotExtTestNocaseDot = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f3) => f3.toLowerCase().endsWith(ext2);
    };
    starDotStarRE = /^\*+\.\*+$/;
    starDotStarTest = (f3) => !f3.startsWith(".") && f3.includes(".");
    starDotStarTestDot = (f3) => f3 !== "." && f3 !== ".." && f3.includes(".");
    dotStarRE = /^\.\*+$/;
    dotStarTest = (f3) => f3 !== "." && f3 !== ".." && f3.startsWith(".");
    starRE = /^\*+$/;
    starTest = (f3) => f3.length !== 0 && !f3.startsWith(".");
    starTestDot = (f3) => f3.length !== 0 && f3 !== "." && f3 !== "..";
    qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
    qmarksTestNocase = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f3) => noext(f3) && f3.toLowerCase().endsWith(ext2);
    };
    qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f3) => noext(f3) && f3.toLowerCase().endsWith(ext2);
    };
    qmarksTestDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      return !ext2 ? noext : (f3) => noext(f3) && f3.endsWith(ext2);
    };
    qmarksTest = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      return !ext2 ? noext : (f3) => noext(f3) && f3.endsWith(ext2);
    };
    qmarksTestNoExt = ([$0]) => {
      const len = $0.length;
      return (f3) => f3.length === len && !f3.startsWith(".");
    };
    qmarksTestNoExtDot = ([$0]) => {
      const len = $0.length;
      return (f3) => f3.length === len && f3 !== "." && f3 !== "..";
    };
    defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
    path3 = {
      win32: { sep: "\\" },
      posix: { sep: "/" }
    };
    sep = defaultPlatform === "win32" ? path3.win32.sep : path3.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 = (s2) => s2.split("").reduce((set, c) => {
      set[c] = true;
      return set;
    }, {});
    reSpecials = charSet("().*{}+?[]^$\\!");
    addPatternStartSet = charSet("[.(");
    filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
    minimatch.filter = filter;
    ext = (a, b = {}) => Object.assign({}, a, b);
    defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch;
      }
      const orig = minimatch;
      const m2 = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
      return Object.assign(m2, {
        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: (s2, options = {}) => orig.unescape(s2, ext(def, options)),
        escape: (s2, options = {}) => orig.escape(s2, 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((f3) => mm.match(f3));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    minimatch.match = match;
    globUnescape = (s2) => s2.replace(/\\(.)/g, "$1");
    globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
    regExpEscape = (s2) => s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    Minimatch = class {
      options;
      set;
      pattern;
      windowsPathsNoEscape;
      nonegate;
      negate;
      comment;
      empty;
      preserveMultipleSlashes;
      partial;
      globSet;
      globParts;
      nocase;
      isWindows;
      platform;
      windowsNoMagicRoot;
      regexp;
      constructor(pattern, options = {}) {
        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(..._2) {
      }
      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((s2) => this.slashSplit(s2));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        let set = this.globParts.map((s2, _2, __) => {
          if (this.isWindows && this.windowsNoMagicRoot) {
            const isUNC = s2[0] === "" && s2[1] === "" && (s2[2] === "?" || !globMagic.test(s2[2])) && !globMagic.test(s2[3]);
            const isDrive = /^[a-z]:/i.test(s2[0]);
            if (isUNC) {
              return [...s2.slice(0, 4), ...s2.slice(4).map((ss) => this.parse(ss))];
            } else if (isDrive) {
              return [s2[0], ...s2.slice(1).map((ss) => this.parse(ss))];
            }
          }
          return s2.map((ss) => this.parse(ss));
        });
        this.debug(this.pattern, set);
        this.set = set.filter((s2) => s2.indexOf(false) === -1);
        if (this.isWindows) {
          for (let i2 = 0; i2 < this.set.length; i2++) {
            const p = this.set[i2];
            if (p[0] === "" && p[1] === "" && this.globParts[i2][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
              p[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 i2 = 0; i2 < globParts.length; i2++) {
            for (let j = 0; j < globParts[i2].length; j++) {
              if (globParts[i2][j] === "**") {
                globParts[i2][j] = "*";
              }
            }
          }
        }
        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 i2 = gs;
            while (parts[i2 + 1] === "**") {
              i2++;
            }
            if (i2 !== gs) {
              parts.splice(gs, i2 - 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 i2 = 1; i2 < parts.length - 1; i2++) {
              const p = parts[i2];
              if (i2 === 1 && p === "" && parts[0] === "")
                continue;
              if (p === "." || p === "") {
                didSomething = true;
                parts.splice(i2, 1);
                i2--;
              }
            }
            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 p = parts[dd - 1];
            if (p && p !== "." && p !== ".." && p !== "**") {
              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 p = parts[gs + 2];
              const p2 = parts[gs + 3];
              if (next !== "..")
                continue;
              if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
                continue;
              }
              didSomething = true;
              parts.splice(gs, 1);
              const other = parts.slice(0);
              other[gs] = "**";
              globParts.push(other);
              gs--;
            }
            if (!this.preserveMultipleSlashes) {
              for (let i2 = 1; i2 < parts.length - 1; i2++) {
                const p = parts[i2];
                if (i2 === 1 && p === "" && parts[0] === "")
                  continue;
                if (p === "." || p === "") {
                  didSomething = true;
                  parts.splice(i2, 1);
                  i2--;
                }
              }
              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 p = parts[dd - 1];
              if (p && p !== "." && p !== ".." && p !== "**") {
                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 i2 = 0; i2 < globParts.length - 1; i2++) {
          for (let j = i2 + 1; j < globParts.length; j++) {
            const matched = this.partsMatch(globParts[i2], globParts[j], !this.preserveMultipleSlashes);
            if (!matched)
              continue;
            globParts[i2] = matched;
            globParts[j] = [];
          }
        }
        return globParts.filter((gs) => gs.length);
      }
      partsMatch(a, b, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = "";
        while (ai < a.length && bi < b.length) {
          if (a[ai] === b[bi]) {
            result.push(which === "b" ? b[bi] : a[ai]);
            ai++;
            bi++;
          } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
            result.push(a[ai]);
            ai++;
          } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
            result.push(b[bi]);
            bi++;
          } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
            if (which === "b")
              return false;
            which = "a";
            result.push(a[ai]);
            ai++;
            bi++;
          } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
            if (which === "a")
              return false;
            which = "b";
            result.push(b[bi]);
            ai++;
            bi++;
          } else {
            return false;
          }
        }
        return a.length === b.length && result;
      }
      parseNegate() {
        if (this.nonegate)
          return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i2 = 0; i2 < pattern.length && pattern.charAt(i2) === "!"; i2++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset)
          this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, 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 p = pattern[pi];
          var f3 = file[fi];
          this.debug(pattern, p, f3);
          if (p === false) {
            return false;
          }
          if (p === GLOBSTAR) {
            this.debug("GLOBSTAR", [pattern, p, f3]);
            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 p === "string") {
            hit = f3 === p;
            this.debug("string match", p, f3, hit);
          } else {
            hit = p.test(f3);
            this.debug("pattern match", p, f3, 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 m2;
        let fastTest = null;
        if (m2 = pattern.match(starRE)) {
          fastTest = options.dot ? starTestDot : starTest;
        } else if (m2 = pattern.match(starDotExtRE)) {
          fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m2[1]);
        } else if (m2 = pattern.match(qmarksRE)) {
          fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m2);
        } else if (m2 = pattern.match(starDotStarRE)) {
          fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        } else if (m2 = 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 = (p) => p.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 i2 = 0, c; i2 < pattern.length && (c = pattern.charAt(i2)); i2++) {
          this.debug("%s	%s %s %j", pattern, i2, re, c);
          if (escaping) {
            if (c === "/") {
              return false;
            }
            if (reSpecials[c]) {
              re += "\\";
            }
            re += c;
            escaping = false;
            continue;
          }
          switch (c) {
            case "/": {
              return false;
            }
            case "\\":
              clearStateChar();
              escaping = true;
              continue;
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i2, re, c);
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c;
              if (options.noext)
                clearStateChar();
              continue;
            case "(": {
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i2 - 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(i2 + 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(i2 + 1));
              }
              continue;
            }
            case "[":
              clearStateChar();
              const [src, needUflag, consumed, magic] = parseClass(pattern, i2);
              if (consumed) {
                re += src;
                uflag = uflag || needUflag;
                i2 += consumed - 1;
                hasMagic = hasMagic || magic;
              } else {
                re += "\\[";
              }
              continue;
            case "]":
              re += "\\" + c;
              continue;
            default:
              clearStateChar();
              re += regExpEscape(c);
              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, (_2, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t2 = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t2 + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet[re.charAt(0)];
        for (let n = negativeLists.length - 1; n > -1; n--) {
          const nl = negativeLists[n];
          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 i2 = 0; i2 < openParensBefore; i2++) {
            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((p) => typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src);
          pp.forEach((p, i2) => {
            const next = pp[i2 + 1];
            const prev = pp[i2 - 1];
            if (p !== GLOBSTAR || prev === GLOBSTAR) {
              return;
            }
            if (prev === void 0) {
              if (next !== void 0 && next !== GLOBSTAR) {
                pp[i2 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
              } else {
                pp[i2] = twoStar;
              }
            } else if (next === void 0) {
              pp[i2 - 1] = prev + "(?:\\/|" + twoStar + ")?";
            } else if (next !== GLOBSTAR) {
              pp[i2 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
              pp[i2 + 1] = GLOBSTAR;
            }
          });
          return pp.filter((p) => p !== 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(p) {
        if (this.preserveMultipleSlashes) {
          return p.split("/");
        } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
          return ["", ...p.split(/\/+/)];
        } else {
          return p.split(/\/+/);
        }
      }
      match(f3, partial = this.partial) {
        this.debug("match", f3, this.pattern);
        if (this.comment) {
          return false;
        }
        if (this.empty) {
          return f3 === "";
        }
        if (f3 === "/" && partial) {
          return true;
        }
        const options = this.options;
        if (this.isWindows) {
          f3 = f3.split("\\").join("/");
        }
        const ff = this.slashSplit(f3);
        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 i2 = ff.length - 2; !filename && i2 >= 0; i2--) {
            filename = ff[i2];
          }
        }
        for (let i2 = 0; i2 < set.length; i2++) {
          const pattern = set[i2];
          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/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,
        fromDatabase(db, databaseName, filter2)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/cli/commands/singlestoreIntrospect.ts
var singlestoreIntrospect_exports = {};
__export(singlestoreIntrospect_exports, {
  singlestorePushIntrospect: () => singlestorePushIntrospect
});
var import_hanji10, singlestorePushIntrospect;
var init_singlestoreIntrospect = __esm({
  "src/cli/commands/singlestoreIntrospect.ts"() {
    "use strict";
    import_hanji10 = __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_hanji10.renderWithTask)(
        progress,
        fromDatabase4(db, databaseName, filter2)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/cli/commands/pgIntrospect.ts
var pgIntrospect_exports = {};
__export(pgIntrospect_exports, {
  pgPushIntrospect: () => pgPushIntrospect
});
var import_hanji11, pgPushIntrospect;
var init_pgIntrospect = __esm({
  "src/cli/commands/pgIntrospect.ts"() {
    "use strict";
    import_hanji11 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_pgSerializer();
    init_views();
    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_hanji11.renderWithTask)(
        progress,
        fromDatabase2(db, filter2, schemaFilters, entities, void 0, tsSchema)
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema6;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/introspect-sqlite.ts
var import_casing2, sqliteImportsList, indexName4, objToStatement2, relations, escapeColumnKey, withCasing, dbColumnName, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column5, createTableColumns, createTableIndexes, createTableUniques, createTableChecks, createTablePKs, createTableFKs;
var init_introspect_sqlite = __esm({
  "src/introspect-sqlite.ts"() {
    "use strict";
    import_casing2 = require("drizzle-orm/casing");
    init_utils();
    init_global();
    sqliteImportsList = /* @__PURE__ */ new Set([
      "sqliteTable",
      "integer",
      "real",
      "text",
      "numeric",
      "blob"
    ]);
    indexName4 = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    objToStatement2 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
      statement += " }";
      return statement;
    };
    relations = /* @__PURE__ */ new Set();
    escapeColumnKey = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    withCasing = (value, casing2) => {
      if (casing2 === "preserve") {
        return escapeColumnKey(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey(value.camelCase());
      }
      return value;
    };
    dbColumnName = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing2.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    schemaToTypeScript = (schema6, casing2) => {
      Object.values(schema6.tables).forEach((table5) => {
        Object.values(table5.foreignKeys).forEach((fk4) => {
          const relation = `${fk4.tableFrom}-${fk4.tableTo}`;
          relations.add(relation);
        });
      });
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
          const pkImports = Object.values(it.compositePrimaryKeys).map(
            (it2) => "primaryKey"
          );
          const uniqueImports = Object.values(it.uniqueConstraints).map(
            (it2) => "unique"
          );
          const checkImports = Object.values(it.checkConstraints).map(
            (it2) => "check"
          );
          res.sqlite.push(...idxImports);
          res.sqlite.push(...fkImpots);
          res.sqlite.push(...pkImports);
          res.sqlite.push(...uniqueImports);
          res.sqlite.push(...checkImports);
          const columnImports = Object.values(it.columns).map((col) => {
            return col.type;
          }).filter((type) => {
            return sqliteImportsList.has(type);
          });
          res.sqlite.push(...columnImports);
          return res;
        },
        { sqlite: [] }
      );
      Object.values(schema6.views).forEach((it) => {
        imports.sqlite.push("sqliteView");
        const columnImports = Object.values(it.columns).map((col) => {
          return col.type;
        }).filter((type) => {
          return sqliteImportsList.has(type);
        });
        imports.sqlite.push(...columnImports);
      });
      const tableStatements = Object.values(schema6.tables).map((table5) => {
        const func = "sqliteTable";
        let statement = "";
        if (imports.sqlite.includes(withCasing(table5.name, casing2))) {
          statement = `// Table name is in conflict with ${withCasing(
            table5.name,
            casing2
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing(table5.name, casing2)} = ${func}("${table5.name}", {
`;
        statement += createTableColumns(
          Object.values(table5.columns),
          Object.values(table5.foreignKeys),
          casing2
        );
        statement += "}";
        const filteredFKs = Object.values(table5.foreignKeys).filter((it) => {
          return it.columnsFrom.length > 1 || isSelf(it);
        });
        if (Object.keys(table5.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table5.compositePrimaryKeys).length > 0 || Object.keys(table5.uniqueConstraints).length > 0 || Object.keys(table5.checkConstraints).length > 0) {
          statement += ",\n";
          statement += "(table) => [";
          statement += createTableIndexes(
            table5.name,
            Object.values(table5.indexes),
            casing2
          );
          statement += createTableFKs(Object.values(filteredFKs), casing2);
          statement += createTablePKs(
            Object.values(table5.compositePrimaryKeys),
            casing2
          );
          statement += createTableUniques(
            Object.values(table5.uniqueConstraints),
            casing2
          );
          statement += createTableChecks(
            Object.values(table5.checkConstraints),
            casing2
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const viewsStatements = Object.values(schema6.views).map((view4) => {
        var _a;
        const func = "sqliteView";
        let statement = "";
        if (imports.sqlite.includes(withCasing(view4.name, casing2))) {
          statement = `// Table name is in conflict with ${withCasing(
            view4.name,
            casing2
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing(view4.name, casing2)} = ${func}("${view4.name}", {
`;
        statement += createTableColumns(
          Object.values(view4.columns),
          [],
          casing2
        );
        statement += "})";
        statement += `.as(sql\`${(_a = view4.definition) == null ? void 0 : _a.replaceAll("`", "\\`")}\`);`;
        return statement;
      });
      const uniqueSqliteImports = [
        "sqliteTable",
        "AnySQLiteColumn",
        ...new Set(imports.sqlite)
      ];
      const importsTs = `import { ${uniqueSqliteImports.join(
        ", "
      )} } from "drizzle-orm/sqlite-core"
  import { sql } from "drizzle-orm"

`;
      let decalrations = tableStatements.join("\n\n");
      decalrations += "\n\n";
      decalrations += viewsStatements.join("\n\n");
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing(it.name, casing2)).join(",")}
    }
  `;
      return { file, imports: importsTs, decalrations, schemaEntry };
    };
    isCyclic = (fk4) => {
      const key = `${fk4.tableFrom}-${fk4.tableTo}`;
      const reverse = `${fk4.tableTo}-${fk4.tableFrom}`;
      return relations.has(key) && relations.has(reverse);
    };
    isSelf = (fk4) => {
      return fk4.tableFrom === fk4.tableTo;
    };
    mapColumnDefault = (defaultValue) => {
      if (typeof defaultValue === "string" && defaultValue.startsWith("(") && defaultValue.endsWith(")")) {
        return `sql\`${defaultValue}\``;
      }
      if (defaultValue === "NULL") {
        return `sql\`NULL\``;
      }
      if (typeof defaultValue === "string") {
        return defaultValue.substring(1, defaultValue.length - 1).replaceAll('"', '\\"').replaceAll("''", "'");
      }
      return defaultValue;
    };
    column5 = (type, name, defaultValue, autoincrement, casing2) => {
      let lowered = type;
      casing2 = casing2;
      if (lowered === "integer") {
        let out = `${withCasing(name, casing2)}: integer(${dbColumnName({ name, casing: casing2 })})`;
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      if (lowered === "real") {
        let out = `${withCasing(name, casing2)}: real(${dbColumnName({ name, casing: casing2 })})`;
        out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      if (lowered.startsWith("text")) {
        const match2 = lowered.match(/\d+/);
        let out;
        if (match2) {
          out = `${withCasing(name, casing2)}: text(${dbColumnName({ name, casing: casing2, withMode: true })}{ length: ${match2[0]} })`;
        } else {
          out = `${withCasing(name, casing2)}: text(${dbColumnName({ name, casing: casing2 })})`;
        }
        out += defaultValue ? `.default("${mapColumnDefault(defaultValue)}")` : "";
        return out;
      }
      if (lowered === "blob") {
        let out = `${withCasing(name, casing2)}: blob(${dbColumnName({ name, casing: casing2 })})`;
        out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      if (lowered === "numeric") {
        let out = `${withCasing(name, casing2)}: numeric(${dbColumnName({ name, casing: casing2 })})`;
        out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
        return out;
      }
      return `// Warning: Can't parse ${type} from database
	// ${type}Type: ${type}("${name}")`;
    };
    createTableColumns = (columns, fks, casing2) => {
      let statement = "";
      const oneColumnsFKs = Object.values(fks).filter((it) => {
        return !isSelf(it);
      }).filter((it) => it.columnsFrom.length === 1);
      const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
        const arr = res[it.columnsFrom[0]] || [];
        arr.push(it);
        res[it.columnsFrom[0]] = arr;
        return res;
      }, {});
      columns.forEach((it) => {
        statement += "	";
        statement += column5(it.type, it.name, it.default, it.autoincrement, casing2);
        statement += it.primaryKey ? `.primaryKey(${it.autoincrement ? "{ autoIncrement: true }" : ""})` : "";
        statement += it.notNull ? ".notNull()" : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(/`/g, "\\`").slice(1, -1)}\`, { mode: "${it.generated.type}" })` : "";
        const fks2 = fkByColumnName[it.name];
        if (fks2) {
          const fksStatement = fks2.map((it2) => {
            const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
            const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
            const params = { onDelete, onUpdate };
            const typeSuffix = isCyclic(it2) ? ": AnySQLiteColumn" : "";
            const paramsStr = objToStatement2(params);
            if (paramsStr) {
              return `.references(()${typeSuffix} => ${withCasing(
                it2.tableTo,
                casing2
              )}.${withCasing(it2.columnsTo[0], casing2)}, ${paramsStr} )`;
            }
            return `.references(()${typeSuffix} => ${withCasing(
              it2.tableTo,
              casing2
            )}.${withCasing(it2.columnsTo[0], casing2)})`;
          }).join("");
          statement += fksStatement;
        }
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = withCasing(idxKey, casing2);
        const indexGeneratedName = indexName4(tableName, it.columns);
        const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `${escapedIndexName})`;
        statement += `.on(${it.columns.map((it2) => `table.${withCasing(it2, casing2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableUniques = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        const idxKey = withCasing(it.name, casing2);
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${withCasing(it2, casing2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableChecks = (checks, casing2) => {
      let statement = "";
      checks.forEach((it) => {
        statement += `
	`;
        statement += "check(";
        statement += `"${it.name}", `;
        statement += `sql\`${it.value}\`)`;
        statement += `,`;
      });
      return statement;
    };
    createTablePKs = (pks, casing2) => {
      let statement = "";
      pks.forEach((it, i2) => {
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c) => {
          return `table.${withCasing(c, casing2)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += ")";
      });
      return statement;
    };
    createTableFKs = (fks, casing2) => {
      let statement = "";
      fks.forEach((it) => {
        const isSelf4 = it.tableTo === it.tableFrom;
        const tableTo = isSelf4 ? "table" : `${withCasing(it.tableTo, casing2)}`;
        statement += `
	`;
        statement += `foreignKey(() => ({
`;
        statement += `			columns: [${it.columnsFrom.map((i2) => `table.${withCasing(i2, casing2)}`).join(", ")}],
`;
        statement += `			foreignColumns: [${it.columnsTo.map((i2) => `${tableTo}.${withCasing(i2, casing2)}`).join(", ")}],
`;
        statement += `			name: "${it.name}"
`;
        statement += `		}))`;
        statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
        statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
        statement += `,`;
      });
      return statement;
    };
  }
});

// src/cli/commands/sqliteIntrospect.ts
var sqliteIntrospect_exports = {};
__export(sqliteIntrospect_exports, {
  sqliteIntrospect: () => sqliteIntrospect,
  sqlitePushIntrospect: () => sqlitePushIntrospect
});
var import_hanji12, sqliteIntrospect, sqlitePushIntrospect;
var init_sqliteIntrospect = __esm({
  "src/cli/commands/sqliteIntrospect.ts"() {
    "use strict";
    import_hanji12 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_introspect_sqlite();
    init_sqliteSerializer();
    init_views();
    sqliteIntrospect = async (credentials2, filters, casing2) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await connectToSQLite2(credentials2);
      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 IntrospectProgress();
      const res = await (0, import_hanji12.renderWithTask)(
        progress,
        fromDatabase3(db, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript(schema6, casing2);
      return { schema: schema6, ts };
    };
    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_hanji12.renderWithTask)(progress, fromDatabase3(db, filter2));
      const schema6 = { id: originUUID, prevId: "", ...res };
      return { schema: schema6 };
    };
  }
});

// src/cli/commands/push.ts
var push_exports = {};
__export(push_exports, {
  libSQLPush: () => libSQLPush,
  mysqlPush: () => mysqlPush,
  pgPush: () => pgPush,
  singlestorePush: () => singlestorePush,
  sqlitePush: () => sqlitePush
});
var import_crypto6, import_hanji13, mysqlPush, singlestorePush, pgPush, sqlitePush, libSQLPush;
var init_push = __esm({
  "src/cli/commands/push.ts"() {
    "use strict";
    init_source();
    import_crypto6 = require("crypto");
    import_hanji13 = __toESM(require_hanji());
    init_serializer();
    init_sqlgenerator();
    init_selector_ui();
    init_outputs();
    init_libSqlPushUtils();
    init_mysqlPushUtils();
    init_pgPushUtils();
    init_singlestorePushUtils();
    init_sqlitePushUtils();
    mysqlPush = async (schemaPath, credentials2, tablesFilter, strict, verbose, force, casing2) => {
      const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { mysqlPushIntrospect: mysqlPushIntrospect2 } = await Promise.resolve().then(() => (init_mysqlIntrospect(), mysqlIntrospect_exports));
      const { db, database } = await connectToMySQL2(credentials2);
      const { schema: schema6 } = await mysqlPushIntrospect2(db, database, tablesFilter);
      const { prepareMySQLPush: prepareMySQLPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareMySQLPush2(schemaPath, schema6, casing2);
      const filteredStatements = filterStatements(
        statements.statements ?? [],
        statements.validatedCur,
        statements.validatedPrev
      );
      try {
        if (filteredStatements.length === 0) {
          (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
        } else {
          const {
            shouldAskForApprove,
            statementsToExecute,
            columnsToRemove,
            tablesToRemove,
            tablesToTruncate,
            infoToPrint
          } = await logSuggestionsAndReturn2(
            db,
            filteredStatements,
            statements.validatedCur
          );
          const filteredSqlStatements = fromJson(filteredStatements, "mysql");
          const uniqueSqlStatementsToExecute = [];
          statementsToExecute.forEach((ss) => {
            if (!uniqueSqlStatementsToExecute.includes(ss)) {
              uniqueSqlStatementsToExecute.push(ss);
            }
          });
          const uniqueFilteredSqlStatements = [];
          filteredSqlStatements.forEach((ss) => {
            if (!uniqueFilteredSqlStatements.includes(ss)) {
              uniqueFilteredSqlStatements.push(ss);
            }
          });
          if (verbose) {
            console.log();
            console.log(
              withStyle.warning("You are about to execute current statements:")
            );
            console.log();
            console.log(
              [...uniqueSqlStatementsToExecute, ...uniqueFilteredSqlStatements].map((s2) => source_default.blue(s2)).join("\n")
            );
            console.log();
          }
          if (!force && strict) {
            if (!shouldAskForApprove) {
              const { status, data } = await (0, import_hanji13.render)(
                new Select(["No, abort", `Yes, I want to execute all statements`])
              );
              if ((data == null ? void 0 : data.index) === 0) {
                (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
                process.exit(0);
              }
            }
          }
          if (!force && shouldAskForApprove) {
            console.log(withStyle.warning("Found data-loss statements:"));
            console.log(infoToPrint.join("\n"));
            console.log();
            console.log(
              source_default.red.bold(
                "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
              )
            );
            console.log(source_default.white("Do you still want to push changes?"));
            const { status, data } = await (0, import_hanji13.render)(
              new Select([
                "No, abort",
                `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
              ])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
          for (const dStmnt of uniqueSqlStatementsToExecute) {
            await db.query(dStmnt);
          }
          for (const statement of uniqueFilteredSqlStatements) {
            await db.query(statement);
          }
          if (filteredStatements.length > 0) {
            (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
          } else {
            (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
          }
        }
      } catch (e2) {
        console.log(e2);
      }
    };
    singlestorePush = async (schemaPath, credentials2, tablesFilter, strict, verbose, force, casing2) => {
      const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { singlestorePushIntrospect: singlestorePushIntrospect2 } = await Promise.resolve().then(() => (init_singlestoreIntrospect(), singlestoreIntrospect_exports));
      const { db, database } = await connectToSingleStore2(credentials2);
      const { schema: schema6 } = await singlestorePushIntrospect2(
        db,
        database,
        tablesFilter
      );
      const { prepareSingleStorePush: prepareSingleStorePush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareSingleStorePush2(schemaPath, schema6, casing2);
      const filteredStatements = filterStatements2(
        statements.statements ?? [],
        statements.validatedCur,
        statements.validatedPrev
      );
      try {
        if (filteredStatements.length === 0) {
          (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
        } else {
          const {
            shouldAskForApprove,
            statementsToExecute,
            columnsToRemove,
            tablesToRemove,
            tablesToTruncate,
            infoToPrint,
            schemasToRemove
          } = await logSuggestionsAndReturn3(
            db,
            filteredStatements,
            statements.validatedCur,
            statements.validatedPrev
          );
          if (verbose) {
            console.log();
            console.log(
              withStyle.warning("You are about to execute current statements:")
            );
            console.log();
            console.log(statementsToExecute.map((s2) => source_default.blue(s2)).join("\n"));
            console.log();
          }
          if (!force && strict) {
            if (!shouldAskForApprove) {
              const { status, data } = await (0, import_hanji13.render)(
                new Select(["No, abort", `Yes, I want to execute all statements`])
              );
              if ((data == null ? void 0 : data.index) === 0) {
                (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
                process.exit(0);
              }
            }
          }
          if (!force && shouldAskForApprove) {
            console.log(withStyle.warning("Found data-loss statements:"));
            console.log(infoToPrint.join("\n"));
            console.log();
            console.log(
              source_default.red.bold(
                "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
              )
            );
            console.log(source_default.white("Do you still want to push changes?"));
            const { status, data } = await (0, import_hanji13.render)(
              new Select([
                "No, abort",
                `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
              ])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
          for (const dStmnt of statementsToExecute) {
            await db.query(dStmnt);
          }
          if (filteredStatements.length > 0) {
            (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
          } else {
            (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
          }
        }
      } catch (e2) {
        console.log(e2);
      }
    };
    pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, entities, force, casing2) => {
      const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { pgPushIntrospect: pgPushIntrospect2 } = await Promise.resolve().then(() => (init_pgIntrospect(), pgIntrospect_exports));
      const db = await preparePostgresDB2(credentials2);
      const serialized = await serializePg(schemaPath, casing2, schemasFilter);
      const { schema: schema6 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter, entities, serialized);
      const { preparePgPush: preparePgPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await preparePgPush2(
        { id: (0, import_crypto6.randomUUID)(), prevId: schema6.id, ...serialized },
        schema6
      );
      try {
        if (statements.sqlStatements.length === 0) {
          (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
        } else {
          const {
            shouldAskForApprove,
            statementsToExecute,
            columnsToRemove,
            tablesToRemove,
            matViewsToRemove,
            tablesToTruncate,
            infoToPrint,
            schemasToRemove
          } = await pgSuggestions(db, statements.statements);
          if (verbose) {
            console.log();
            console.log(
              withStyle.warning("You are about to execute current statements:")
            );
            console.log();
            console.log(statementsToExecute.map((s2) => source_default.blue(s2)).join("\n"));
            console.log();
          }
          if (!force && strict) {
            if (!shouldAskForApprove) {
              const { status, data } = await (0, import_hanji13.render)(
                new Select(["No, abort", `Yes, I want to execute all statements`])
              );
              if ((data == null ? void 0 : data.index) === 0) {
                (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
                process.exit(0);
              }
            }
          }
          if (!force && shouldAskForApprove) {
            console.log(withStyle.warning("Found data-loss statements:"));
            console.log(infoToPrint.join("\n"));
            console.log();
            console.log(
              source_default.red.bold(
                "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
              )
            );
            console.log(source_default.white("Do you still want to push changes?"));
            const { status, data } = await (0, import_hanji13.render)(
              new Select([
                "No, abort",
                `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}${matViewsToRemove.length > 0 ? ` remove ${matViewsToRemove.length} ${matViewsToRemove.length > 1 ? "materialized views" : "materialize view"},` : " "}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
              ])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
          for (const dStmnt of statementsToExecute) {
            await db.query(dStmnt);
          }
          if (statements.statements.length > 0) {
            (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
          } else {
            (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
          }
        }
      } catch (e2) {
        console.error(e2);
      }
    };
    sqlitePush = async (schemaPath, verbose, strict, credentials2, tablesFilter, force, casing2) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { sqlitePushIntrospect: sqlitePushIntrospect2 } = await Promise.resolve().then(() => (init_sqliteIntrospect(), sqliteIntrospect_exports));
      const db = await connectToSQLite2(credentials2);
      const { schema: schema6 } = await sqlitePushIntrospect2(db, tablesFilter);
      const { prepareSQLitePush: prepareSQLitePush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareSQLitePush2(schemaPath, schema6, casing2);
      if (statements.sqlStatements.length === 0) {
        (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
      } else {
        const {
          shouldAskForApprove,
          statementsToExecute,
          columnsToRemove,
          tablesToRemove,
          tablesToTruncate,
          infoToPrint,
          schemasToRemove
        } = await logSuggestionsAndReturn(
          db,
          statements.statements,
          statements.squashedPrev,
          statements.squashedCur,
          statements.meta
        );
        if (verbose && statementsToExecute.length > 0) {
          console.log();
          console.log(
            withStyle.warning("You are about to execute current statements:")
          );
          console.log();
          console.log(statementsToExecute.map((s2) => source_default.blue(s2)).join("\n"));
          console.log();
        }
        if (!force && strict) {
          if (!shouldAskForApprove) {
            const { status, data } = await (0, import_hanji13.render)(
              new Select(["No, abort", `Yes, I want to execute all statements`])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
        }
        if (!force && shouldAskForApprove) {
          console.log(withStyle.warning("Found data-loss statements:"));
          console.log(infoToPrint.join("\n"));
          console.log();
          console.log(
            source_default.red.bold(
              "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
            )
          );
          console.log(source_default.white("Do you still want to push changes?"));
          const { status, data } = await (0, import_hanji13.render)(
            new Select([
              "No, abort",
              `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.trimEnd().replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
            ])
          );
          if ((data == null ? void 0 : data.index) === 0) {
            (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
            process.exit(0);
          }
        }
        if (statementsToExecute.length === 0) {
          (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
        } else {
          if (!("driver" in credentials2)) {
            await db.run("begin");
            try {
              for (const dStmnt of statementsToExecute) {
                await db.run(dStmnt);
              }
              await db.run("commit");
            } catch (e2) {
              console.error(e2);
              await db.run("rollback");
              process.exit(1);
            }
          }
          (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
        }
      }
    };
    libSQLPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, force, casing2) => {
      const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { sqlitePushIntrospect: sqlitePushIntrospect2 } = await Promise.resolve().then(() => (init_sqliteIntrospect(), sqliteIntrospect_exports));
      const db = await connectToLibSQL2(credentials2);
      const { schema: schema6 } = await sqlitePushIntrospect2(db, tablesFilter);
      const { prepareLibSQLPush: prepareLibSQLPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
      const statements = await prepareLibSQLPush2(schemaPath, schema6, casing2);
      if (statements.sqlStatements.length === 0) {
        (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
      } else {
        const {
          shouldAskForApprove,
          statementsToExecute,
          columnsToRemove,
          tablesToRemove,
          tablesToTruncate,
          infoToPrint
        } = await libSqlLogSuggestionsAndReturn(
          db,
          statements.statements,
          statements.squashedPrev,
          statements.squashedCur,
          statements.meta
        );
        if (verbose && statementsToExecute.length > 0) {
          console.log();
          console.log(
            withStyle.warning("You are about to execute current statements:")
          );
          console.log();
          console.log(statementsToExecute.map((s2) => source_default.blue(s2)).join("\n"));
          console.log();
        }
        if (!force && strict) {
          if (!shouldAskForApprove) {
            const { status, data } = await (0, import_hanji13.render)(
              new Select(["No, abort", `Yes, I want to execute all statements`])
            );
            if ((data == null ? void 0 : data.index) === 0) {
              (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
              process.exit(0);
            }
          }
        }
        if (!force && shouldAskForApprove) {
          console.log(withStyle.warning("Found data-loss statements:"));
          console.log(infoToPrint.join("\n"));
          console.log();
          console.log(
            source_default.red.bold(
              "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
            )
          );
          console.log(source_default.white("Do you still want to push changes?"));
          const { status, data } = await (0, import_hanji13.render)(
            new Select([
              "No, abort",
              `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.trimEnd().replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
            ])
          );
          if ((data == null ? void 0 : data.index) === 0) {
            (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
            process.exit(0);
          }
        }
        if (statementsToExecute.length === 0) {
          (0, import_hanji13.render)(`
[${source_default.blue("i")}] No changes detected`);
        } else {
          await db.batchWithPragma(statementsToExecute);
          (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
        }
      }
    };
  }
});

// ../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js
var require_pluralize = __commonJS({
  "../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js"(exports2, module2) {
    (function(root, pluralize) {
      if (typeof require === "function" && typeof exports2 === "object" && typeof module2 === "object") {
        module2.exports = pluralize();
      } else if (typeof define === "function" && define.amd) {
        define(function() {
          return pluralize();
        });
      } else {
        root.pluralize = pluralize();
      }
    })(exports2, function() {
      var pluralRules = [];
      var singularRules = [];
      var uncountables = {};
      var irregularPlurals = {};
      var irregularSingles = {};
      function sanitizeRule(rule) {
        if (typeof rule === "string") {
          return new RegExp("^" + rule + "$", "i");
        }
        return rule;
      }
      function restoreCase(word, token) {
        if (word === token)
          return token;
        if (word === word.toLowerCase())
          return token.toLowerCase();
        if (word === word.toUpperCase())
          return token.toUpperCase();
        if (word[0] === word[0].toUpperCase()) {
          return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
        }
        return token.toLowerCase();
      }
      function interpolate(str, args) {
        return str.replace(/\$(\d{1,2})/g, function(match2, index5) {
          return args[index5] || "";
        });
      }
      function replace(word, rule) {
        return word.replace(rule[0], function(match2, index5) {
          var result = interpolate(rule[1], arguments);
          if (match2 === "") {
            return restoreCase(word[index5 - 1], result);
          }
          return restoreCase(match2, result);
        });
      }
      function sanitizeWord(token, word, rules) {
        if (!token.length || uncountables.hasOwnProperty(token)) {
          return word;
        }
        var len = rules.length;
        while (len--) {
          var rule = rules[len];
          if (rule[0].test(word))
            return replace(word, rule);
        }
        return word;
      }
      function replaceWord(replaceMap, keepMap, rules) {
        return function(word) {
          var token = word.toLowerCase();
          if (keepMap.hasOwnProperty(token)) {
            return restoreCase(word, token);
          }
          if (replaceMap.hasOwnProperty(token)) {
            return restoreCase(word, replaceMap[token]);
          }
          return sanitizeWord(token, word, rules);
        };
      }
      function checkWord(replaceMap, keepMap, rules, bool) {
        return function(word) {
          var token = word.toLowerCase();
          if (keepMap.hasOwnProperty(token))
            return true;
          if (replaceMap.hasOwnProperty(token))
            return false;
          return sanitizeWord(token, token, rules) === token;
        };
      }
      function pluralize(word, count, inclusive) {
        var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word);
        return (inclusive ? count + " " : "") + pluralized;
      }
      pluralize.plural = replaceWord(
        irregularSingles,
        irregularPlurals,
        pluralRules
      );
      pluralize.isPlural = checkWord(
        irregularSingles,
        irregularPlurals,
        pluralRules
      );
      pluralize.singular = replaceWord(
        irregularPlurals,
        irregularSingles,
        singularRules
      );
      pluralize.isSingular = checkWord(
        irregularPlurals,
        irregularSingles,
        singularRules
      );
      pluralize.addPluralRule = function(rule, replacement) {
        pluralRules.push([sanitizeRule(rule), replacement]);
      };
      pluralize.addSingularRule = function(rule, replacement) {
        singularRules.push([sanitizeRule(rule), replacement]);
      };
      pluralize.addUncountableRule = function(word) {
        if (typeof word === "string") {
          uncountables[word.toLowerCase()] = true;
          return;
        }
        pluralize.addPluralRule(word, "$0");
        pluralize.addSingularRule(word, "$0");
      };
      pluralize.addIrregularRule = function(single, plural2) {
        plural2 = plural2.toLowerCase();
        single = single.toLowerCase();
        irregularSingles[single] = plural2;
        irregularPlurals[plural2] = single;
      };
      [
        // Pronouns.
        ["I", "we"],
        ["me", "us"],
        ["he", "they"],
        ["she", "they"],
        ["them", "them"],
        ["myself", "ourselves"],
        ["yourself", "yourselves"],
        ["itself", "themselves"],
        ["herself", "themselves"],
        ["himself", "themselves"],
        ["themself", "themselves"],
        ["is", "are"],
        ["was", "were"],
        ["has", "have"],
        ["this", "these"],
        ["that", "those"],
        // Words ending in with a consonant and `o`.
        ["echo", "echoes"],
        ["dingo", "dingoes"],
        ["volcano", "volcanoes"],
        ["tornado", "tornadoes"],
        ["torpedo", "torpedoes"],
        // Ends with `us`.
        ["genus", "genera"],
        ["viscus", "viscera"],
        // Ends with `ma`.
        ["stigma", "stigmata"],
        ["stoma", "stomata"],
        ["dogma", "dogmata"],
        ["lemma", "lemmata"],
        ["schema", "schemata"],
        ["anathema", "anathemata"],
        // Other irregular rules.
        ["ox", "oxen"],
        ["axe", "axes"],
        ["die", "dice"],
        ["yes", "yeses"],
        ["foot", "feet"],
        ["eave", "eaves"],
        ["goose", "geese"],
        ["tooth", "teeth"],
        ["quiz", "quizzes"],
        ["human", "humans"],
        ["proof", "proofs"],
        ["carve", "carves"],
        ["valve", "valves"],
        ["looey", "looies"],
        ["thief", "thieves"],
        ["groove", "grooves"],
        ["pickaxe", "pickaxes"],
        ["passerby", "passersby"]
      ].forEach(function(rule) {
        return pluralize.addIrregularRule(rule[0], rule[1]);
      });
      [
        [/s?$/i, "s"],
        [/[^\u0000-\u007F]$/i, "$0"],
        [/([^aeiou]ese)$/i, "$1"],
        [/(ax|test)is$/i, "$1es"],
        [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, "$1es"],
        [/(e[mn]u)s?$/i, "$1s"],
        [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, "$1"],
        [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1i"],
        [/(alumn|alg|vertebr)(?:a|ae)$/i, "$1ae"],
        [/(seraph|cherub)(?:im)?$/i, "$1im"],
        [/(her|at|gr)o$/i, "$1oes"],
        [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, "$1a"],
        [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, "$1a"],
        [/sis$/i, "ses"],
        [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, "$1$2ves"],
        [/([^aeiouy]|qu)y$/i, "$1ies"],
        [/([^ch][ieo][ln])ey$/i, "$1ies"],
        [/(x|ch|ss|sh|zz)$/i, "$1es"],
        [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, "$1ices"],
        [/\b((?:tit)?m|l)(?:ice|ouse)$/i, "$1ice"],
        [/(pe)(?:rson|ople)$/i, "$1ople"],
        [/(child)(?:ren)?$/i, "$1ren"],
        [/eaux$/i, "$0"],
        [/m[ae]n$/i, "men"],
        ["thou", "you"]
      ].forEach(function(rule) {
        return pluralize.addPluralRule(rule[0], rule[1]);
      });
      [
        [/s$/i, ""],
        [/(ss)$/i, "$1"],
        [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, "$1fe"],
        [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, "$1f"],
        [/ies$/i, "y"],
        [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, "$1ie"],
        [/\b(mon|smil)ies$/i, "$1ey"],
        [/\b((?:tit)?m|l)ice$/i, "$1ouse"],
        [/(seraph|cherub)im$/i, "$1"],
        [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, "$1"],
        [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, "$1sis"],
        [/(movie|twelve|abuse|e[mn]u)s$/i, "$1"],
        [/(test)(?:is|es)$/i, "$1is"],
        [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1us"],
        [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, "$1um"],
        [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, "$1on"],
        [/(alumn|alg|vertebr)ae$/i, "$1a"],
        [/(cod|mur|sil|vert|ind)ices$/i, "$1ex"],
        [/(matr|append)ices$/i, "$1ix"],
        [/(pe)(rson|ople)$/i, "$1rson"],
        [/(child)ren$/i, "$1"],
        [/(eau)x?$/i, "$1"],
        [/men$/i, "man"]
      ].forEach(function(rule) {
        return pluralize.addSingularRule(rule[0], rule[1]);
      });
      [
        // Singular words with no plurals.
        "adulthood",
        "advice",
        "agenda",
        "aid",
        "aircraft",
        "alcohol",
        "ammo",
        "analytics",
        "anime",
        "athletics",
        "audio",
        "bison",
        "blood",
        "bream",
        "buffalo",
        "butter",
        "carp",
        "cash",
        "chassis",
        "chess",
        "clothing",
        "cod",
        "commerce",
        "cooperation",
        "corps",
        "debris",
        "diabetes",
        "digestion",
        "elk",
        "energy",
        "equipment",
        "excretion",
        "expertise",
        "firmware",
        "flounder",
        "fun",
        "gallows",
        "garbage",
        "graffiti",
        "hardware",
        "headquarters",
        "health",
        "herpes",
        "highjinks",
        "homework",
        "housework",
        "information",
        "jeans",
        "justice",
        "kudos",
        "labour",
        "literature",
        "machinery",
        "mackerel",
        "mail",
        "media",
        "mews",
        "moose",
        "music",
        "mud",
        "manga",
        "news",
        "only",
        "personnel",
        "pike",
        "plankton",
        "pliers",
        "police",
        "pollution",
        "premises",
        "rain",
        "research",
        "rice",
        "salmon",
        "scissors",
        "series",
        "sewage",
        "shambles",
        "shrimp",
        "software",
        "species",
        "staff",
        "swine",
        "tennis",
        "traffic",
        "transportation",
        "trout",
        "tuna",
        "wealth",
        "welfare",
        "whiting",
        "wildebeest",
        "wildlife",
        "you",
        /pok[eé]mon$/i,
        // Regexes.
        /[^aeiou]ese$/i,
        // "chinese", "japanese"
        /deer$/i,
        // "deer", "reindeer"
        /fish$/i,
        // "fish", "blowfish", "angelfish"
        /measles$/i,
        /o[iu]s$/i,
        // "carnivorous"
        /pox$/i,
        // "chickpox", "smallpox"
        /sheep$/i
      ].forEach(pluralize.addUncountableRule);
      return pluralize;
    });
  }
});

// src/introspect-mysql.ts
var import_casing3, mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations2, escapeColumnKey2, prepareCasing, dbColumnName2, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault2, mapColumnDefaultForJson, column6, createTableColumns2, createTableIndexes2, createTableUniques2, createTableChecks2, createTablePKs2, createTableFKs2;
var init_introspect_mysql = __esm({
  "src/introspect-mysql.ts"() {
    "use strict";
    import_casing3 = require("drizzle-orm/casing");
    init_utils();
    init_global();
    init_utils2();
    mysqlImportsList = /* @__PURE__ */ new Set([
      "mysqlTable",
      "mysqlEnum",
      "bigint",
      "binary",
      "boolean",
      "char",
      "date",
      "datetime",
      "decimal",
      "double",
      "float",
      "int",
      "json",
      "mediumint",
      "real",
      "serial",
      "smallint",
      "text",
      "tinytext",
      "mediumtext",
      "longtext",
      "time",
      "timestamp",
      "tinyint",
      "varbinary",
      "varchar",
      "year",
      "enum"
    ]);
    objToStatement22 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
      statement += " }";
      return statement;
    };
    timeConfig = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    binaryConfig = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    importsPatch = {
      "double precision": "doublePrecision",
      "timestamp without time zone": "timestamp"
    };
    relations2 = /* @__PURE__ */ new Set();
    escapeColumnKey2 = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    prepareCasing = (casing2) => (value) => {
      if (casing2 === "preserve") {
        return escapeColumnKey2(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey2(value.camelCase());
      }
      assertUnreachable(casing2);
    };
    dbColumnName2 = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing3.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    schemaToTypeScript2 = (schema6, casing2) => {
      const withCasing4 = prepareCasing(casing2);
      Object.values(schema6.tables).forEach((table5) => {
        Object.values(table5.foreignKeys).forEach((fk4) => {
          const relation = `${fk4.tableFrom}-${fk4.tableTo}`;
          relations2.add(relation);
        });
      });
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
          const pkImports = Object.values(it.compositePrimaryKeys).map(
            (it2) => "primaryKey"
          );
          const uniqueImports = Object.values(it.uniqueConstraints).map(
            (it2) => "unique"
          );
          const checkImports = Object.values(it.checkConstraint).map(
            (it2) => "check"
          );
          res.mysql.push(...idxImports);
          res.mysql.push(...fkImpots);
          res.mysql.push(...pkImports);
          res.mysql.push(...uniqueImports);
          res.mysql.push(...checkImports);
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = importsPatch[col.type] ?? col.type;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("binary(") ? "binary" : patched;
            patched = patched.startsWith("decimal(") ? "decimal" : patched;
            patched = patched.startsWith("smallint(") ? "smallint" : patched;
            patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
            patched = patched.startsWith("datetime(") ? "datetime" : patched;
            patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
            patched = patched.startsWith("int(") ? "int" : patched;
            patched = patched.startsWith("double(") ? "double" : patched;
            patched = patched.startsWith("float(") ? "float" : patched;
            patched = patched.startsWith("int unsigned") ? "int" : patched;
            patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
            patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
            patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
            patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
            return patched;
          }).filter((type) => {
            return mysqlImportsList.has(type);
          });
          res.mysql.push(...columnImports);
          return res;
        },
        { mysql: [] }
      );
      Object.values(schema6.views).forEach((it) => {
        imports.mysql.push("mysqlView");
        const columnImports = Object.values(it.columns).map((col) => {
          let patched = importsPatch[col.type] ?? col.type;
          patched = patched.startsWith("varchar(") ? "varchar" : patched;
          patched = patched.startsWith("char(") ? "char" : patched;
          patched = patched.startsWith("binary(") ? "binary" : patched;
          patched = patched.startsWith("decimal(") ? "decimal" : patched;
          patched = patched.startsWith("smallint(") ? "smallint" : patched;
          patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
          patched = patched.startsWith("datetime(") ? "datetime" : patched;
          patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
          patched = patched.startsWith("int(") ? "int" : patched;
          patched = patched.startsWith("double(") ? "double" : patched;
          patched = patched.startsWith("float(") ? "float" : patched;
          patched = patched.startsWith("int unsigned") ? "int" : patched;
          patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
          patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
          patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
          patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
          return patched;
        }).filter((type) => {
          return mysqlImportsList.has(type);
        });
        imports.mysql.push(...columnImports);
      });
      const tableStatements = Object.values(schema6.tables).map((table5) => {
        const func = "mysqlTable";
        let statement = "";
        if (imports.mysql.includes(withCasing4(table5.name))) {
          statement = `// Table name is in conflict with ${withCasing4(
            table5.name
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing4(table5.name)} = ${func}("${table5.name}", {
`;
        statement += createTableColumns2(
          Object.values(table5.columns),
          Object.values(table5.foreignKeys),
          withCasing4,
          casing2,
          table5.name,
          schema6
        );
        statement += "}";
        const filteredFKs = Object.values(table5.foreignKeys).filter((it) => {
          return it.columnsFrom.length > 1 || isSelf2(it);
        });
        if (Object.keys(table5.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table5.compositePrimaryKeys).length > 0 || Object.keys(table5.uniqueConstraints).length > 0 || Object.keys(table5.checkConstraint).length > 0) {
          statement += ",\n";
          statement += "(table) => [";
          statement += createTableIndexes2(
            table5.name,
            Object.values(table5.indexes),
            withCasing4
          );
          statement += createTableFKs2(Object.values(filteredFKs), withCasing4);
          statement += createTablePKs2(
            Object.values(table5.compositePrimaryKeys),
            withCasing4
          );
          statement += createTableUniques2(
            Object.values(table5.uniqueConstraints),
            withCasing4
          );
          statement += createTableChecks2(
            Object.values(table5.checkConstraint),
            withCasing4
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const viewsStatements = Object.values(schema6.views).map((view4) => {
        const { columns, name, algorithm, definition, sqlSecurity, withCheckOption } = view4;
        const func = "mysqlView";
        let statement = "";
        if (imports.mysql.includes(withCasing4(name))) {
          statement = `// Table name is in conflict with ${withCasing4(
            view4.name
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing4(name)} = ${func}("${name}", {
`;
        statement += createTableColumns2(
          Object.values(columns),
          [],
          withCasing4,
          casing2,
          name,
          schema6
        );
        statement += "})";
        statement += algorithm ? `.algorithm("${algorithm}")` : "";
        statement += sqlSecurity ? `.sqlSecurity("${sqlSecurity}")` : "";
        statement += withCheckOption ? `.withCheckOption("${withCheckOption}")` : "";
        statement += `.as(sql\`${definition == null ? void 0 : definition.replaceAll("`", "\\`")}\`);`;
        return statement;
      });
      const uniqueMySqlImports = [
        "mysqlTable",
        "mysqlSchema",
        "AnyMySqlColumn",
        ...new Set(imports.mysql)
      ];
      const importsTs = `import { ${uniqueMySqlImports.join(
        ", "
      )} } from "drizzle-orm/mysql-core"
import { sql } from "drizzle-orm"

`;
      let decalrations = "";
      decalrations += tableStatements.join("\n\n");
      decalrations += "\n";
      decalrations += viewsStatements.join("\n\n");
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing4(it.name)).join(",")}
    }
  `;
      return {
        file,
        // backward compatible, print to file
        imports: importsTs,
        decalrations,
        schemaEntry
      };
    };
    isCyclic2 = (fk4) => {
      const key = `${fk4.tableFrom}-${fk4.tableTo}`;
      const reverse = `${fk4.tableTo}-${fk4.tableFrom}`;
      return relations2.has(key) && relations2.has(reverse);
    };
    isSelf2 = (fk4) => {
      return fk4.tableFrom === fk4.tableTo;
    };
    mapColumnDefault2 = (defaultValue, isExpression) => {
      if (isExpression) {
        return `sql\`${defaultValue}\``;
      }
      return defaultValue;
    };
    mapColumnDefaultForJson = (defaultValue) => {
      if (typeof defaultValue === "string" && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
        return defaultValue.substring(2, defaultValue.length - 2);
      }
      return defaultValue;
    };
    column6 = (type, name, casing2, rawCasing, defaultValue, autoincrement, onUpdate, isExpression) => {
      let lowered = type;
      if (!type.startsWith("enum(")) {
        lowered = type.toLowerCase();
      }
      if (lowered === "serial") {
        return `${casing2(name)}: serial(${dbColumnName2({ name, casing: rawCasing })})`;
      }
      if (lowered.startsWith("int")) {
        const isUnsigned = lowered.startsWith("int unsigned");
        const columnName = dbColumnName2({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: int(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("tinyint")) {
        const isUnsigned = lowered.startsWith("tinyint unsigned");
        const columnName = dbColumnName2({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: tinyint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("smallint")) {
        const isUnsigned = lowered.startsWith("smallint unsigned");
        const columnName = dbColumnName2({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: smallint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("mediumint")) {
        const isUnsigned = lowered.startsWith("mediumint unsigned");
        const columnName = dbColumnName2({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: mediumint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("bigint")) {
        const isUnsigned = lowered.startsWith("bigint unsigned");
        let out = `${casing2(name)}: bigint(${dbColumnName2({ name, casing: rawCasing, withMode: true })}{ mode: "number"${isUnsigned ? ", unsigned: true" : ""} })`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "boolean") {
        let out = `${casing2(name)}: boolean(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("double")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 15 : 6)) {
          const [precision, scale] = lowered.slice(7, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig(params) : void 0;
        let out = params ? `${casing2(name)}: double(${dbColumnName2({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfig(params)})` : `${casing2(name)}: double(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("float")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 14 : 5)) {
          const [precision, scale] = lowered.slice(6, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        let out = `${casing2(name)}: float(${dbColumnName2({ name, casing: rawCasing })}${params ? timeConfig(params) : ""})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "real") {
        let out = `${casing2(name)}: real(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("timestamp")) {
        const keyLength = "timestamp".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig({ fsp, mode: "'string'" });
        let out = params ? `${casing2(name)}: timestamp(${dbColumnName2({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: timestamp(${dbColumnName2({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" || defaultValue === "(CURRENT_TIMESTAMP)" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        out += defaultValue;
        let onUpdateNow = onUpdate ? ".onUpdateNow()" : "";
        out += onUpdateNow;
        return out;
      }
      if (lowered.startsWith("time")) {
        const keyLength = "time".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig({ fsp });
        let out = params ? `${casing2(name)}: time(${dbColumnName2({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: time(${dbColumnName2({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "date") {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	${casing2(
          name
        )}: date(${dbColumnName2({ name, casing: rawCasing, withMode: true })}{ mode: 'string' })`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "text") {
        let out = `${casing2(name)}: text(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "tinytext") {
        let out = `${casing2(name)}: tinytext(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "mediumtext") {
        let out = `${casing2(name)}: mediumtext(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "longtext") {
        let out = `${casing2(name)}: longtext(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "year") {
        let out = `${casing2(name)}: year(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "json") {
        let out = `${casing2(name)}: json(${dbColumnName2({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefaultForJson(defaultValue)})` : "";
        return out;
      }
      if (lowered.startsWith("varchar")) {
        let out = `${casing2(
          name
        )}: varchar(${dbColumnName2({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "varchar".length + 1,
          lowered.length - 1
        )} })`;
        const mappedDefaultValue = mapColumnDefault2(defaultValue, isExpression);
        out += defaultValue ? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})` : "";
        return out;
      }
      if (lowered.startsWith("char")) {
        let out = `${casing2(
          name
        )}: char(${dbColumnName2({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "char".length + 1,
          lowered.length - 1
        )} })`;
        out += defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("datetime")) {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	`;
        const fsp = lowered.startsWith("datetime(") ? lowered.substring("datetime".length + 1, lowered.length - 1) : void 0;
        out = fsp ? `${casing2(
          name
        )}: datetime(${dbColumnName2({ name, casing: rawCasing, withMode: true })}{ mode: 'string', fsp: ${lowered.substring(
          "datetime".length + 1,
          lowered.length - 1
        )} })` : `${casing2(name)}: datetime(${dbColumnName2({ name, casing: rawCasing, withMode: true })}{ mode: 'string'})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("decimal")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 16 : 7)) {
          const [precision, scale] = lowered.slice(8, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig(params) : void 0;
        let out = params ? `${casing2(name)}: decimal(${dbColumnName2({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfigParams})` : `${casing2(name)}: decimal(${dbColumnName2({ name, casing: rawCasing })})`;
        defaultValue = typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("binary")) {
        const keyLength = "binary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig({ length });
        let out = params ? `${casing2(name)}: binary(${dbColumnName2({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: binary(${dbColumnName2({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("enum")) {
        const values = lowered.substring("enum".length + 1, lowered.length - 1).split(",").map((v) => unescapeSingleQuotes(v, true)).join(",");
        let out = `${casing2(name)}: mysqlEnum(${dbColumnName2({ name, casing: rawCasing, withMode: true })}[${values}])`;
        const mappedDefaultValue = mapColumnDefault2(defaultValue, isExpression);
        out += defaultValue ? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})` : "";
        return out;
      }
      if (lowered.startsWith("varbinary")) {
        const keyLength = "varbinary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig({ length });
        let out = params ? `${casing2(name)}: varbinary(${dbColumnName2({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: varbinary(${dbColumnName2({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      console.log("uknown", type);
      return `// Warning: Can't parse ${type} from database
	// ${type}Type: ${type}("${name}")`;
    };
    createTableColumns2 = (columns, fks, casing2, rawCasing, tableName, schema6) => {
      let statement = "";
      const oneColumnsFKs = Object.values(fks).filter((it) => {
        return !isSelf2(it);
      }).filter((it) => it.columnsFrom.length === 1);
      const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
        const arr = res[it.columnsFrom[0]] || [];
        arr.push(it);
        res[it.columnsFrom[0]] = arr;
        return res;
      }, {});
      columns.forEach((it) => {
        var _a, _b, _c;
        statement += "	";
        statement += column6(
          it.type,
          it.name,
          casing2,
          rawCasing,
          it.default,
          it.autoincrement,
          it.onUpdate,
          ((_c = (_b = (_a = schema6.internal) == null ? void 0 : _a.tables[tableName]) == null ? void 0 : _b.columns[it.name]) == null ? void 0 : _c.isDefaultAnExpression) ?? false
        );
        statement += it.primaryKey ? ".primaryKey()" : "";
        statement += it.notNull ? ".notNull()" : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(
          /`/g,
          "\\`"
        )}\`, { mode: "${it.generated.type}" })` : "";
        const fks2 = fkByColumnName[it.name];
        if (fks2) {
          const fksStatement = fks2.map((it2) => {
            const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
            const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
            const params = { onDelete, onUpdate };
            const typeSuffix = isCyclic2(it2) ? ": AnyMySqlColumn" : "";
            const paramsStr = objToStatement22(params);
            if (paramsStr) {
              return `.references(()${typeSuffix} => ${casing2(
                it2.tableTo
              )}.${casing2(it2.columnsTo[0])}, ${paramsStr} )`;
            }
            return `.references(()${typeSuffix} => ${casing2(it2.tableTo)}.${casing2(
              it2.columnsTo[0]
            )})`;
          }).join("");
          statement += fksStatement;
        }
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes2 = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = casing2(idxKey);
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableUniques2 = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        const idxKey = casing2(it.name);
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableChecks2 = (checks, casing2) => {
      let statement = "";
      checks.forEach((it) => {
        statement += `
	`;
        statement += "check(";
        statement += `"${it.name}", `;
        statement += `sql\`${it.value.replace(/`/g, "\\`")}\`)`;
        statement += `,`;
      });
      return statement;
    };
    createTablePKs2 = (pks, casing2) => {
      let statement = "";
      pks.forEach((it) => {
        let idxKey = casing2(it.name);
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c) => {
          return `table.${casing2(c)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += "),";
      });
      return statement;
    };
    createTableFKs2 = (fks, casing2) => {
      let statement = "";
      fks.forEach((it) => {
        const isSelf4 = it.tableTo === it.tableFrom;
        const tableTo = isSelf4 ? "table" : `${casing2(it.tableTo)}`;
        statement += `
	`;
        statement += `foreignKey({
`;
        statement += `			columns: [${it.columnsFrom.map((i2) => `table.${casing2(i2)}`).join(", ")}],
`;
        statement += `			foreignColumns: [${it.columnsTo.map((i2) => `${tableTo}.${casing2(i2)}`).join(", ")}],
`;
        statement += `			name: "${it.name}"
`;
        statement += `		})`;
        statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
        statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
        statement += `,`;
      });
      return statement;
    };
  }
});

// src/introspect-pg.ts
function generateIdentityParams(identity) {
  let paramsObj = `{ name: "${identity.name}"`;
  if (identity == null ? void 0 : identity.startWith) {
    paramsObj += `, startWith: ${identity.startWith}`;
  }
  if (identity == null ? void 0 : identity.increment) {
    paramsObj += `, increment: ${identity.increment}`;
  }
  if (identity == null ? void 0 : identity.minValue) {
    paramsObj += `, minValue: ${identity.minValue}`;
  }
  if (identity == null ? void 0 : identity.maxValue) {
    paramsObj += `, maxValue: ${identity.maxValue}`;
  }
  if (identity == null ? void 0 : identity.cache) {
    paramsObj += `, cache: ${identity.cache}`;
  }
  if (identity == null ? void 0 : identity.cycle) {
    paramsObj += `, cycle: true`;
  }
  paramsObj += " }";
  if ((identity == null ? void 0 : identity.type) === "always") {
    return `.generatedAlwaysAsIdentity(${paramsObj})`;
  }
  return `.generatedByDefaultAsIdentity(${paramsObj})`;
}
var import_drizzle_orm9, import_relations, import_casing4, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, dbColumnName3, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column7, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTablePolicies, createTableUniques3, createTableChecks3, createTableFKs3;
var init_introspect_pg = __esm({
  "src/introspect-pg.ts"() {
    "use strict";
    import_drizzle_orm9 = require("drizzle-orm");
    import_relations = require("drizzle-orm/relations");
    init_utils();
    import_casing4 = require("drizzle-orm/casing");
    init_global();
    init_pgSerializer();
    init_utils2();
    pgImportsList = /* @__PURE__ */ new Set([
      "pgTable",
      "pgEnum",
      "smallint",
      "integer",
      "bigint",
      "boolean",
      "text",
      "varchar",
      "char",
      "serial",
      "smallserial",
      "bigserial",
      "decimal",
      "numeric",
      "real",
      "json",
      "jsonb",
      "time",
      "timestamp",
      "date",
      "interval",
      "cidr",
      "inet",
      "macaddr",
      "macaddr8",
      "bigint",
      "doublePrecision",
      "uuid",
      "vector",
      "point",
      "line",
      "geometry"
    ]);
    timeConfig2 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    possibleIntervals = [
      "year",
      "month",
      "day",
      "hour",
      "minute",
      "second",
      "year to month",
      "day to hour",
      "day to minute",
      "day to second",
      "hour to minute",
      "hour to second",
      "minute to second"
    ];
    intervalStrToObj = (str) => {
      if (str.startsWith("interval(")) {
        return {
          precision: Number(str.substring("interval(".length, str.length - 1))
        };
      }
      const splitted = str.split(" ");
      if (splitted.length === 1) {
        return {};
      }
      const rest = splitted.slice(1, splitted.length).join(" ");
      if (possibleIntervals.includes(rest)) {
        return { fields: `"${rest}"` };
      }
      for (const s2 of possibleIntervals) {
        if (rest.startsWith(`${s2}(`)) {
          return {
            fields: `"${s2}"`,
            precision: Number(rest.substring(s2.length + 1, rest.length - 1))
          };
        }
      }
      return {};
    };
    intervalConfig = (str) => {
      const json = intervalStrToObj(str);
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    mapColumnDefault3 = (defaultValue, isExpression) => {
      if (isExpression) {
        return `sql\`${defaultValue}\``;
      }
      return defaultValue;
    };
    importsPatch2 = {
      "double precision": "doublePrecision",
      "timestamp without time zone": "timestamp",
      "timestamp with time zone": "timestamp",
      "time without time zone": "time",
      "time with time zone": "time"
    };
    relations3 = /* @__PURE__ */ new Set();
    escapeColumnKey3 = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    withCasing2 = (value, casing2) => {
      if (casing2 === "preserve") {
        return escapeColumnKey3(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey3(value.camelCase());
      }
      assertUnreachable(casing2);
    };
    dbColumnName3 = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing4.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    paramNameFor = (name, schema6) => {
      const schemaSuffix = schema6 && schema6 !== "public" ? `In${schema6.capitalise()}` : "";
      return `${name}${schemaSuffix}`;
    };
    schemaToTypeScript3 = (schema6, casing2) => {
      Object.values(schema6.tables).forEach((table5) => {
        Object.values(table5.foreignKeys).forEach((fk4) => {
          const relation = `${fk4.tableFrom}-${fk4.tableTo}`;
          relations3.add(relation);
        });
      });
      const schemas = Object.fromEntries(
        Object.entries(schema6.schemas).map((it) => {
          return [it[0], withCasing2(it[1], casing2)];
        })
      );
      const enumTypes = Object.values(schema6.enums).reduce((acc, cur) => {
        acc.add(`${cur.schema}.${cur.name}`);
        return acc;
      }, /* @__PURE__ */ new Set());
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
          if (Object.values(it.foreignKeys).some((it2) => isCyclic3(it2) && !isSelf3(it2))) {
            res.pg.push("type AnyPgColumn");
          }
          const pkImports = Object.values(it.compositePrimaryKeys).map((it2) => "primaryKey");
          const uniqueImports = Object.values(it.uniqueConstraints).map((it2) => "unique");
          const checkImports = Object.values(it.checkConstraints).map(
            (it2) => "check"
          );
          const policiesImports = Object.values(it.policies).map(
            (it2) => "pgPolicy"
          );
          if (it.schema && it.schema !== "public" && it.schema !== "") {
            res.pg.push("pgSchema");
          }
          res.pg.push(...idxImports);
          res.pg.push(...fkImpots);
          res.pg.push(...pkImports);
          res.pg.push(...uniqueImports);
          res.pg.push(...policiesImports);
          res.pg.push(...checkImports);
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
            patched = patched === "double precision" ? "doublePrecision" : patched;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("numeric(") ? "numeric" : patched;
            patched = patched.startsWith("time(") ? "time" : patched;
            patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
            patched = patched.startsWith("vector(") ? "vector" : patched;
            patched = patched.startsWith("geometry(") ? "geometry" : patched;
            return patched;
          }).filter((type) => {
            return pgImportsList.has(type);
          });
          res.pg.push(...columnImports);
          return res;
        },
        { pg: [] }
      );
      Object.values(schema6.views).forEach((it) => {
        if (it.schema && it.schema !== "public" && it.schema !== "") {
          imports.pg.push("pgSchema");
        } else if (it.schema === "public") {
          it.materialized ? imports.pg.push("pgMaterializedView") : imports.pg.push("pgView");
        }
        Object.values(it.columns).forEach(() => {
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
            patched = patched === "double precision" ? "doublePrecision" : patched;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("numeric(") ? "numeric" : patched;
            patched = patched.startsWith("time(") ? "time" : patched;
            patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
            patched = patched.startsWith("vector(") ? "vector" : patched;
            patched = patched.startsWith("geometry(") ? "geometry" : patched;
            return patched;
          }).filter((type) => {
            return pgImportsList.has(type);
          });
          imports.pg.push(...columnImports);
        });
      });
      Object.values(schema6.sequences).forEach((it) => {
        if (it.schema && it.schema !== "public" && it.schema !== "") {
          imports.pg.push("pgSchema");
        } else if (it.schema === "public") {
          imports.pg.push("pgSequence");
        }
      });
      Object.values(schema6.enums).forEach((it) => {
        if (it.schema && it.schema !== "public" && it.schema !== "") {
          imports.pg.push("pgSchema");
        } else if (it.schema === "public") {
          imports.pg.push("pgEnum");
        }
      });
      if (Object.keys(schema6.roles).length > 0) {
        imports.pg.push("pgRole");
      }
      const enumStatements = Object.values(schema6.enums).map((it) => {
        const enumSchema3 = schemas[it.schema];
        const paramName = paramNameFor(it.name, enumSchema3);
        const func = enumSchema3 ? `${enumSchema3}.enum` : "pgEnum";
        const values = Object.values(it.values).map((it2) => `'${unescapeSingleQuotes(it2, false)}'`).join(", ");
        return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}", [${values}])
`;
      }).join("").concat("\n");
      const sequencesStatements = Object.values(schema6.sequences).map((it) => {
        const seqSchema = schemas[it.schema];
        const paramName = paramNameFor(it.name, seqSchema);
        const func = seqSchema ? `${seqSchema}.sequence` : "pgSequence";
        let params = "";
        if (it.startWith) {
          params += `, startWith: "${it.startWith}"`;
        }
        if (it.increment) {
          params += `, increment: "${it.increment}"`;
        }
        if (it.minValue) {
          params += `, minValue: "${it.minValue}"`;
        }
        if (it.maxValue) {
          params += `, maxValue: "${it.maxValue}"`;
        }
        if (it.cache) {
          params += `, cache: "${it.cache}"`;
        }
        if (it.cycle) {
          params += `, cycle: true`;
        } else {
          params += `, cycle: false`;
        }
        return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
`;
      }).join("").concat("");
      const schemaStatements = Object.entries(schemas).map((it) => {
        return `export const ${it[1]} = pgSchema("${it[0]}");
`;
      }).join("");
      const rolesNameToTsKey = {};
      const rolesStatements = Object.entries(schema6.roles).map((it) => {
        const fields = it[1];
        rolesNameToTsKey[fields.name] = it[0];
        return `export const ${withCasing2(it[0], casing2)} = pgRole("${fields.name}", ${!fields.createDb && !fields.createRole && fields.inherit ? "" : `${`, { ${fields.createDb ? `createDb: true,` : ""}${fields.createRole ? ` createRole: true,` : ""}${!fields.inherit ? ` inherit: false ` : ""}`.trimChar(",")}}`} );
`;
      }).join("");
      const tableStatements = Object.values(schema6.tables).map((table5) => {
        const tableSchema = schemas[table5.schema];
        const paramName = paramNameFor(table5.name, tableSchema);
        const func = tableSchema ? `${tableSchema}.table` : "pgTable";
        let statement = `export const ${withCasing2(paramName, casing2)} = ${func}("${table5.name}", {
`;
        statement += createTableColumns3(
          table5.name,
          Object.values(table5.columns),
          Object.values(table5.foreignKeys),
          enumTypes,
          schemas,
          casing2,
          schema6.internal
        );
        statement += "}";
        if (Object.keys(table5.indexes).length > 0 || Object.values(table5.foreignKeys).length > 0 || Object.values(table5.policies).length > 0 || Object.keys(table5.compositePrimaryKeys).length > 0 || Object.keys(table5.uniqueConstraints).length > 0 || Object.keys(table5.checkConstraints).length > 0) {
          statement += ", ";
          statement += "(table) => [";
          statement += createTableIndexes3(table5.name, Object.values(table5.indexes), casing2);
          statement += createTableFKs3(Object.values(table5.foreignKeys), schemas, casing2);
          statement += createTablePKs3(
            Object.values(table5.compositePrimaryKeys),
            casing2
          );
          statement += createTableUniques3(
            Object.values(table5.uniqueConstraints),
            casing2
          );
          statement += createTablePolicies(
            Object.values(table5.policies),
            casing2,
            rolesNameToTsKey
          );
          statement += createTableChecks3(
            Object.values(table5.checkConstraints),
            casing2
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const viewsStatements = Object.values(schema6.views).map((it) => {
        const viewSchema = schemas[it.schema];
        const paramName = paramNameFor(it.name, viewSchema);
        const func = viewSchema ? it.materialized ? `${viewSchema}.materializedView` : `${viewSchema}.view` : it.materialized ? "pgMaterializedView" : "pgView";
        const withOption = it.with ?? "";
        const as = `sql\`${it.definition}\``;
        const tablespace = it.tablespace ?? "";
        const columns = createTableColumns3(
          "",
          Object.values(it.columns),
          [],
          enumTypes,
          schemas,
          casing2,
          schema6.internal
        );
        let statement = `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}", {${columns}})`;
        statement += tablespace ? `.tablespace("${tablespace}")` : "";
        statement += withOption ? `.with(${JSON.stringify(withOption)})` : "";
        statement += `.as(${as});`;
        return statement;
      }).join("\n\n");
      const uniquePgImports = ["pgTable", ...new Set(imports.pg)];
      const importsTs = `import { ${uniquePgImports.join(
        ", "
      )} } from "drizzle-orm/pg-core"
import { sql } from "drizzle-orm"

`;
      let decalrations = schemaStatements;
      decalrations += rolesStatements;
      decalrations += enumStatements;
      decalrations += sequencesStatements;
      decalrations += "\n";
      decalrations += tableStatements.join("\n\n");
      decalrations += "\n";
      decalrations += viewsStatements;
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing2(it.name, casing2)).join(",\n")}
    }
  `;
      return { file, imports: importsTs, decalrations, schemaEntry };
    };
    isCyclic3 = (fk4) => {
      const key = `${fk4.tableFrom}-${fk4.tableTo}`;
      const reverse = `${fk4.tableTo}-${fk4.tableFrom}`;
      return relations3.has(key) && relations3.has(reverse);
    };
    isSelf3 = (fk4) => {
      return fk4.tableFrom === fk4.tableTo;
    };
    buildArrayDefault = (defaultValue, typeName) => {
      if (typeof defaultValue === "string" && !(defaultValue.startsWith("{") || defaultValue.startsWith("'{"))) {
        return `sql\`${defaultValue}\``;
      }
      defaultValue = defaultValue.substring(2, defaultValue.length - 2);
      return `[${defaultValue.split(/\s*,\s*/g).map((value) => {
        if (typeName === "json" || typeName === "jsonb") {
          return value.substring(1, value.length - 1).replaceAll("\\", "");
        }
        return value;
      }).join(", ")}]`;
    };
    mapDefault = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
      var _a, _b, _c, _d;
      const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
      const isArray3 = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
      const lowered = type.toLowerCase().replace("[]", "");
      if (isArray3) {
        return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault(defaultValue, lowered)})` : "";
      }
      if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("integer")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("smallint")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("bigint")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("boolean")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("double precision")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("real")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("uuid")) {
        return defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("numeric")) {
        defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
        return defaultValue ? `.default('${mapColumnDefault3(defaultValue, isExpression)}')` : "";
      }
      if (lowered.startsWith("timestamp")) {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}(:\d{2})?)?'$/.test(defaultValue) ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("time")) {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{2}:\d{2}(:\d{2})?(\.\d+)?'$/.test(defaultValue) ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("interval")) {
        return defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered === "date") {
        return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2}'$/.test(defaultValue) ? `.default(${defaultValue})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
      }
      if (lowered.startsWith("text")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("jsonb")) {
        const def = typeof defaultValue !== "undefined" ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
        return defaultValue ? `.default(${def})` : "";
      }
      if (lowered.startsWith("json")) {
        const def = defaultValue ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
        return typeof defaultValue !== "undefined" ? `.default(${def})` : "";
      }
      if (lowered.startsWith("inet")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("cidr")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("macaddr8")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("macaddr")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("varchar")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      if (lowered.startsWith("point")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("line")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("geometry")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("vector")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
      }
      if (lowered.startsWith("char")) {
        return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
      }
      return "";
    };
    column7 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
      var _a, _b;
      const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
      const lowered = type.toLowerCase().replace("[]", "");
      if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
        let out = `${withCasing2(name, casing2)}: ${withCasing2(paramNameFor(type.replace("[]", ""), typeSchema), casing2)}(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("serial")) {
        return `${withCasing2(name, casing2)}: serial(${dbColumnName3({ name, casing: casing2 })})`;
      }
      if (lowered.startsWith("smallserial")) {
        return `${withCasing2(name, casing2)}: smallserial(${dbColumnName3({ name, casing: casing2 })})`;
      }
      if (lowered.startsWith("bigserial")) {
        return `${withCasing2(name, casing2)}: bigserial(${dbColumnName3({ name, casing: casing2, withMode: true })}{ mode: "bigint" })`;
      }
      if (lowered.startsWith("integer")) {
        let out = `${withCasing2(name, casing2)}: integer(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("smallint")) {
        let out = `${withCasing2(name, casing2)}: smallint(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("bigint")) {
        let out = `// You can use { mode: "bigint" } if numbers are exceeding js number limitations
	`;
        out += `${withCasing2(name, casing2)}: bigint(${dbColumnName3({ name, casing: casing2, withMode: true })}{ mode: "number" })`;
        return out;
      }
      if (lowered.startsWith("boolean")) {
        let out = `${withCasing2(name, casing2)}: boolean(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("double precision")) {
        let out = `${withCasing2(name, casing2)}: doublePrecision(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("real")) {
        let out = `${withCasing2(name, casing2)}: real(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("uuid")) {
        let out = `${withCasing2(name, casing2)}: uuid(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("numeric")) {
        let params;
        if (lowered.length > 7) {
          const [precision, scale] = lowered.slice(8, lowered.length - 1).split(",");
          params = { precision, scale };
        }
        let out = params ? `${withCasing2(name, casing2)}: numeric(${dbColumnName3({ name, casing: casing2, withMode: true })}${timeConfig2(params)})` : `${withCasing2(name, casing2)}: numeric(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("timestamp")) {
        const withTimezone = lowered.includes("with time zone");
        let precision = lowered.startsWith("timestamp(") ? Number(lowered.split(" ")[0].substring("timestamp(".length, lowered.split(" ")[0].length - 1)) : null;
        precision = precision ? precision : null;
        const params = timeConfig2({
          precision,
          withTimezone,
          mode: "'string'"
        });
        let out = params ? `${withCasing2(name, casing2)}: timestamp(${dbColumnName3({ name, casing: casing2, withMode: true })}${params})` : `${withCasing2(name, casing2)}: timestamp(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("time")) {
        const withTimezone = lowered.includes("with time zone");
        let precision = lowered.startsWith("time(") ? Number(lowered.split(" ")[0].substring("time(".length, lowered.split(" ")[0].length - 1)) : null;
        precision = precision ? precision : null;
        const params = timeConfig2({ precision, withTimezone });
        let out = params ? `${withCasing2(name, casing2)}: time(${dbColumnName3({ name, casing: casing2, withMode: true })}${params})` : `${withCasing2(name, casing2)}: time(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("interval")) {
        const params = intervalConfig(lowered);
        let out = params ? `${withCasing2(name, casing2)}: interval(${dbColumnName3({ name, casing: casing2, withMode: true })}${params})` : `${withCasing2(name, casing2)}: interval(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered === "date") {
        let out = `${withCasing2(name, casing2)}: date(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("text")) {
        let out = `${withCasing2(name, casing2)}: text(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("jsonb")) {
        let out = `${withCasing2(name, casing2)}: jsonb(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("json")) {
        let out = `${withCasing2(name, casing2)}: json(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("inet")) {
        let out = `${withCasing2(name, casing2)}: inet(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("cidr")) {
        let out = `${withCasing2(name, casing2)}: cidr(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("macaddr8")) {
        let out = `${withCasing2(name, casing2)}: macaddr8(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("macaddr")) {
        let out = `${withCasing2(name, casing2)}: macaddr(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("varchar")) {
        let out;
        if (lowered.length !== 7) {
          out = `${withCasing2(name, casing2)}: varchar(${dbColumnName3({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(8, lowered.length - 1)} })`;
        } else {
          out = `${withCasing2(name, casing2)}: varchar(${dbColumnName3({ name, casing: casing2 })})`;
        }
        return out;
      }
      if (lowered.startsWith("point")) {
        let out = `${withCasing2(name, casing2)}: point(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("line")) {
        let out = `${withCasing2(name, casing2)}: point(${dbColumnName3({ name, casing: casing2 })})`;
        return out;
      }
      if (lowered.startsWith("geometry")) {
        let out = "";
        let isGeoUnknown = false;
        if (lowered.length !== 8) {
          const geometryOptions = lowered.slice(9, -1).split(",");
          if (geometryOptions.length === 1 && geometryOptions[0] !== "") {
            out = `${withCasing2(name, casing2)}: geometry(${dbColumnName3({ name, casing: casing2, withMode: true })}{ type: "${geometryOptions[0]}" })`;
          } else if (geometryOptions.length === 2) {
            out = `${withCasing2(name, casing2)}: geometry(${dbColumnName3({ name, casing: casing2, withMode: true })}{ type: "${geometryOptions[0]}", srid: ${geometryOptions[1]} })`;
          } else {
            isGeoUnknown = true;
          }
        } else {
          out = `${withCasing2(name, casing2)}: geometry(${dbColumnName3({ name, casing: casing2 })})`;
        }
        if (isGeoUnknown) {
          let unknown2 = `// TODO: failed to parse geometry type because found more than 2 options inside geometry function '${type}'
// Introspect is currently supporting only type and srid options
`;
          unknown2 += `	${withCasing2(name, casing2)}: unknown("${name}")`;
          return unknown2;
        }
        return out;
      }
      if (lowered.startsWith("vector")) {
        let out;
        if (lowered.length !== 6) {
          out = `${withCasing2(name, casing2)}: vector(${dbColumnName3({ name, casing: casing2, withMode: true })}{ dimensions: ${lowered.substring(7, lowered.length - 1)} })`;
        } else {
          out = `${withCasing2(name, casing2)}: vector(${dbColumnName3({ name, casing: casing2 })})`;
        }
        return out;
      }
      if (lowered.startsWith("char")) {
        let out;
        if (lowered.length !== 4) {
          out = `${withCasing2(name, casing2)}: char(${dbColumnName3({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(5, lowered.length - 1)} })`;
        } else {
          out = `${withCasing2(name, casing2)}: char(${dbColumnName3({ name, casing: casing2 })})`;
        }
        return out;
      }
      let unknown = `// TODO: failed to parse database type '${type}'
`;
      unknown += `	${withCasing2(name, casing2)}: unknown("${name}")`;
      return unknown;
    };
    dimensionsInArray = (size) => {
      let res = "";
      if (typeof size === "undefined")
        return res;
      for (let i2 = 0; i2 < size; i2++) {
        res += ".array()";
      }
      return res;
    };
    createTableColumns3 = (tableName, columns, fks, enumTypes, schemas, casing2, internals) => {
      let statement = "";
      const oneColumnsFKs = Object.values(fks).filter((it) => {
        return !isSelf3(it);
      }).filter((it) => it.columnsFrom.length === 1);
      const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
        const arr = res[it.columnsFrom[0]] || [];
        arr.push(it);
        res[it.columnsFrom[0]] = arr;
        return res;
      }, {});
      columns.forEach((it) => {
        var _a, _b, _c, _d;
        const columnStatement = column7(
          tableName,
          it.type,
          it.name,
          enumTypes,
          it.typeSchema ?? "public",
          casing2,
          it.default,
          internals
        );
        statement += "	";
        statement += columnStatement;
        if ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[it.name]) == null ? void 0 : _b.isArray) {
          statement += dimensionsInArray((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions);
        }
        statement += mapDefault(tableName, it.type, it.name, enumTypes, it.typeSchema ?? "public", it.default, internals);
        statement += it.primaryKey ? ".primaryKey()" : "";
        statement += it.notNull && !it.identity ? ".notNull()" : "";
        statement += it.identity ? generateIdentityParams(it.identity) : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes3 = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = withCasing2(idxKey, casing2);
        const indexGeneratedName = indexName2(
          tableName,
          it.columns.map((it2) => it2.expression)
        );
        const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `${escapedIndexName})`;
        statement += `${it.concurrently ? `.concurrently()` : ""}`;
        statement += `.using("${it.method}", ${it.columns.map((it2) => {
          if (it2.isExpression) {
            return `sql\`${it2.expression}\``;
          } else {
            return `table.${withCasing2(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass ? `.op("${it2.opclass}")` : ""}`;
          }
        }).join(", ")})`;
        statement += it.where ? `.where(sql\`${it.where}\`)` : "";
        function reverseLogic(mappedWith) {
          let reversedString = "{";
          for (const key in mappedWith) {
            if (mappedWith.hasOwnProperty(key)) {
              reversedString += `${key}: "${mappedWith[key]}",`;
            }
          }
          reversedString = reversedString.length > 1 ? reversedString.slice(0, reversedString.length - 1) : reversedString;
          return `${reversedString}}`;
        }
        statement += it.with && Object.keys(it.with).length > 0 ? `.with(${reverseLogic(it.with)})` : "";
        statement += `,`;
      });
      return statement;
    };
    createTablePKs3 = (pks, casing2) => {
      let statement = "";
      pks.forEach((it) => {
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c) => {
          return `table.${withCasing2(c, casing2)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += ")";
        statement += `,`;
      });
      return statement;
    };
    createTablePolicies = (policies, casing2, rolesNameToTsKey = {}) => {
      let statement = "";
      policies.forEach((it) => {
        var _a, _b, _c;
        const idxKey = withCasing2(it.name, casing2);
        const mappedItTo = (_a = it.to) == null ? void 0 : _a.map((v) => {
          return rolesNameToTsKey[v] ? withCasing2(rolesNameToTsKey[v], casing2) : `"${v}"`;
        });
        statement += `
	`;
        statement += "pgPolicy(";
        statement += `"${it.name}", { `;
        statement += `as: "${(_b = it.as) == null ? void 0 : _b.toLowerCase()}", for: "${(_c = it.for) == null ? void 0 : _c.toLowerCase()}", to: [${mappedItTo == null ? void 0 : mappedItTo.join(", ")}]${it.using ? `, using: sql\`${it.using}\`` : ""}${it.withCheck ? `, withCheck: sql\`${it.withCheck}\` ` : ""}`;
        statement += ` }),`;
      });
      return statement;
    };
    createTableUniques3 = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${withCasing2(it2, casing2)}`).join(", ")})`;
        statement += it.nullsNotDistinct ? `.nullsNotDistinct()` : "";
        statement += `,`;
      });
      return statement;
    };
    createTableChecks3 = (checkConstraints, casing2) => {
      let statement = "";
      checkConstraints.forEach((it) => {
        statement += `
	`;
        statement += "check(";
        statement += `"${it.name}", `;
        statement += `sql\`${it.value}\`)`;
        statement += `,`;
      });
      return statement;
    };
    createTableFKs3 = (fks, schemas, casing2) => {
      let statement = "";
      fks.forEach((it) => {
        const tableSchema = schemas[it.schemaTo || ""];
        const paramName = paramNameFor(it.tableTo, tableSchema);
        const isSelf4 = it.tableTo === it.tableFrom;
        const tableTo = isSelf4 ? "table" : `${withCasing2(paramName, casing2)}`;
        statement += `
	`;
        statement += `foreignKey({
`;
        statement += `			columns: [${it.columnsFrom.map((i2) => `table.${withCasing2(i2, casing2)}`).join(", ")}],
`;
        statement += `			foreignColumns: [${it.columnsTo.map((i2) => `${tableTo}.${withCasing2(i2, casing2)}`).join(", ")}],
`;
        statement += `			name: "${it.name}"
`;
        statement += `		})`;
        statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
        statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
        statement += `,`;
      });
      return statement;
    };
  }
});

// src/introspect-singlestore.ts
var import_casing5, singlestoreImportsList, timeConfig3, binaryConfig2, importsPatch3, escapeColumnKey4, prepareCasing2, dbColumnName4, schemaToTypeScript4, mapColumnDefault4, mapColumnDefaultForJson2, column8, createTableColumns4, createTableIndexes4, createTableUniques4, createTablePKs4;
var init_introspect_singlestore = __esm({
  "src/introspect-singlestore.ts"() {
    "use strict";
    import_casing5 = require("drizzle-orm/casing");
    init_utils();
    init_global();
    init_singlestoreSerializer();
    singlestoreImportsList = /* @__PURE__ */ new Set([
      "singlestoreTable",
      "singlestoreEnum",
      "bigint",
      "binary",
      "boolean",
      "char",
      "date",
      "datetime",
      "decimal",
      "double",
      "float",
      "int",
      "json",
      // TODO: add new type BSON
      // TODO: add new type Blob
      // TODO: add new type UUID
      // TODO: add new type GUID
      // TODO: add new type Vector
      // TODO: add new type GeoPoint
      "mediumint",
      "real",
      "serial",
      "smallint",
      "text",
      "tinytext",
      "mediumtext",
      "longtext",
      "time",
      "timestamp",
      "tinyint",
      "varbinary",
      "varchar",
      "vector",
      "year",
      "enum"
    ]);
    timeConfig3 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    binaryConfig2 = (json) => {
      json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
      const keys = Object.keys(json);
      if (keys.length === 0)
        return;
      let statement = "{ ";
      statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
      statement += " }";
      return statement;
    };
    importsPatch3 = {
      "double precision": "doublePrecision",
      "timestamp without time zone": "timestamp"
    };
    escapeColumnKey4 = (value) => {
      if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
        return `"${value}"`;
      }
      return value;
    };
    prepareCasing2 = (casing2) => (value) => {
      if (casing2 === "preserve") {
        return escapeColumnKey4(value);
      }
      if (casing2 === "camel") {
        return escapeColumnKey4(value.camelCase());
      }
      assertUnreachable(casing2);
    };
    dbColumnName4 = ({ name, casing: casing2, withMode = false }) => {
      if (casing2 === "preserve") {
        return "";
      }
      if (casing2 === "camel") {
        return (0, import_casing5.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
      }
      assertUnreachable(casing2);
    };
    schemaToTypeScript4 = (schema6, casing2) => {
      const withCasing4 = prepareCasing2(casing2);
      const imports = Object.values(schema6.tables).reduce(
        (res, it) => {
          const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
          const pkImports = Object.values(it.compositePrimaryKeys).map(
            (it2) => "primaryKey"
          );
          const uniqueImports = Object.values(it.uniqueConstraints).map(
            (it2) => "unique"
          );
          res.singlestore.push(...idxImports);
          res.singlestore.push(...pkImports);
          res.singlestore.push(...uniqueImports);
          const columnImports = Object.values(it.columns).map((col) => {
            let patched = importsPatch3[col.type] ?? col.type;
            patched = patched.startsWith("varchar(") ? "varchar" : patched;
            patched = patched.startsWith("char(") ? "char" : patched;
            patched = patched.startsWith("binary(") ? "binary" : patched;
            patched = patched.startsWith("decimal(") ? "decimal" : patched;
            patched = patched.startsWith("smallint(") ? "smallint" : patched;
            patched = patched.startsWith("enum(") ? "singlestoreEnum" : patched;
            patched = patched.startsWith("datetime(") ? "datetime" : patched;
            patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
            patched = patched.startsWith("int(") ? "int" : patched;
            patched = patched.startsWith("double(") ? "double" : patched;
            patched = patched.startsWith("float(") ? "float" : patched;
            patched = patched.startsWith("int unsigned") ? "int" : patched;
            patched = patched.startsWith("tinyint(") ? "tinyint" : patched;
            patched = patched.startsWith("mediumint(") ? "mediumint" : patched;
            patched = patched.startsWith("bigint(") ? "bigint" : patched;
            patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
            patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
            patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
            patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
            return patched;
          }).filter((type) => {
            return singlestoreImportsList.has(type);
          });
          res.singlestore.push(...columnImports);
          return res;
        },
        { singlestore: [] }
      );
      const tableStatements = Object.values(schema6.tables).map((table5) => {
        const func = "singlestoreTable";
        let statement = "";
        if (imports.singlestore.includes(withCasing4(table5.name))) {
          statement = `// Table name is in conflict with ${withCasing4(
            table5.name
          )} import.
// Please change to any other name, that is not in imports list
`;
        }
        statement += `export const ${withCasing4(table5.name)} = ${func}("${table5.name}", {
`;
        statement += createTableColumns4(
          Object.values(table5.columns),
          withCasing4,
          casing2,
          table5.name,
          schema6
        );
        statement += "}";
        if (Object.keys(table5.indexes).length > 0 || Object.keys(table5.compositePrimaryKeys).length > 0 || Object.keys(table5.uniqueConstraints).length > 0) {
          statement += ",\n";
          statement += "(table) => [";
          statement += createTableIndexes4(
            table5.name,
            Object.values(table5.indexes),
            withCasing4
          );
          statement += createTablePKs4(
            Object.values(table5.compositePrimaryKeys),
            withCasing4
          );
          statement += createTableUniques4(
            Object.values(table5.uniqueConstraints),
            withCasing4
          );
          statement += "\n]";
        }
        statement += ");";
        return statement;
      });
      const uniqueSingleStoreImports = [
        "singlestoreTable",
        "singlestoreSchema",
        "AnySingleStoreColumn",
        ...new Set(imports.singlestore)
      ];
      const importsTs = `import { ${uniqueSingleStoreImports.join(
        ", "
      )} } from "drizzle-orm/singlestore-core"
import { sql } from "drizzle-orm"

`;
      let decalrations = "";
      decalrations += tableStatements.join("\n\n");
      decalrations += "\n";
      const file = importsTs + decalrations;
      const schemaEntry = `
    {
      ${Object.values(schema6.tables).map((it) => withCasing4(it.name)).join(",")}
    }
  `;
      return {
        file,
        // backward compatible, print to file
        imports: importsTs,
        decalrations,
        schemaEntry
      };
    };
    mapColumnDefault4 = (defaultValue, isExpression) => {
      if (isExpression) {
        return `sql\`${defaultValue}\``;
      }
      return defaultValue;
    };
    mapColumnDefaultForJson2 = (defaultValue) => {
      if (typeof defaultValue === "string" && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
        return defaultValue.substring(2, defaultValue.length - 2);
      }
      return defaultValue;
    };
    column8 = (type, name, casing2, rawCasing, defaultValue, autoincrement, onUpdate, isExpression) => {
      let lowered = type;
      if (!type.startsWith("enum(")) {
        lowered = type.toLowerCase();
      }
      if (lowered === "serial") {
        return `${casing2(name)}: serial(${dbColumnName4({ name, casing: rawCasing })})`;
      }
      if (lowered.startsWith("int")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName4({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: int(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("tinyint")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName4({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: tinyint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("smallint")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName4({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: smallint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("mediumint")) {
        const isUnsigned = lowered.includes("unsigned");
        const columnName = dbColumnName4({ name, casing: rawCasing, withMode: isUnsigned });
        let out = `${casing2(name)}: mediumint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("bigint")) {
        const isUnsigned = lowered.includes("unsigned");
        let out = `${casing2(name)}: bigint(${dbColumnName4({ name, casing: rawCasing, withMode: true })}{ mode: "number"${isUnsigned ? ", unsigned: true" : ""} })`;
        out += autoincrement ? `.autoincrement()` : "";
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "boolean") {
        let out = `${casing2(name)}: boolean(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("double")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 15 : 6)) {
          const [precision, scale] = lowered.slice(7, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig3(params) : void 0;
        let out = params ? `${casing2(name)}: double(${dbColumnName4({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfig3(params)})` : `${casing2(name)}: double(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("float")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 14 : 5)) {
          const [precision, scale] = lowered.slice(6, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        let out = `${casing2(name)}: float(${dbColumnName4({ name, casing: rawCasing })}${params ? timeConfig3(params) : ""})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "real") {
        let out = `${casing2(name)}: real(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("timestamp")) {
        const keyLength = "timestamp".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig3({ fsp, mode: "'string'" });
        let out = params ? `${casing2(name)}: timestamp(${dbColumnName4({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: timestamp(${dbColumnName4({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" || defaultValue === "CURRENT_TIMESTAMP" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        out += defaultValue;
        let onUpdateNow = onUpdate ? ".onUpdateNow()" : "";
        out += onUpdateNow;
        return out;
      }
      if (lowered.startsWith("time")) {
        const keyLength = "time".length + 1;
        let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        fsp = fsp ? fsp : null;
        const params = timeConfig3({ fsp });
        let out = params ? `${casing2(name)}: time(${dbColumnName4({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: time(${dbColumnName4({ name, casing: rawCasing })})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "date") {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	${casing2(
          name
        )}: date(${dbColumnName4({ name, casing: rawCasing, withMode: true })}{ mode: 'string' })`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered === "text") {
        let out = `${casing2(name)}: text(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "tinytext") {
        let out = `${casing2(name)}: tinytext(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "mediumtext") {
        let out = `${casing2(name)}: mediumtext(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "longtext") {
        let out = `${casing2(name)}: longtext(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "year") {
        let out = `${casing2(name)}: year(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered === "json") {
        let out = `${casing2(name)}: json(${dbColumnName4({ name, casing: rawCasing })})`;
        out += defaultValue ? `.default(${mapColumnDefaultForJson2(defaultValue)})` : "";
        return out;
      }
      if (lowered.startsWith("varchar")) {
        let out = `${casing2(
          name
        )}: varchar(${dbColumnName4({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "varchar".length + 1,
          lowered.length - 1
        )} })`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("char")) {
        let out = `${casing2(
          name
        )}: char(${dbColumnName4({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
          "char".length + 1,
          lowered.length - 1
        )} })`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("datetime")) {
        let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
	`;
        const fsp = lowered.startsWith("datetime(") ? lowered.substring("datetime".length + 1, lowered.length - 1) : void 0;
        out = fsp ? `${casing2(
          name
        )}: datetime(${dbColumnName4({ name, casing: rawCasing, withMode: true })}{ mode: 'string', fsp: ${lowered.substring(
          "datetime".length + 1,
          lowered.length - 1
        )} })` : `${casing2(name)}: datetime(${dbColumnName4({ name, casing: rawCasing, withMode: true })}{ mode: 'string'})`;
        defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("decimal")) {
        let params;
        if (lowered.length > (lowered.includes("unsigned") ? 16 : 7)) {
          const [precision, scale] = lowered.slice(8, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
          params = { precision, scale };
        }
        if (lowered.includes("unsigned")) {
          params = { ...params ?? {}, unsigned: true };
        }
        const timeConfigParams = params ? timeConfig3(params) : void 0;
        let out = params ? `${casing2(name)}: decimal(${dbColumnName4({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfigParams})` : `${casing2(name)}: decimal(${dbColumnName4({ name, casing: rawCasing })})`;
        defaultValue = typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("binary")) {
        const keyLength = "binary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig2({ length });
        let out = params ? `${casing2(name)}: binary(${dbColumnName4({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: binary(${dbColumnName4({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("enum")) {
        const values = lowered.substring("enum".length + 1, lowered.length - 1);
        let out = `${casing2(name)}: singlestoreEnum(${dbColumnName4({ name, casing: rawCasing, withMode: true })}[${values}])`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      if (lowered.startsWith("varbinary")) {
        const keyLength = "varbinary".length + 1;
        let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
        length = length ? length : null;
        const params = binaryConfig2({ length });
        let out = params ? `${casing2(name)}: varbinary(${dbColumnName4({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: varbinary(${dbColumnName4({ name, casing: rawCasing })})`;
        defaultValue = defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        out += defaultValue;
        return out;
      }
      if (lowered.startsWith("vector")) {
        const [dimensions, elementType] = lowered.substring("vector".length + 1, lowered.length - 1).split(",");
        let out = `${casing2(name)}: vector(${dbColumnName4({ name, casing: rawCasing, withMode: true })}{ dimensions: ${dimensions}, elementType: ${elementType} })`;
        out += defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
        return out;
      }
      console.log("uknown", type);
      return `// Warning: Can't parse ${type} from database
	// ${type}Type: ${type}("${name}")`;
    };
    createTableColumns4 = (columns, casing2, rawCasing, tableName, schema6) => {
      let statement = "";
      columns.forEach((it) => {
        var _a, _b, _c;
        statement += "	";
        statement += column8(
          it.type,
          it.name,
          casing2,
          rawCasing,
          it.default,
          it.autoincrement,
          it.onUpdate,
          ((_c = (_b = (_a = schema6.internal) == null ? void 0 : _a.tables[tableName]) == null ? void 0 : _b.columns[it.name]) == null ? void 0 : _c.isDefaultAnExpression) ?? false
        );
        statement += it.primaryKey ? ".primaryKey()" : "";
        statement += it.notNull ? ".notNull()" : "";
        statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(
          /`/g,
          "\\`"
        )}\`, { mode: "${it.generated.type}" })` : "";
        statement += ",\n";
      });
      return statement;
    };
    createTableIndexes4 = (tableName, idxs, casing2) => {
      let statement = "";
      idxs.forEach((it) => {
        let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
        idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
        idxKey = casing2(idxKey);
        const indexGeneratedName = indexName3(tableName, it.columns);
        const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
        statement += `
	`;
        statement += it.isUnique ? "uniqueIndex(" : "index(";
        statement += `${escapedIndexName})`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTableUniques4 = (unqs, casing2) => {
      let statement = "";
      unqs.forEach((it) => {
        statement += `
	`;
        statement += "unique(";
        statement += `"${it.name}")`;
        statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
      });
      return statement;
    };
    createTablePKs4 = (pks, casing2) => {
      let statement = "";
      pks.forEach((it) => {
        let idxKey = casing2(it.name);
        statement += `
	`;
        statement += "primaryKey({ columns: [";
        statement += `${it.columns.map((c) => {
          return `table.${casing2(c)}`;
        }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
        statement += "),";
      });
      return statement;
    };
  }
});

// src/cli/commands/introspect.ts
var introspect_exports = {};
__export(introspect_exports, {
  introspectLibSQL: () => introspectLibSQL,
  introspectMysql: () => introspectMysql,
  introspectPostgres: () => introspectPostgres,
  introspectSingleStore: () => introspectSingleStore,
  introspectSqlite: () => introspectSqlite,
  relationsToTypeScript: () => relationsToTypeScript
});
var import_fs11, import_hanji14, import_path7, import_pluralize, introspectPostgres, introspectMysql, introspectSingleStore, introspectSqlite, introspectLibSQL, withCasing3, relationsToTypeScript;
var init_introspect = __esm({
  "src/cli/commands/introspect.ts"() {
    "use strict";
    init_source();
    import_fs11 = require("fs");
    import_hanji14 = __toESM(require_hanji());
    init_mjs();
    import_path7 = require("path");
    import_pluralize = __toESM(require_pluralize());
    init_singlestoreSchema();
    init_global();
    init_introspect_mysql();
    init_introspect_pg();
    init_introspect_singlestore();
    init_introspect_sqlite();
    init_mysqlSchema();
    init_mysqlSerializer();
    init_pgSchema();
    init_pgSerializer();
    init_singlestoreSerializer();
    init_sqliteSchema();
    init_sqliteSerializer();
    init_snapshotsDiffer();
    init_utils2();
    init_views();
    init_migrate();
    introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
      const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await preparePostgresDB2(credentials2);
      const matchers = tablesFilter.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 IntrospectProgress(true);
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase2(
          db,
          filter2,
          schemasFilter,
          entities,
          (stage, count, status) => {
            progress.update(stage, count, status);
          }
        )
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript3(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const { internal, ...schemaWithoutInternals } = schema6;
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "postgresql");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applyPgSnapshotsDiff(
          squashPgScheme(dryPg),
          squashPgScheme(schema6),
          schemasResolver,
          enumsResolver,
          sequencesResolver,
          policyResolver,
          indPolicyResolver,
          roleResolver,
          tablesResolver,
          columnsResolver,
          viewsResolver,
          dryPg,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    introspectMysql = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { db, database } = await connectToMySQL2(credentials2);
      const matchers = tablesFilter.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 IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase(db, database, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript2(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const { internal, ...schemaWithoutInternals } = schema6;
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "mysql");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applyMysqlSnapshotsDiff(
          squashMysqlScheme(dryMySql),
          squashMysqlScheme(schema6),
          tablesResolver,
          columnsResolver,
          mySqlViewsResolver,
          dryMySql,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    introspectSingleStore = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { db, database } = await connectToSingleStore2(credentials2);
      const matchers = tablesFilter.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 IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase4(db, database, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript4(schema6, casing2);
      const { internal, ...schemaWithoutInternals } = schema6;
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "postgresql");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
          squashSingleStoreScheme(drySingleStore),
          squashSingleStoreScheme(schema6),
          tablesResolver,
          columnsResolver,
          /* singleStoreViewsResolver, */
          drySingleStore,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] You schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      process.exit(0);
    };
    introspectSqlite = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await connectToSQLite2(credentials2);
      const matchers = tablesFilter.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 IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase3(db, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "sqlite");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
          squashSqliteScheme(drySQLite),
          squashSqliteScheme(schema6),
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          drySQLite,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] You schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] You relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    introspectLibSQL = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
      const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await connectToLibSQL2(credentials2);
      const matchers = tablesFilter.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 IntrospectProgress();
      const res = await (0, import_hanji14.renderWithTask)(
        progress,
        fromDatabase3(db, filter2, (stage, count, status) => {
          progress.update(stage, count, status);
        })
      );
      const schema6 = { id: originUUID, prevId: "", ...res };
      const ts = schemaToTypeScript(schema6, casing2);
      const relationsTs = relationsToTypeScript(schema6, casing2);
      const schemaFile = (0, import_path7.join)(out, "schema.ts");
      (0, import_fs11.writeFileSync)(schemaFile, ts.file);
      const relationsFile = (0, import_path7.join)(out, "relations.ts");
      (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
      console.log();
      const { snapshots, journal } = prepareOutFolder(out, "sqlite");
      if (snapshots.length === 0) {
        const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
          squashSqliteScheme(drySQLite),
          squashSqliteScheme(schema6),
          tablesResolver,
          columnsResolver,
          sqliteViewsResolver,
          drySQLite,
          schema6
        );
        writeResult({
          cur: schema6,
          sqlStatements,
          journal,
          _meta,
          outFolder: out,
          breakpoints,
          type: "introspect",
          prefixMode: prefix2
        });
      } else {
        (0, import_hanji14.render)(
          `[${source_default.blue(
            "i"
          )}] No SQL generated, you already have migrations in project`
        );
      }
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
      );
      (0, import_hanji14.render)(
        `[${source_default.green(
          "\u2713"
        )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
          relationsFile
        )} \u{1F680}`
      );
      process.exit(0);
    };
    withCasing3 = (value, casing2) => {
      if (casing2 === "preserve") {
        return value;
      }
      if (casing2 === "camel") {
        return value.camelCase();
      }
      assertUnreachable(casing2);
    };
    relationsToTypeScript = (schema6, casing2) => {
      const imports = [];
      const tableRelations = {};
      Object.values(schema6.tables).forEach((table5) => {
        Object.values(table5.foreignKeys).forEach((fk4) => {
          const tableNameFrom = paramNameFor(fk4.tableFrom, table5.schema);
          const tableNameTo = paramNameFor(fk4.tableTo, fk4.schemaTo);
          const tableFrom = withCasing3(tableNameFrom, casing2);
          const tableTo = withCasing3(tableNameTo, casing2);
          const columnFrom = withCasing3(fk4.columnsFrom[0], casing2);
          const columnTo = withCasing3(fk4.columnsTo[0], casing2);
          imports.push(tableTo, tableFrom);
          const keyFrom = tableFrom;
          if (!tableRelations[keyFrom]) {
            tableRelations[keyFrom] = [];
          }
          tableRelations[keyFrom].push({
            name: (0, import_pluralize.singular)(tableTo),
            type: "one",
            tableFrom,
            columnFrom,
            tableTo,
            columnTo
          });
          const keyTo = tableTo;
          if (!tableRelations[keyTo]) {
            tableRelations[keyTo] = [];
          }
          tableRelations[keyTo].push({
            name: (0, import_pluralize.plural)(tableFrom),
            type: "many",
            tableFrom: tableTo,
            columnFrom: columnTo,
            tableTo: tableFrom,
            columnTo: columnFrom
          });
        });
      });
      const uniqueImports = [...new Set(imports)];
      const importsTs = `import { relations } from "drizzle-orm/relations";
import { ${uniqueImports.join(
        ", "
      )} } from "./schema";

`;
      const relationStatements = Object.entries(tableRelations).map(
        ([table5, relations4]) => {
          const hasOne = relations4.some((it) => it.type === "one");
          const hasMany = relations4.some((it) => it.type === "many");
          const preparedRelations = relations4.map(
            (relation, relationIndex, originArray) => {
              let name = relation.name;
              let relationName;
              const hasMultipleRelations = originArray.some(
                (it, originIndex) => relationIndex !== originIndex && it.tableTo === relation.tableTo
              );
              if (hasMultipleRelations) {
                relationName = relation.type === "one" ? `${relation.tableFrom}_${relation.columnFrom}_${relation.tableTo}_${relation.columnTo}` : `${relation.tableTo}_${relation.columnTo}_${relation.tableFrom}_${relation.columnFrom}`;
              }
              const hasDuplicatedRelation = originArray.some(
                (it, originIndex) => relationIndex !== originIndex && it.name === relation.name
              );
              if (hasDuplicatedRelation) {
                name = `${relation.name}_${relation.type === "one" ? relation.columnFrom : relation.columnTo}`;
              }
              return {
                ...relation,
                name,
                relationName
              };
            }
          );
          const fields = preparedRelations.map((relation) => {
            if (relation.type === "one") {
              return `	${relation.name}: one(${relation.tableTo}, {
		fields: [${relation.tableFrom}.${relation.columnFrom}],
		references: [${relation.tableTo}.${relation.columnTo}]${relation.relationName ? `,
		relationName: "${relation.relationName}"` : ""}
	}),`;
            } else {
              return `	${relation.name}: many(${relation.tableTo}${relation.relationName ? `, {
		relationName: "${relation.relationName}"
	}` : ""}),`;
            }
          });
          return `export const ${table5}Relations = relations(${table5}, ({${hasOne ? "one" : ""}${hasOne && hasMany ? ", " : ""}${hasMany ? "many" : ""}}) => ({
${fields.join("\n")}
}));`;
        }
      );
      return {
        file: importsTs + relationStatements.join("\n\n")
      };
    };
  }
});

// ../node_modules/.pnpm/@hono+node-server@1.12.0/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 (e2) {
      cancel(e2);
    }
  }
}
function getInternalBody(response) {
  if (!stateKey) {
    return;
  }
  if (response instanceof Response22) {
    response = response[getResponseCache]();
  }
  const state = response[stateKey];
  return state && state.body || void 0;
}
var import_http, import_http2, import_stream2, import_crypto7, RequestError, toRequestError, GlobalRequest, Request3, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, abortControllerKey, getAbortController, requestPrototype, newRequest, buildOutgoingHttpHeaders, responseCache, getResponseCache, cacheKey, GlobalResponse, Response22, stateKey, X_ALREADY_SENT, webFetch, regBuffer, regContentType, handleRequestError, handleFetchError, handleResponseError, responseViaCache, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
var init_dist2 = __esm({
  "../node_modules/.pnpm/@hono+node-server@1.12.0/node_modules/@hono/node-server/dist/index.mjs"() {
    import_http = require("http");
    import_http2 = require("http2");
    import_stream2 = require("stream");
    import_crypto7 = __toESM(require("crypto"), 1);
    RequestError = class extends Error {
      static name = "RequestError";
      constructor(message, options) {
        super(message, options);
      }
    };
    toRequestError = (e2) => {
      if (e2 instanceof RequestError) {
        return e2;
      }
      return new RequestError(e2.message, { cause: e2 });
    };
    GlobalRequest = global.Request;
    Request3 = class extends GlobalRequest {
      constructor(input, options) {
        var _a;
        if (typeof input === "object" && getRequestCache in input) {
          input = input[getRequestCache]();
        }
        if (typeof ((_a = options == null ? void 0 : options.body) == null ? void 0 : _a.getReader) !== "undefined") {
          ;
          options.duplex ??= "half";
        }
        super(input, options);
      }
    };
    newRequestFromIncoming = (method, url, incoming, abortController) => {
      const headerRecord = [];
      const rawHeaders = incoming.rawHeaders;
      for (let i2 = 0; i2 < rawHeaders.length; i2 += 2) {
        const { [i2]: key, [i2 + 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 Request3(url, init2);
        Object.defineProperty(req, "method", {
          get() {
            return "TRACE";
          }
        });
        return req;
      }
      if (!(method === "GET" || method === "HEAD")) {
        init2.body = import_stream2.Readable.toWeb(incoming);
      }
      return new Request3(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((k) => {
      Object.defineProperty(requestPrototype, k, {
        get() {
          return this[getRequestCache]()[k];
        }
      });
    });
    ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
      Object.defineProperty(requestPrototype, k, {
        value: function() {
          return this[getRequestCache]()[k]();
        }
      });
    });
    Object.setPrototypeOf(requestPrototype, Request3.prototype);
    newRequest = (incoming, defaultHostname) => {
      const req = Object.create(requestPrototype);
      req[incomingKey] = incoming;
      const host = (incoming instanceof import_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
      if (!host) {
        throw new RequestError("Missing host header");
      }
      const url = new URL(
        `${incoming instanceof import_http2.Http2ServerRequest || incoming.socket && incoming.socket.encrypted ? "https" : "http"}://${host}${incoming.url}`
      );
      if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
        throw new RequestError("Invalid host header");
      }
      req[urlKey] = url.href;
      return req;
    };
    buildOutgoingHttpHeaders = (headers) => {
      const res = {};
      const cookies = [];
      for (const [k, v] of headers) {
        if (k === "set-cookie") {
          cookies.push(v);
        } else {
          res[k] = v;
        }
      }
      if (cookies.length > 0) {
        res["set-cookie"] = cookies;
      }
      res["content-type"] ??= "text/plain; charset=UTF-8";
      return res;
    };
    responseCache = Symbol("responseCache");
    getResponseCache = Symbol("getResponseCache");
    cacheKey = Symbol("cache");
    GlobalResponse = global.Response;
    Response22 = class _Response {
      #body;
      #init;
      [getResponseCache]() {
        delete this[cacheKey];
        return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
      }
      constructor(body, init2) {
        this.#body = body;
        if (init2 instanceof _Response) {
          const cachedGlobalResponse = init2[responseCache];
          if (cachedGlobalResponse) {
            this.#init = cachedGlobalResponse;
            this[getResponseCache]();
            return;
          } else {
            this.#init = init2.#init;
          }
        } else {
          this.#init = init2;
        }
        if (typeof body === "string" || typeof (body == null ? void 0 : body.getReader) !== "undefined") {
          let headers = (init2 == null ? void 0 : init2.headers) || { "content-type": "text/plain; charset=UTF-8" };
          if (headers instanceof Headers) {
            headers = buildOutgoingHttpHeaders(headers);
          }
          ;
          this[cacheKey] = [(init2 == null ? void 0 : init2.status) || 200, body, headers];
        }
      }
    };
    [
      "body",
      "bodyUsed",
      "headers",
      "ok",
      "redirected",
      "status",
      "statusText",
      "trailers",
      "type",
      "url"
    ].forEach((k) => {
      Object.defineProperty(Response22.prototype, k, {
        get() {
          return this[getResponseCache]()[k];
        }
      });
    });
    ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
      Object.defineProperty(Response22.prototype, k, {
        value: function() {
          return this[getResponseCache]()[k]();
        }
      });
    });
    Object.setPrototypeOf(Response22, GlobalResponse);
    Object.setPrototypeOf(Response22.prototype, GlobalResponse.prototype);
    stateKey = Reflect.ownKeys(new GlobalResponse()).find(
      (k) => typeof k === "symbol" && k.toString() === "Symbol(state)"
    );
    if (!stateKey) {
      console.warn("Failed to find Response internal state key");
    }
    X_ALREADY_SENT = "x-hono-already-sent";
    webFetch = global.fetch;
    if (typeof global.crypto === "undefined") {
      global.crypto = import_crypto7.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 = (e2) => new Response(null, {
      status: e2 instanceof Error && (e2.name === "TimeoutError" || e2.constructor.name === "TimeoutError") ? 504 : 500
    });
    handleResponseError = (e2, outgoing) => {
      const err2 = e2 instanceof Error ? e2 : new Error("unknown error", { cause: e2 });
      if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") {
        console.info("The user aborted a request.");
      } else {
        console.error(e2);
        if (!outgoing.headersSent) {
          outgoing.writeHead(500, { "Content-Type": "text/plain" });
        }
        outgoing.end(`Error: ${err2.message}`);
        outgoing.destroy(err2);
      }
    };
    responseViaCache = (res, outgoing) => {
      var _a;
      const [status, body, header] = res[cacheKey];
      if (typeof body === "string") {
        header["Content-Length"] = Buffer.byteLength(body);
        outgoing.writeHead(status, header);
        outgoing.end(body);
      } else {
        outgoing.writeHead(status, header);
        return (_a = writeFromReadableStream(body, outgoing)) == null ? void 0 : _a.catch(
          (e2) => handleResponseError(e2, 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);
      const internalBody = getInternalBody(res);
      if (internalBody) {
        if (internalBody.length) {
          resHeaderRecord["content-length"] = internalBody.length;
        }
        outgoing.writeHead(res.status, resHeaderRecord);
        if (typeof internalBody.source === "string" || internalBody.source instanceof Uint8Array) {
          outgoing.end(internalBody.source);
        } else if (internalBody.source instanceof Blob) {
          outgoing.end(new Uint8Array(await internalBody.source.arrayBuffer()));
        } else {
          await writeFromReadableStream(internalBody.stream, outgoing);
        }
      } else 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 !== Request3) {
        Object.defineProperty(global, "Request", {
          value: Request3
        });
        Object.defineProperty(global, "Response", {
          value: Response22
        });
      }
      return async (incoming, outgoing) => {
        let res, req;
        try {
          req = newRequest(incoming, options.hostname);
          outgoing.on("close", () => {
            if (incoming.errored) {
              req[getAbortController]().abort(incoming.errored.toString());
            }
          });
          res = fetchCallback(req, { incoming, outgoing });
          if (cacheKey in res) {
            return responseViaCache(res, outgoing);
          }
        } catch (e2) {
          if (!res) {
            if (options.errorHandler) {
              res = await options.errorHandler(req ? e2 : toRequestError(e2));
              if (!res) {
                return;
              }
            } else if (!req) {
              res = handleRequestError();
            } else {
              res = handleFetchError(e2);
            }
          } else {
            return handleResponseError(e2, outgoing);
          }
        }
        try {
          return responseViaResponseObject(res, outgoing, options);
        } catch (e2) {
          return handleResponseError(e2, 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 == null ? void 0 : options.port) ?? 3e3, options.hostname ?? "0.0.0.0", () => {
        const serverInfo = server.address();
        listeningListener && listeningListener(serverInfo);
      });
      return server;
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/url.js
var splitPath, splitRoutingPath, extractGroupsFromPath, replaceGroupMarks, patternCache, getPattern, tryDecodeURI, getPath, getPathNoStrict, mergePath, checkOptionalParameter, _decodeURI, _getQueryParam, getQueryParam, getQueryParams, decodeURIComponent_;
var init_url = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/url.js"() {
    splitPath = (path4) => {
      const paths = path4.split("/");
      if (paths[0] === "") {
        paths.shift();
      }
      return paths;
    };
    splitRoutingPath = (routePath) => {
      const { groups, path: path4 } = extractGroupsFromPath(routePath);
      const paths = splitPath(path4);
      return replaceGroupMarks(paths, groups);
    };
    extractGroupsFromPath = (path4) => {
      const groups = [];
      path4 = path4.replace(/\{[^}]+\}/g, (match2, index5) => {
        const mark = `@${index5}`;
        groups.push([mark, match2]);
        return mark;
      });
      return { groups, path: path4 };
    };
    replaceGroupMarks = (paths, groups) => {
      for (let i2 = groups.length - 1; i2 >= 0; i2--) {
        const [mark] = groups[i2];
        for (let j = paths.length - 1; j >= 0; j--) {
          if (paths[j].includes(mark)) {
            paths[j] = paths[j].replace(mark, groups[i2][1]);
            break;
          }
        }
      }
      return paths;
    };
    patternCache = {};
    getPattern = (label) => {
      if (label === "*") {
        return "*";
      }
      const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
      if (match2) {
        if (!patternCache[label]) {
          if (match2[2]) {
            patternCache[label] = [label, match2[1], new RegExp("^" + match2[2] + "$")];
          } else {
            patternCache[label] = [label, match2[1], true];
          }
        }
        return patternCache[label];
      }
      return null;
    };
    tryDecodeURI = (str) => {
      try {
        return decodeURI(str);
      } catch {
        return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
          try {
            return decodeURI(match2);
          } catch {
            return match2;
          }
        });
      }
    };
    getPath = (request) => {
      const url = request.url;
      const start = url.indexOf("/", 8);
      let i2 = start;
      for (; i2 < url.length; i2++) {
        const charCode = url.charCodeAt(i2);
        if (charCode === 37) {
          const queryIndex = url.indexOf("?", i2);
          const path4 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
          return tryDecodeURI(path4.includes("%25") ? path4.replace(/%25/g, "%2525") : path4);
        } else if (charCode === 63) {
          break;
        }
      }
      return url.slice(start, i2);
    };
    getPathNoStrict = (request) => {
      const result = getPath(request);
      return result.length > 1 && result[result.length - 1] === "/" ? result.slice(0, -1) : result;
    };
    mergePath = (...paths) => {
      let p = "";
      let endsWithSlash = false;
      for (let path4 of paths) {
        if (p[p.length - 1] === "/") {
          p = p.slice(0, -1);
          endsWithSlash = true;
        }
        if (path4[0] !== "/") {
          path4 = `/${path4}`;
        }
        if (path4 === "/" && endsWithSlash) {
          p = `${p}/`;
        } else if (path4 !== "/") {
          p = `${p}${path4}`;
        }
        if (path4 === "/" && p === "") {
          p = "/";
        }
      }
      return p;
    };
    checkOptionalParameter = (path4) => {
      if (!path4.match(/\:.+\?$/)) {
        return null;
      }
      const segments = path4.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((v, i2, a) => a.indexOf(v) === i2);
    };
    _decodeURI = (value) => {
      if (!/[%+]/.test(value)) {
        return value;
      }
      if (value.indexOf("+") !== -1) {
        value = value.replace(/\+/g, " ");
      }
      return /%/.test(value) ? 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.5.0/node_modules/hono/dist/utils/cookie.js
var validCookieNameRegEx, validCookieValueRegEx, parse3;
var init_cookie = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/cookie.js"() {
    init_url();
    validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
    validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
    parse3 = (cookie, name) => {
      const pairs = cookie.trim().split(";");
      return pairs.reduce((parsedCookie, pairStr) => {
        pairStr = pairStr.trim();
        const valueStartPos = pairStr.indexOf("=");
        if (valueStartPos === -1) {
          return parsedCookie;
        }
        const cookieName = pairStr.substring(0, valueStartPos).trim();
        if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
          return parsedCookie;
        }
        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);
        }
        return parsedCookie;
      }, {});
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/helper/cookie/index.js
var getCookie;
var init_cookie2 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/helper/cookie/index.js"() {
    init_cookie();
    getCookie = (c, key, prefix2) => {
      const cookie = c.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 = parse3(cookie, finalKey);
        return obj2[finalKey];
      }
      if (!cookie) {
        return {};
      }
      const obj = parse3(cookie);
      return obj;
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/http-exception.js
var HTTPException;
var init_http_exception = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/http-exception.js"() {
    HTTPException = class extends Error {
      res;
      status;
      constructor(status = 500, options) {
        super(options == null ? void 0 : options.message, { cause: options == null ? void 0 : options.cause });
        this.res = options == null ? void 0 : 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.5.0/node_modules/hono/dist/utils/crypto.js
var init_crypto = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/crypto.js"() {
  }
});

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

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/validator/validator.js
var validator;
var init_validator = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/validator/validator.js"() {
    init_cookie2();
    init_http_exception();
    init_buffer();
    validator = (target, validationFunc) => {
      return async (c, next) => {
        let value = {};
        const contentType = c.req.header("Content-Type");
        switch (target) {
          case "json":
            if (!contentType || !/^application\/([a-z-\.]+\+)?json/.test(contentType)) {
              const message = `Invalid HTTP header: Content-Type=${contentType}`;
              throw new HTTPException(400, { message });
            }
            try {
              value = await c.req.json();
            } catch {
              const message = "Malformed JSON in request body";
              throw new HTTPException(400, { message });
            }
            break;
          case "form": {
            if (!contentType) {
              break;
            }
            let formData;
            if (c.req.bodyCache.formData) {
              formData = await c.req.bodyCache.formData;
            } else {
              try {
                const arrayBuffer = await c.req.arrayBuffer();
                formData = await bufferToFormData(arrayBuffer, contentType);
                c.req.bodyCache.formData = formData;
              } catch (e2) {
                let message = "Malformed FormData request.";
                message += e2 instanceof Error ? ` ${e2.message}` : ` ${String(e2)}`;
                throw new HTTPException(400, { message });
              }
            }
            const form = {};
            formData.forEach((value2, key) => {
              if (key.endsWith("[]")) {
                if (form[key] === void 0) {
                  form[key] = [value2];
                } else if (Array.isArray(form[key])) {
                  ;
                  form[key].push(value2);
                }
              } else {
                form[key] = value2;
              }
            });
            value = form;
            break;
          }
          case "query":
            value = Object.fromEntries(
              Object.entries(c.req.queries()).map(([k, v]) => {
                return v.length === 1 ? [k, v[0]] : [k, v];
              })
            );
            break;
          case "param":
            value = c.req.param();
            break;
          case "header":
            value = c.req.header();
            break;
          case "cookie":
            value = getCookie(c);
            break;
        }
        const res = await validationFunc(value, c);
        if (res instanceof Response) {
          return res;
        }
        c.req.addValidatedData(target, res);
        await next();
      };
    };
  }
});

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

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

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/body.js
async function parseFormData(request, options) {
  const formData = await request.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_body2 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/body.js"() {
    init_request2();
    parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
      const { all = false, dot = false } = options;
      const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
      const contentType = headers.get("Content-Type");
      if (contentType !== null && contentType.startsWith("multipart/form-data") || contentType !== null && contentType.startsWith("application/x-www-form-urlencoded")) {
        return parseFormData(request, { 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, index5) => {
        if (index5 === 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.5.0/node_modules/hono/dist/request.js
var HonoRequest;
var init_request2 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/request.js"() {
    init_body2();
    init_url();
    HonoRequest = class {
      raw;
      #validatedData;
      #matchResult;
      routeIndex = 0;
      path;
      bodyCache = {};
      constructor(request, path4 = "/", matchResult = [[]]) {
        this.raw = request;
        this.path = path4;
        this.#matchResult = matchResult;
        this.#validatedData = {};
      }
      param(key) {
        return key ? this.getDecodedParam(key) : this.getAllDecodedParams();
      }
      getDecodedParam(key) {
        const paramKey = this.#matchResult[0][this.routeIndex][1][key];
        const param = this.getParamValue(paramKey);
        return param ? /\%/.test(param) ? decodeURIComponent_(param) : param : void 0;
      }
      getAllDecodedParams() {
        const decoded = {};
        const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
        for (const key of keys) {
          const value = this.getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
          if (value && typeof value === "string") {
            decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value;
          }
        }
        return decoded;
      }
      getParamValue(paramKey) {
        return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
      }
      query(key) {
        return getQueryParam(this.url, key);
      }
      queries(key) {
        return getQueryParams(this.url, key);
      }
      header(name) {
        if (name) {
          return this.raw.headers.get(name.toLowerCase()) ?? 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);
      }
      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]();
      };
      json() {
        return this.cachedBody("json");
      }
      text() {
        return this.cachedBody("text");
      }
      arrayBuffer() {
        return this.cachedBody("arrayBuffer");
      }
      blob() {
        return this.cachedBody("blob");
      }
      formData() {
        return this.cachedBody("formData");
      }
      addValidatedData(target, data) {
        this.#validatedData[target] = data;
      }
      valid(target) {
        return this.#validatedData[target];
      }
      get url() {
        return this.raw.url;
      }
      get method() {
        return this.raw.method;
      }
      get matchedRoutes() {
        return this.#matchResult[0].map(([[, route]]) => route);
      }
      get routePath() {
        return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/html.js
var HtmlEscapedCallbackPhase, raw, resolveCallback;
var init_html = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/utils/html.js"() {
    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) => {
      const callbacks = str.callbacks;
      if (!(callbacks == null ? void 0 : callbacks.length)) {
        return Promise.resolve(str);
      }
      if (buffer) {
        buffer[0] += str;
      } else {
        buffer = [str];
      }
      const resStr = Promise.all(callbacks.map((c) => c({ 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.5.0/node_modules/hono/dist/context.js
var TEXT_PLAIN, setHeaders, Context;
var init_context = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/context.js"() {
    init_request2();
    init_html();
    TEXT_PLAIN = "text/plain; charset=UTF-8";
    setHeaders = (headers, map = {}) => {
      Object.entries(map).forEach(([key, value]) => headers.set(key, value));
      return headers;
    };
    Context = class {
      #rawRequest;
      #req;
      env = {};
      #var;
      finalized = false;
      error;
      #status = 200;
      #executionCtx;
      #headers;
      #preparedHeaders;
      #res;
      #isFresh = true;
      #layout;
      #renderer;
      #notFoundHandler;
      #matchResult;
      #path;
      constructor(req, options) {
        this.#rawRequest = req;
        if (options) {
          this.#executionCtx = options.executionCtx;
          this.env = options.env;
          this.#notFoundHandler = options.notFoundHandler;
          this.#path = options.path;
          this.#matchResult = options.matchResult;
        }
      }
      get req() {
        this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
        return this.#req;
      }
      get event() {
        if (this.#executionCtx && "respondWith" in this.#executionCtx) {
          return this.#executionCtx;
        } else {
          throw Error("This context has no FetchEvent");
        }
      }
      get executionCtx() {
        if (this.#executionCtx) {
          return this.#executionCtx;
        } else {
          throw Error("This context has no ExecutionContext");
        }
      }
      get res() {
        this.#isFresh = false;
        return this.#res ||= new Response("404 Not Found", { status: 404 });
      }
      set res(_res) {
        this.#isFresh = false;
        if (this.#res && _res) {
          this.#res.headers.delete("content-type");
          for (const [k, v] of this.#res.headers.entries()) {
            if (k === "set-cookie") {
              const cookies = this.#res.headers.getSetCookie();
              _res.headers.delete("set-cookie");
              for (const cookie of cookies) {
                _res.headers.append("set-cookie", cookie);
              }
            } else {
              _res.headers.set(k, v);
            }
          }
        }
        this.#res = _res;
        this.finalized = true;
      }
      render = (...args) => {
        this.#renderer ??= (content) => this.html(content);
        return this.#renderer(...args);
      };
      setLayout = (layout) => this.#layout = layout;
      getLayout = () => this.#layout;
      setRenderer = (renderer) => {
        this.#renderer = renderer;
      };
      header = (name, value, options) => {
        if (value === void 0) {
          if (this.#headers) {
            this.#headers.delete(name);
          } else if (this.#preparedHeaders) {
            delete this.#preparedHeaders[name.toLocaleLowerCase()];
          }
          if (this.finalized) {
            this.res.headers.delete(name);
          }
          return;
        }
        if (options == null ? void 0 : options.append) {
          if (!this.#headers) {
            this.#isFresh = false;
            this.#headers = new Headers(this.#preparedHeaders);
            this.#preparedHeaders = {};
          }
          this.#headers.append(name, value);
        } else {
          if (this.#headers) {
            this.#headers.set(name, value);
          } else {
            this.#preparedHeaders ??= {};
            this.#preparedHeaders[name.toLowerCase()] = value;
          }
        }
        if (this.finalized) {
          if (options == null ? void 0 : options.append) {
            this.res.headers.append(name, value);
          } else {
            this.res.headers.set(name, value);
          }
        }
      };
      status = (status) => {
        this.#isFresh = false;
        this.#status = status;
      };
      set = (key, value) => {
        this.#var ??= /* @__PURE__ */ new Map();
        this.#var.set(key, value);
      };
      get = (key) => {
        return this.#var ? this.#var.get(key) : void 0;
      };
      get var() {
        if (!this.#var) {
          return {};
        }
        return Object.fromEntries(this.#var);
      }
      newResponse = (data, arg, headers) => {
        if (this.#isFresh && !headers && !arg && this.#status === 200) {
          return new Response(data, {
            headers: this.#preparedHeaders
          });
        }
        if (arg && typeof arg !== "number") {
          const header = new Headers(arg.headers);
          if (this.#headers) {
            this.#headers.forEach((v, k) => {
              if (k === "set-cookie") {
                header.append(k, v);
              } else {
                header.set(k, v);
              }
            });
          }
          const headers2 = setHeaders(header, this.#preparedHeaders);
          return new Response(data, {
            headers: headers2,
            status: arg.status ?? this.#status
          });
        }
        const status = typeof arg === "number" ? arg : this.#status;
        this.#preparedHeaders ??= {};
        this.#headers ??= new Headers();
        setHeaders(this.#headers, this.#preparedHeaders);
        if (this.#res) {
          this.#res.headers.forEach((v, k) => {
            var _a, _b;
            if (k === "set-cookie") {
              (_a = this.#headers) == null ? void 0 : _a.append(k, v);
            } else {
              (_b = this.#headers) == null ? void 0 : _b.set(k, v);
            }
          });
          setHeaders(this.#headers, this.#preparedHeaders);
        }
        headers ??= {};
        for (const [k, v] of Object.entries(headers)) {
          if (typeof v === "string") {
            this.#headers.set(k, v);
          } else {
            this.#headers.delete(k);
            for (const v2 of v) {
              this.#headers.append(k, v2);
            }
          }
        }
        return new Response(data, {
          status,
          headers: this.#headers
        });
      };
      body = (data, arg, headers) => {
        return typeof arg === "number" ? this.newResponse(data, arg, headers) : this.newResponse(data, arg);
      };
      text = (text, arg, headers) => {
        if (!this.#preparedHeaders) {
          if (this.#isFresh && !headers && !arg) {
            return new Response(text);
          }
          this.#preparedHeaders = {};
        }
        this.#preparedHeaders["content-type"] = TEXT_PLAIN;
        return typeof arg === "number" ? this.newResponse(text, arg, headers) : this.newResponse(text, arg);
      };
      json = (object, arg, headers) => {
        const body = JSON.stringify(object);
        this.#preparedHeaders ??= {};
        this.#preparedHeaders["content-type"] = "application/json; charset=UTF-8";
        return typeof arg === "number" ? this.newResponse(body, arg, headers) : this.newResponse(body, arg);
      };
      html = (html, arg, headers) => {
        this.#preparedHeaders ??= {};
        this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
        if (typeof html === "object") {
          if (!(html instanceof Promise)) {
            html = html.toString();
          }
          if (html instanceof Promise) {
            return html.then((html2) => resolveCallback(html2, HtmlEscapedCallbackPhase.Stringify, false, {})).then((html2) => {
              return typeof arg === "number" ? this.newResponse(html2, arg, headers) : this.newResponse(html2, arg);
            });
          }
        }
        return typeof arg === "number" ? this.newResponse(html, arg, headers) : this.newResponse(html, arg);
      };
      redirect = (location, status) => {
        this.#headers ??= new Headers();
        this.#headers.set("Location", location);
        return this.newResponse(null, status ?? 302);
      };
      notFound = () => {
        this.#notFoundHandler ??= () => new Response();
        return this.#notFoundHandler(this);
      };
    };
  }
});

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

// ../node_modules/.pnpm/hono@4.5.0/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.5.0/node_modules/hono/dist/router.js"() {
    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.5.0/node_modules/hono/dist/hono-base.js
var COMPOSED_HANDLER, notFoundHandler, errorHandler, Hono;
var init_hono_base = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/hono-base.js"() {
    init_compose();
    init_context();
    init_router();
    init_url();
    COMPOSED_HANDLER = Symbol("composedHandler");
    notFoundHandler = (c) => {
      return c.text("404 Not Found", 404);
    };
    errorHandler = (err2, c) => {
      if ("getResponse" in err2) {
        return err2.getResponse();
      }
      console.error(err2);
      return c.text("Internal Server Error", 500);
    };
    Hono = class {
      get;
      post;
      put;
      delete;
      options;
      patch;
      all;
      on;
      use;
      router;
      getPath;
      _basePath = "/";
      #path = "/";
      routes = [];
      constructor(options = {}) {
        const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
        allMethods.forEach((method) => {
          this[method] = (args1, ...args) => {
            if (typeof args1 === "string") {
              this.#path = args1;
            } else {
              this.addRoute(method, this.#path, args1);
            }
            args.forEach((handler) => {
              if (typeof handler !== "string") {
                this.addRoute(method, this.#path, handler);
              }
            });
            return this;
          };
        });
        this.on = (method, path4, ...handlers) => {
          for (const p of [path4].flat()) {
            this.#path = p;
            for (const m2 of [method].flat()) {
              handlers.map((handler) => {
                this.addRoute(m2.toUpperCase(), this.#path, handler);
              });
            }
          }
          return this;
        };
        this.use = (arg1, ...handlers) => {
          if (typeof arg1 === "string") {
            this.#path = arg1;
          } else {
            this.#path = "*";
            handlers.unshift(arg1);
          }
          handlers.forEach((handler) => {
            this.addRoute(METHOD_NAME_ALL, this.#path, handler);
          });
          return this;
        };
        const strict = options.strict ?? true;
        delete options.strict;
        Object.assign(this, options);
        this.getPath = strict ? options.getPath ?? getPath : getPathNoStrict;
      }
      clone() {
        const clone2 = new Hono({
          router: this.router,
          getPath: this.getPath
        });
        clone2.routes = this.routes;
        return clone2;
      }
      notFoundHandler = notFoundHandler;
      errorHandler = errorHandler;
      route(path4, app) {
        const subApp = this.basePath(path4);
        app.routes.map((r2) => {
          let handler;
          if (app.errorHandler === errorHandler) {
            handler = r2.handler;
          } else {
            handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r2.handler(c, next))).res;
            handler[COMPOSED_HANDLER] = r2.handler;
          }
          subApp.addRoute(r2.method, r2.path, handler);
        });
        return this;
      }
      basePath(path4) {
        const subApp = this.clone();
        subApp._basePath = mergePath(this._basePath, path4);
        return subApp;
      }
      onError = (handler) => {
        this.errorHandler = handler;
        return this;
      };
      notFound = (handler) => {
        this.notFoundHandler = handler;
        return this;
      };
      mount(path4, applicationHandler, options) {
        let replaceRequest;
        let optionHandler;
        if (options) {
          if (typeof options === "function") {
            optionHandler = options;
          } else {
            optionHandler = options.optionHandler;
            replaceRequest = options.replaceRequest;
          }
        }
        const getOptions = optionHandler ? (c) => {
          const options2 = optionHandler(c);
          return Array.isArray(options2) ? options2 : [options2];
        } : (c) => {
          let executionContext = void 0;
          try {
            executionContext = c.executionCtx;
          } catch {
          }
          return [c.env, executionContext];
        };
        replaceRequest ||= (() => {
          const mergedPath = mergePath(this._basePath, path4);
          const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
          return (request) => {
            const url = new URL(request.url);
            url.pathname = url.pathname.slice(pathPrefixLength) || "/";
            return new Request(url, request);
          };
        })();
        const handler = async (c, next) => {
          const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
          if (res) {
            return res;
          }
          await next();
        };
        this.addRoute(METHOD_NAME_ALL, mergePath(path4, "*"), handler);
        return this;
      }
      addRoute(method, path4, handler) {
        method = method.toUpperCase();
        path4 = mergePath(this._basePath, path4);
        const r2 = { path: path4, method, handler };
        this.router.add(method, path4, [handler, r2]);
        this.routes.push(r2);
      }
      matchRoute(method, path4) {
        return this.router.match(method, path4);
      }
      handleError(err2, c) {
        if (err2 instanceof Error) {
          return this.errorHandler(err2, c);
        }
        throw err2;
      }
      dispatch(request, executionCtx, env3, method) {
        if (method === "HEAD") {
          return (async () => new Response(null, await this.dispatch(request, executionCtx, env3, "GET")))();
        }
        const path4 = this.getPath(request, { env: env3 });
        const matchResult = this.matchRoute(method, path4);
        const c = new Context(request, {
          path: path4,
          matchResult,
          env: env3,
          executionCtx,
          notFoundHandler: this.notFoundHandler
        });
        if (matchResult[0].length === 1) {
          let res;
          try {
            res = matchResult[0][0][0][0](c, async () => {
              c.res = await this.notFoundHandler(c);
            });
          } catch (err2) {
            return this.handleError(err2, c);
          }
          return res instanceof Promise ? res.then(
            (resolved) => resolved || (c.finalized ? c.res : this.notFoundHandler(c))
          ).catch((err2) => this.handleError(err2, c)) : res ?? this.notFoundHandler(c);
        }
        const composed = compose(matchResult[0], this.errorHandler, this.notFoundHandler);
        return (async () => {
          try {
            const context = await composed(c);
            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 this.handleError(err2, c);
          }
        })();
      }
      fetch = (request, ...rest) => {
        return this.dispatch(request, rest[1], rest[0], request.method);
      };
      request = (input, requestInit, Env, executionCtx) => {
        if (input instanceof Request) {
          if (requestInit !== void 0) {
            input = new Request(input, requestInit);
          }
          return this.fetch(input, Env, executionCtx);
        }
        input = input.toString();
        const path4 = /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`;
        const req = new Request(path4, requestInit);
        return this.fetch(req, Env, executionCtx);
      };
      fire = () => {
        addEventListener("fetch", (event) => {
          event.respondWith(this.dispatch(event.request, event, void 0, event.request.method));
        });
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/reg-exp-router/node.js
function compareKey(a, b) {
  if (a.length === 1) {
    return b.length === 1 ? a < b ? -1 : 1 : -1;
  }
  if (b.length === 1) {
    return 1;
  }
  if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
    return 1;
  } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
    return -1;
  }
  if (a === LABEL_REG_EXP_STR) {
    return 1;
  } else if (b === LABEL_REG_EXP_STR) {
    return -1;
  }
  return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
}
var LABEL_REG_EXP_STR, ONLY_WILDCARD_REG_EXP_STR, TAIL_WILDCARD_REG_EXP_STR, PATH_ERROR, regExpMetaChars, Node;
var init_node = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/reg-exp-router/node.js"() {
    LABEL_REG_EXP_STR = "[^/]+";
    ONLY_WILDCARD_REG_EXP_STR = ".*";
    TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
    PATH_ERROR = Symbol();
    regExpMetaChars = new Set(".\\+*[^]$()");
    Node = class {
      index;
      varIndex;
      children = /* @__PURE__ */ Object.create(null);
      insert(tokens, index5, paramMap, context, pathErrorCheckOnly) {
        if (tokens.length === 0) {
          if (this.index !== void 0) {
            throw PATH_ERROR;
          }
          if (pathErrorCheckOnly) {
            return;
          }
          this.index = index5;
          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 = this.children[regexpStr];
          if (!node) {
            if (Object.keys(this.children).some(
              (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
            )) {
              throw PATH_ERROR;
            }
            if (pathErrorCheckOnly) {
              return;
            }
            node = this.children[regexpStr] = new Node();
            if (name !== "") {
              node.varIndex = context.varIndex++;
            }
          }
          if (!pathErrorCheckOnly && name !== "") {
            paramMap.push([name, node.varIndex]);
          }
        } else {
          node = this.children[token];
          if (!node) {
            if (Object.keys(this.children).some(
              (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
            )) {
              throw PATH_ERROR;
            }
            if (pathErrorCheckOnly) {
              return;
            }
            node = this.children[token] = new Node();
          }
        }
        node.insert(restTokens, index5, paramMap, context, pathErrorCheckOnly);
      }
      buildRegExpStr() {
        const childKeys = Object.keys(this.children).sort(compareKey);
        const strList = childKeys.map((k) => {
          const c = this.children[k];
          return (typeof c.varIndex === "number" ? `(${k})@${c.varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
        });
        if (typeof this.index === "number") {
          strList.unshift(`#${this.index}`);
        }
        if (strList.length === 0) {
          return "";
        }
        if (strList.length === 1) {
          return strList[0];
        }
        return "(?:" + strList.join("|") + ")";
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/reg-exp-router/trie.js
var Trie;
var init_trie = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/reg-exp-router/trie.js"() {
    init_node();
    Trie = class {
      context = { varIndex: 0 };
      root = new Node();
      insert(path4, index5, pathErrorCheckOnly) {
        const paramAssoc = [];
        const groups = [];
        for (let i2 = 0; ; ) {
          let replaced = false;
          path4 = path4.replace(/\{[^}]+\}/g, (m2) => {
            const mark = `@\\${i2}`;
            groups[i2] = [mark, m2];
            i2++;
            replaced = true;
            return mark;
          });
          if (!replaced) {
            break;
          }
        }
        const tokens = path4.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
        for (let i2 = groups.length - 1; i2 >= 0; i2--) {
          const [mark] = groups[i2];
          for (let j = tokens.length - 1; j >= 0; j--) {
            if (tokens[j].indexOf(mark) !== -1) {
              tokens[j] = tokens[j].replace(mark, groups[i2][1]);
              break;
            }
          }
        }
        this.root.insert(tokens, index5, paramAssoc, this.context, pathErrorCheckOnly);
        return paramAssoc;
      }
      buildRegExp() {
        let regexp = this.root.buildRegExpStr();
        if (regexp === "") {
          return [/^$/, [], []];
        }
        let captureIndex = 0;
        const indexReplacementMap = [];
        const paramReplacementMap = [];
        regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_2, handlerIndex, paramIndex) => {
          if (typeof handlerIndex !== "undefined") {
            indexReplacementMap[++captureIndex] = Number(handlerIndex);
            return "$()";
          }
          if (typeof paramIndex !== "undefined") {
            paramReplacementMap[Number(paramIndex)] = ++captureIndex;
            return "";
          }
          return "";
        });
        return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/reg-exp-router/router.js
function buildWildcardRegExp(path4) {
  return wildcardRegExpCache[path4] ??= new RegExp(
    path4 === "*" ? "" : `^${path4.replace(
      /\/\*$|([.\\+*[^\]$()])/g,
      (_2, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
    )}$`
  );
}
function clearWildcardRegExpCache() {
  wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
}
function buildMatcherFromPreprocessedRoutes(routes) {
  var _a;
  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 i2 = 0, j = -1, len = routesWithStaticPathFlag.length; i2 < len; i2++) {
    const [pathErrorCheckOnly, path4, handlers] = routesWithStaticPathFlag[i2];
    if (pathErrorCheckOnly) {
      staticMap[path4] = [handlers.map(([h2]) => [h2, /* @__PURE__ */ Object.create(null)]), emptyParam];
    } else {
      j++;
    }
    let paramAssoc;
    try {
      paramAssoc = trie.insert(path4, j, pathErrorCheckOnly);
    } catch (e2) {
      throw e2 === PATH_ERROR ? new UnsupportedPathError(path4) : e2;
    }
    if (pathErrorCheckOnly) {
      continue;
    }
    handlerData[j] = handlers.map(([h2, paramCount]) => {
      const paramIndexMap = /* @__PURE__ */ Object.create(null);
      paramCount -= 1;
      for (; paramCount >= 0; paramCount--) {
        const [key, value] = paramAssoc[paramCount];
        paramIndexMap[key] = value;
      }
      return [h2, paramIndexMap];
    });
  }
  const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
  for (let i2 = 0, len = handlerData.length; i2 < len; i2++) {
    for (let j = 0, len2 = handlerData[i2].length; j < len2; j++) {
      const map = (_a = handlerData[i2][j]) == null ? void 0 : _a[1];
      if (!map) {
        continue;
      }
      const keys = Object.keys(map);
      for (let k = 0, len3 = keys.length; k < len3; k++) {
        map[keys[k]] = paramReplacementMap[map[keys[k]]];
      }
    }
  }
  const handlerMap = [];
  for (const i2 in indexReplacementMap) {
    handlerMap[i2] = handlerData[indexReplacementMap[i2]];
  }
  return [regexp, handlerMap, staticMap];
}
function findMiddleware(middleware, path4) {
  if (!middleware) {
    return void 0;
  }
  for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
    if (buildWildcardRegExp(k).test(path4)) {
      return [...middleware[k]];
    }
  }
  return void 0;
}
var emptyParam, nullMatcher, wildcardRegExpCache, RegExpRouter;
var init_router2 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/reg-exp-router/router.js"() {
    init_router();
    init_url();
    init_node();
    init_trie();
    emptyParam = [];
    nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
    wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
    RegExpRouter = class {
      name = "RegExpRouter";
      middleware;
      routes;
      constructor() {
        this.middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
        this.routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
      }
      add(method, path4, handler) {
        const { middleware, routes } = this;
        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((p) => {
              handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
            });
          });
        }
        if (path4 === "/*") {
          path4 = "*";
        }
        const paramCount = (path4.match(/\/:/g) || []).length;
        if (/\*$/.test(path4)) {
          const re = buildWildcardRegExp(path4);
          if (method === METHOD_NAME_ALL) {
            Object.keys(middleware).forEach((m2) => {
              middleware[m2][path4] ||= findMiddleware(middleware[m2], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
            });
          } else {
            middleware[method][path4] ||= findMiddleware(middleware[method], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
          }
          Object.keys(middleware).forEach((m2) => {
            if (method === METHOD_NAME_ALL || method === m2) {
              Object.keys(middleware[m2]).forEach((p) => {
                re.test(p) && middleware[m2][p].push([handler, paramCount]);
              });
            }
          });
          Object.keys(routes).forEach((m2) => {
            if (method === METHOD_NAME_ALL || method === m2) {
              Object.keys(routes[m2]).forEach(
                (p) => re.test(p) && routes[m2][p].push([handler, paramCount])
              );
            }
          });
          return;
        }
        const paths = checkOptionalParameter(path4) || [path4];
        for (let i2 = 0, len = paths.length; i2 < len; i2++) {
          const path22 = paths[i2];
          Object.keys(routes).forEach((m2) => {
            if (method === METHOD_NAME_ALL || method === m2) {
              routes[m2][path22] ||= [
                ...findMiddleware(middleware[m2], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
              ];
              routes[m2][path22].push([handler, paramCount - len + i2 + 1]);
            }
          });
        }
      }
      match(method, path4) {
        clearWildcardRegExpCache();
        const matchers = this.buildAllMatchers();
        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 index5 = match2.indexOf("", 1);
          return [matcher[1][index5], match2];
        };
        return this.match(method, path4);
      }
      buildAllMatchers() {
        const matchers = /* @__PURE__ */ Object.create(null);
        [...Object.keys(this.routes), ...Object.keys(this.middleware)].forEach((method) => {
          matchers[method] ||= this.buildMatcher(method);
        });
        this.middleware = this.routes = void 0;
        return matchers;
      }
      buildMatcher(method) {
        const routes = [];
        let hasOwnRoute = method === METHOD_NAME_ALL;
        [this.middleware, this.routes].forEach((r2) => {
          const ownRoute = r2[method] ? Object.keys(r2[method]).map((path4) => [path4, r2[method][path4]]) : [];
          if (ownRoute.length !== 0) {
            hasOwnRoute ||= true;
            routes.push(...ownRoute);
          } else if (method !== METHOD_NAME_ALL) {
            routes.push(
              ...Object.keys(r2[METHOD_NAME_ALL]).map((path4) => [path4, r2[METHOD_NAME_ALL][path4]])
            );
          }
        });
        if (!hasOwnRoute) {
          return null;
        } else {
          return buildMatcherFromPreprocessedRoutes(routes);
        }
      }
    };
  }
});

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

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/smart-router/router.js
var SmartRouter;
var init_router3 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/smart-router/router.js"() {
    init_router();
    SmartRouter = class {
      name = "SmartRouter";
      routers = [];
      routes = [];
      constructor(init2) {
        Object.assign(this, init2);
      }
      add(method, path4, handler) {
        if (!this.routes) {
          throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
        }
        this.routes.push([method, path4, handler]);
      }
      match(method, path4) {
        if (!this.routes) {
          throw new Error("Fatal error");
        }
        const { routers, routes } = this;
        const len = routers.length;
        let i2 = 0;
        let res;
        for (; i2 < len; i2++) {
          const router = routers[i2];
          try {
            routes.forEach((args) => {
              router.add(...args);
            });
            res = router.match(method, path4);
          } catch (e2) {
            if (e2 instanceof UnsupportedPathError) {
              continue;
            }
            throw e2;
          }
          this.match = router.match.bind(router);
          this.routers = [router];
          this.routes = void 0;
          break;
        }
        if (i2 === len) {
          throw new Error("Fatal error");
        }
        this.name = `SmartRouter + ${this.activeRouter.name}`;
        return res;
      }
      get activeRouter() {
        if (this.routes || this.routers.length !== 1) {
          throw new Error("No active router has been determined yet.");
        }
        return this.routers[0];
      }
    };
  }
});

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

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/trie-router/node.js
var Node2;
var init_node2 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/trie-router/node.js"() {
    init_router();
    init_url();
    Node2 = class {
      methods;
      children;
      patterns;
      order = 0;
      name;
      params = /* @__PURE__ */ Object.create(null);
      constructor(method, handler, children) {
        this.children = children || /* @__PURE__ */ Object.create(null);
        this.methods = [];
        this.name = "";
        if (method && handler) {
          const m2 = /* @__PURE__ */ Object.create(null);
          m2[method] = { handler, possibleKeys: [], score: 0, name: this.name };
          this.methods = [m2];
        }
        this.patterns = [];
      }
      insert(method, path4, handler) {
        this.name = `${method} ${path4}`;
        this.order = ++this.order;
        let curNode = this;
        const parts = splitRoutingPath(path4);
        const possibleKeys = [];
        for (let i2 = 0, len = parts.length; i2 < len; i2++) {
          const p = parts[i2];
          if (Object.keys(curNode.children).includes(p)) {
            curNode = curNode.children[p];
            const pattern2 = getPattern(p);
            if (pattern2) {
              possibleKeys.push(pattern2[1]);
            }
            continue;
          }
          curNode.children[p] = new Node2();
          const pattern = getPattern(p);
          if (pattern) {
            curNode.patterns.push(pattern);
            possibleKeys.push(pattern[1]);
          }
          curNode = curNode.children[p];
        }
        if (!curNode.methods.length) {
          curNode.methods = [];
        }
        const m2 = /* @__PURE__ */ Object.create(null);
        const handlerSet = {
          handler,
          possibleKeys: possibleKeys.filter((v, i2, a) => a.indexOf(v) === i2),
          name: this.name,
          score: this.order
        };
        m2[method] = handlerSet;
        curNode.methods.push(m2);
        return curNode;
      }
      gHSets(node, method, nodeParams, params) {
        const handlerSets = [];
        for (let i2 = 0, len = node.methods.length; i2 < len; i2++) {
          const m2 = node.methods[i2];
          const handlerSet = m2[method] || m2[METHOD_NAME_ALL];
          const processedSet = /* @__PURE__ */ Object.create(null);
          if (handlerSet !== void 0) {
            handlerSet.params = /* @__PURE__ */ Object.create(null);
            handlerSet.possibleKeys.forEach((key) => {
              const processed = processedSet[handlerSet.name];
              handlerSet.params[key] = params[key] && !processed ? params[key] : nodeParams[key] ?? params[key];
              processedSet[handlerSet.name] = true;
            });
            handlerSets.push(handlerSet);
          }
        }
        return handlerSets;
      }
      search(method, path4) {
        const handlerSets = [];
        this.params = /* @__PURE__ */ Object.create(null);
        const curNode = this;
        let curNodes = [curNode];
        const parts = splitPath(path4);
        for (let i2 = 0, len = parts.length; i2 < len; i2++) {
          const part = parts[i2];
          const isLast = i2 === len - 1;
          const tempNodes = [];
          for (let j = 0, len2 = curNodes.length; j < len2; j++) {
            const node = curNodes[j];
            const nextNode = node.children[part];
            if (nextNode) {
              nextNode.params = node.params;
              if (isLast === true) {
                if (nextNode.children["*"]) {
                  handlerSets.push(
                    ...this.gHSets(nextNode.children["*"], method, node.params, /* @__PURE__ */ Object.create(null))
                  );
                }
                handlerSets.push(...this.gHSets(nextNode, method, node.params, /* @__PURE__ */ Object.create(null)));
              } else {
                tempNodes.push(nextNode);
              }
            }
            for (let k = 0, len3 = node.patterns.length; k < len3; k++) {
              const pattern = node.patterns[k];
              const params = { ...node.params };
              if (pattern === "*") {
                const astNode = node.children["*"];
                if (astNode) {
                  handlerSets.push(...this.gHSets(astNode, method, node.params, /* @__PURE__ */ Object.create(null)));
                  tempNodes.push(astNode);
                }
                continue;
              }
              if (part === "") {
                continue;
              }
              const [key, name, matcher] = pattern;
              const child = node.children[key];
              const restPathString = parts.slice(i2).join("/");
              if (matcher instanceof RegExp && matcher.test(restPathString)) {
                params[name] = restPathString;
                handlerSets.push(...this.gHSets(child, method, node.params, params));
                continue;
              }
              if (matcher === true || matcher instanceof RegExp && matcher.test(part)) {
                if (typeof key === "string") {
                  params[name] = part;
                  if (isLast === true) {
                    handlerSets.push(...this.gHSets(child, method, params, node.params));
                    if (child.children["*"]) {
                      handlerSets.push(...this.gHSets(child.children["*"], method, params, node.params));
                    }
                  } else {
                    child.params = params;
                    tempNodes.push(child);
                  }
                }
              }
            }
          }
          curNodes = tempNodes;
        }
        const results = handlerSets.sort((a, b) => {
          return a.score - b.score;
        });
        return [results.map(({ handler, params }) => [handler, params])];
      }
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/trie-router/router.js
var TrieRouter;
var init_router4 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/router/trie-router/router.js"() {
    init_url();
    init_node2();
    TrieRouter = class {
      name = "TrieRouter";
      node;
      constructor() {
        this.node = new Node2();
      }
      add(method, path4, handler) {
        const results = checkOptionalParameter(path4);
        if (results) {
          for (const p of results) {
            this.node.insert(method, p, handler);
          }
          return;
        }
        this.node.insert(method, path4, handler);
      }
      match(method, path4) {
        return this.node.search(method, path4);
      }
    };
  }
});

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

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/hono.js
var Hono2;
var init_hono = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/hono.js"() {
    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.5.0/node_modules/hono/dist/index.js
var init_dist3 = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/index.js"() {
    init_hono();
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/middleware/compress/index.js
var ENCODING_TYPES, compress;
var init_compress = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/middleware/compress/index.js"() {
    ENCODING_TYPES = ["gzip", "deflate"];
    compress = (options) => {
      return async function compress2(ctx, next) {
        await next();
        const accepted = ctx.req.header("Accept-Encoding");
        const encoding = (options == null ? void 0 : options.encoding) ?? ENCODING_TYPES.find((encoding2) => accepted == null ? void 0 : 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);
      };
    };
  }
});

// ../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/middleware/cors/index.js
var cors;
var init_cors = __esm({
  "../node_modules/.pnpm/hono@4.5.0/node_modules/hono/dist/middleware/cors/index.js"() {
    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") {
          return () => optsOrigin;
        } else if (typeof optsOrigin === "function") {
          return optsOrigin;
        } else {
          return (origin) => optsOrigin.includes(origin) ? origin : optsOrigin[0];
        }
      })(opts.origin);
      return async function cors2(c, next) {
        var _a, _b;
        function set(key, value) {
          c.res.headers.set(key, value);
        }
        const allowOrigin = findAllowOrigin(c.req.header("origin") || "", c);
        if (allowOrigin) {
          set("Access-Control-Allow-Origin", allowOrigin);
        }
        if (opts.origin !== "*") {
          const existingVary = c.req.header("Vary");
          if (existingVary) {
            set("Vary", existingVary);
          } else {
            set("Vary", "Origin");
          }
        }
        if (opts.credentials) {
          set("Access-Control-Allow-Credentials", "true");
        }
        if ((_a = opts.exposeHeaders) == null ? void 0 : _a.length) {
          set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
        }
        if (c.req.method === "OPTIONS") {
          if (opts.maxAge != null) {
            set("Access-Control-Max-Age", opts.maxAge.toString());
          }
          if ((_b = opts.allowMethods) == null ? void 0 : _b.length) {
            set("Access-Control-Allow-Methods", opts.allowMethods.join(","));
          }
          let headers = opts.allowHeaders;
          if (!(headers == null ? void 0 : headers.length)) {
            const requestHeaders = c.req.header("Access-Control-Request-Headers");
            if (requestHeaders) {
              headers = requestHeaders.split(/\s*,\s*/);
            }
          }
          if (headers == null ? void 0 : headers.length) {
            set("Access-Control-Allow-Headers", headers.join(","));
            c.res.headers.append("Vary", "Access-Control-Request-Headers");
          }
          c.res.headers.delete("Content-Length");
          c.res.headers.delete("Content-Type");
          return new Response(null, {
            headers: c.res.headers,
            status: 204,
            statusText: c.res.statusText
          });
        }
        await next();
      };
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/double-indexed-kv.js
var DoubleIndexedKV;
var init_double_indexed_kv = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/double-indexed-kv.js"() {
    DoubleIndexedKV = class {
      constructor() {
        this.keyToValue = /* @__PURE__ */ new Map();
        this.valueToKey = /* @__PURE__ */ new Map();
      }
      set(key, value) {
        this.keyToValue.set(key, value);
        this.valueToKey.set(value, key);
      }
      getByKey(key) {
        return this.keyToValue.get(key);
      }
      getByValue(value) {
        return this.valueToKey.get(value);
      }
      clear() {
        this.keyToValue.clear();
        this.valueToKey.clear();
      }
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/registry.js
var Registry;
var init_registry = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/registry.js"() {
    init_double_indexed_kv();
    Registry = class {
      constructor(generateIdentifier) {
        this.generateIdentifier = generateIdentifier;
        this.kv = new DoubleIndexedKV();
      }
      register(value, identifier) {
        if (this.kv.getByValue(value)) {
          return;
        }
        if (!identifier) {
          identifier = this.generateIdentifier(value);
        }
        this.kv.set(identifier, value);
      }
      clear() {
        this.kv.clear();
      }
      getIdentifier(value) {
        return this.kv.getByValue(value);
      }
      getValue(identifier) {
        return this.kv.getByKey(identifier);
      }
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/class-registry.js
var ClassRegistry;
var init_class_registry = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/class-registry.js"() {
    init_registry();
    ClassRegistry = class extends Registry {
      constructor() {
        super((c) => c.name);
        this.classToAllowedProps = /* @__PURE__ */ new Map();
      }
      register(value, options) {
        if (typeof options === "object") {
          if (options.allowProps) {
            this.classToAllowedProps.set(value, options.allowProps);
          }
          super.register(value, options.identifier);
        } else {
          super.register(value, options);
        }
      }
      getAllowedProps(value) {
        return this.classToAllowedProps.get(value);
      }
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/util.js
function valuesOfObj(record) {
  if ("values" in Object) {
    return Object.values(record);
  }
  const values = [];
  for (const key in record) {
    if (record.hasOwnProperty(key)) {
      values.push(record[key]);
    }
  }
  return values;
}
function find(record, predicate) {
  const values = valuesOfObj(record);
  if ("find" in values) {
    return values.find(predicate);
  }
  const valuesNotNever = values;
  for (let i2 = 0; i2 < valuesNotNever.length; i2++) {
    const value = valuesNotNever[i2];
    if (predicate(value)) {
      return value;
    }
  }
  return void 0;
}
function forEach(record, run2) {
  Object.entries(record).forEach(([key, value]) => run2(value, key));
}
function includes(arr, value) {
  return arr.indexOf(value) !== -1;
}
function findArr(record, predicate) {
  for (let i2 = 0; i2 < record.length; i2++) {
    const value = record[i2];
    if (predicate(value)) {
      return value;
    }
  }
  return void 0;
}
var init_util = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/util.js"() {
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/custom-transformer-registry.js
var CustomTransformerRegistry;
var init_custom_transformer_registry = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/custom-transformer-registry.js"() {
    init_util();
    CustomTransformerRegistry = class {
      constructor() {
        this.transfomers = {};
      }
      register(transformer) {
        this.transfomers[transformer.name] = transformer;
      }
      findApplicable(v) {
        return find(this.transfomers, (transformer) => transformer.isApplicable(v));
      }
      findByName(name) {
        return this.transfomers[name];
      }
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/is.js
var getType, isUndefined, isNull, isPlainObject, isEmptyObject, isArray, isString, isNumber, isBoolean, isRegExp, isMap, isSet, isSymbol, isDate, isError, isNaNValue, isPrimitive, isBigint, isInfinite, isTypedArray, isURL;
var init_is2 = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/is.js"() {
    getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
    isUndefined = (payload) => typeof payload === "undefined";
    isNull = (payload) => payload === null;
    isPlainObject = (payload) => {
      if (typeof payload !== "object" || payload === null)
        return false;
      if (payload === Object.prototype)
        return false;
      if (Object.getPrototypeOf(payload) === null)
        return true;
      return Object.getPrototypeOf(payload) === Object.prototype;
    };
    isEmptyObject = (payload) => isPlainObject(payload) && Object.keys(payload).length === 0;
    isArray = (payload) => Array.isArray(payload);
    isString = (payload) => typeof payload === "string";
    isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
    isBoolean = (payload) => typeof payload === "boolean";
    isRegExp = (payload) => payload instanceof RegExp;
    isMap = (payload) => payload instanceof Map;
    isSet = (payload) => payload instanceof Set;
    isSymbol = (payload) => getType(payload) === "Symbol";
    isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
    isError = (payload) => payload instanceof Error;
    isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
    isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
    isBigint = (payload) => typeof payload === "bigint";
    isInfinite = (payload) => payload === Infinity || payload === -Infinity;
    isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
    isURL = (payload) => payload instanceof URL;
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/pathstringifier.js
var escapeKey, stringifyPath, parsePath;
var init_pathstringifier = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/pathstringifier.js"() {
    escapeKey = (key) => key.replace(/\./g, "\\.");
    stringifyPath = (path4) => path4.map(String).map(escapeKey).join(".");
    parsePath = (string2) => {
      const result = [];
      let segment = "";
      for (let i2 = 0; i2 < string2.length; i2++) {
        let char = string2.charAt(i2);
        const isEscapedDot = char === "\\" && string2.charAt(i2 + 1) === ".";
        if (isEscapedDot) {
          segment += ".";
          i2++;
          continue;
        }
        const isEndOfSegment = char === ".";
        if (isEndOfSegment) {
          result.push(segment);
          segment = "";
          continue;
        }
        segment += char;
      }
      const lastSegment = segment;
      result.push(lastSegment);
      return result;
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/transformer.js
function simpleTransformation(isApplicable, annotation, transform, untransform) {
  return {
    isApplicable,
    annotation,
    transform,
    untransform
  };
}
function compositeTransformation(isApplicable, annotation, transform, untransform) {
  return {
    isApplicable,
    annotation,
    transform,
    untransform
  };
}
function isInstanceOfRegisteredClass(potentialClass, superJson) {
  if (potentialClass == null ? void 0 : potentialClass.constructor) {
    const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
    return isRegistered;
  }
  return false;
}
var simpleRules, symbolRule, constructorToName, typedArrayRule, classRule, customRule, compositeRules, transformValue, simpleRulesByAnnotation, untransformValue;
var init_transformer = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/transformer.js"() {
    init_is2();
    init_util();
    simpleRules = [
      simpleTransformation(isUndefined, "undefined", () => null, () => void 0),
      simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
        if (typeof BigInt !== "undefined") {
          return BigInt(v);
        }
        console.error("Please add a BigInt polyfill.");
        return v;
      }),
      simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
      simpleTransformation(isError, "Error", (v, superJson) => {
        const baseError = {
          name: v.name,
          message: v.message
        };
        superJson.allowedErrorProps.forEach((prop) => {
          baseError[prop] = v[prop];
        });
        return baseError;
      }, (v, superJson) => {
        const e2 = new Error(v.message);
        e2.name = v.name;
        e2.stack = v.stack;
        superJson.allowedErrorProps.forEach((prop) => {
          e2[prop] = v[prop];
        });
        return e2;
      }),
      simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
        const body = regex.slice(1, regex.lastIndexOf("/"));
        const flags = regex.slice(regex.lastIndexOf("/") + 1);
        return new RegExp(body, flags);
      }),
      simpleTransformation(
        isSet,
        "set",
        // (sets only exist in es6+)
        // eslint-disable-next-line es5/no-es6-methods
        (v) => [...v.values()],
        (v) => new Set(v)
      ),
      simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
      simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
        if (isNaNValue(v)) {
          return "NaN";
        }
        if (v > 0) {
          return "Infinity";
        } else {
          return "-Infinity";
        }
      }, Number),
      simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
        return "-0";
      }, Number),
      simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
    ];
    symbolRule = compositeTransformation((s2, superJson) => {
      if (isSymbol(s2)) {
        const isRegistered = !!superJson.symbolRegistry.getIdentifier(s2);
        return isRegistered;
      }
      return false;
    }, (s2, superJson) => {
      const identifier = superJson.symbolRegistry.getIdentifier(s2);
      return ["symbol", identifier];
    }, (v) => v.description, (_2, a, superJson) => {
      const value = superJson.symbolRegistry.getValue(a[1]);
      if (!value) {
        throw new Error("Trying to deserialize unknown symbol");
      }
      return value;
    });
    constructorToName = [
      Int8Array,
      Uint8Array,
      Int16Array,
      Uint16Array,
      Int32Array,
      Uint32Array,
      Float32Array,
      Float64Array,
      Uint8ClampedArray
    ].reduce((obj, ctor) => {
      obj[ctor.name] = ctor;
      return obj;
    }, {});
    typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a) => {
      const ctor = constructorToName[a[1]];
      if (!ctor) {
        throw new Error("Trying to deserialize unknown typed array");
      }
      return new ctor(v);
    });
    classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
      const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
      return ["class", identifier];
    }, (clazz, superJson) => {
      const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
      if (!allowedProps) {
        return { ...clazz };
      }
      const result = {};
      allowedProps.forEach((prop) => {
        result[prop] = clazz[prop];
      });
      return result;
    }, (v, a, superJson) => {
      const clazz = superJson.classRegistry.getValue(a[1]);
      if (!clazz) {
        throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");
      }
      return Object.assign(Object.create(clazz.prototype), v);
    });
    customRule = compositeTransformation((value, superJson) => {
      return !!superJson.customTransformerRegistry.findApplicable(value);
    }, (value, superJson) => {
      const transformer = superJson.customTransformerRegistry.findApplicable(value);
      return ["custom", transformer.name];
    }, (value, superJson) => {
      const transformer = superJson.customTransformerRegistry.findApplicable(value);
      return transformer.serialize(value);
    }, (v, a, superJson) => {
      const transformer = superJson.customTransformerRegistry.findByName(a[1]);
      if (!transformer) {
        throw new Error("Trying to deserialize unknown custom value");
      }
      return transformer.deserialize(v);
    });
    compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
    transformValue = (value, superJson) => {
      const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
      if (applicableCompositeRule) {
        return {
          value: applicableCompositeRule.transform(value, superJson),
          type: applicableCompositeRule.annotation(value, superJson)
        };
      }
      const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
      if (applicableSimpleRule) {
        return {
          value: applicableSimpleRule.transform(value, superJson),
          type: applicableSimpleRule.annotation
        };
      }
      return void 0;
    };
    simpleRulesByAnnotation = {};
    simpleRules.forEach((rule) => {
      simpleRulesByAnnotation[rule.annotation] = rule;
    });
    untransformValue = (json, type, superJson) => {
      if (isArray(type)) {
        switch (type[0]) {
          case "symbol":
            return symbolRule.untransform(json, type, superJson);
          case "class":
            return classRule.untransform(json, type, superJson);
          case "custom":
            return customRule.untransform(json, type, superJson);
          case "typed-array":
            return typedArrayRule.untransform(json, type, superJson);
          default:
            throw new Error("Unknown transformation: " + type);
        }
      } else {
        const transformation = simpleRulesByAnnotation[type];
        if (!transformation) {
          throw new Error("Unknown transformation: " + type);
        }
        return transformation.untransform(json, superJson);
      }
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/accessDeep.js
function validatePath(path4) {
  if (includes(path4, "__proto__")) {
    throw new Error("__proto__ is not allowed as a property");
  }
  if (includes(path4, "prototype")) {
    throw new Error("prototype is not allowed as a property");
  }
  if (includes(path4, "constructor")) {
    throw new Error("constructor is not allowed as a property");
  }
}
var getNthKey, getDeep, setDeep;
var init_accessDeep = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/accessDeep.js"() {
    init_is2();
    init_util();
    getNthKey = (value, n) => {
      const keys = value.keys();
      while (n > 0) {
        keys.next();
        n--;
      }
      return keys.next().value;
    };
    getDeep = (object, path4) => {
      validatePath(path4);
      for (let i2 = 0; i2 < path4.length; i2++) {
        const key = path4[i2];
        if (isSet(object)) {
          object = getNthKey(object, +key);
        } else if (isMap(object)) {
          const row = +key;
          const type = +path4[++i2] === 0 ? "key" : "value";
          const keyOfRow = getNthKey(object, row);
          switch (type) {
            case "key":
              object = keyOfRow;
              break;
            case "value":
              object = object.get(keyOfRow);
              break;
          }
        } else {
          object = object[key];
        }
      }
      return object;
    };
    setDeep = (object, path4, mapper) => {
      validatePath(path4);
      if (path4.length === 0) {
        return mapper(object);
      }
      let parent = object;
      for (let i2 = 0; i2 < path4.length - 1; i2++) {
        const key = path4[i2];
        if (isArray(parent)) {
          const index5 = +key;
          parent = parent[index5];
        } else if (isPlainObject(parent)) {
          parent = parent[key];
        } else if (isSet(parent)) {
          const row = +key;
          parent = getNthKey(parent, row);
        } else if (isMap(parent)) {
          const isEnd = i2 === path4.length - 2;
          if (isEnd) {
            break;
          }
          const row = +key;
          const type = +path4[++i2] === 0 ? "key" : "value";
          const keyOfRow = getNthKey(parent, row);
          switch (type) {
            case "key":
              parent = keyOfRow;
              break;
            case "value":
              parent = parent.get(keyOfRow);
              break;
          }
        }
      }
      const lastKey = path4[path4.length - 1];
      if (isArray(parent)) {
        parent[+lastKey] = mapper(parent[+lastKey]);
      } else if (isPlainObject(parent)) {
        parent[lastKey] = mapper(parent[lastKey]);
      }
      if (isSet(parent)) {
        const oldValue = getNthKey(parent, +lastKey);
        const newValue = mapper(oldValue);
        if (oldValue !== newValue) {
          parent.delete(oldValue);
          parent.add(newValue);
        }
      }
      if (isMap(parent)) {
        const row = +path4[path4.length - 2];
        const keyToRow = getNthKey(parent, row);
        const type = +lastKey === 0 ? "key" : "value";
        switch (type) {
          case "key": {
            const newKey = mapper(keyToRow);
            parent.set(newKey, parent.get(keyToRow));
            if (newKey !== keyToRow) {
              parent.delete(keyToRow);
            }
            break;
          }
          case "value": {
            parent.set(keyToRow, mapper(parent.get(keyToRow)));
            break;
          }
        }
      }
      return object;
    };
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/plainer.js
function traverse(tree, walker2, origin = []) {
  if (!tree) {
    return;
  }
  if (!isArray(tree)) {
    forEach(tree, (subtree, key) => traverse(subtree, walker2, [...origin, ...parsePath(key)]));
    return;
  }
  const [nodeValue, children] = tree;
  if (children) {
    forEach(children, (child, key) => {
      traverse(child, walker2, [...origin, ...parsePath(key)]);
    });
  }
  walker2(nodeValue, origin);
}
function applyValueAnnotations(plain, annotations, superJson) {
  traverse(annotations, (type, path4) => {
    plain = setDeep(plain, path4, (v) => untransformValue(v, type, superJson));
  });
  return plain;
}
function applyReferentialEqualityAnnotations(plain, annotations) {
  function apply(identicalPaths, path4) {
    const object = getDeep(plain, parsePath(path4));
    identicalPaths.map(parsePath).forEach((identicalObjectPath) => {
      plain = setDeep(plain, identicalObjectPath, () => object);
    });
  }
  if (isArray(annotations)) {
    const [root, other] = annotations;
    root.forEach((identicalPath) => {
      plain = setDeep(plain, parsePath(identicalPath), () => plain);
    });
    if (other) {
      forEach(other, apply);
    }
  } else {
    forEach(annotations, apply);
  }
  return plain;
}
function addIdentity(object, path4, identities) {
  const existingSet = identities.get(object);
  if (existingSet) {
    existingSet.push(path4);
  } else {
    identities.set(object, [path4]);
  }
}
function generateReferentialEqualityAnnotations(identitites, dedupe) {
  const result = {};
  let rootEqualityPaths = void 0;
  identitites.forEach((paths) => {
    if (paths.length <= 1) {
      return;
    }
    if (!dedupe) {
      paths = paths.map((path4) => path4.map(String)).sort((a, b) => a.length - b.length);
    }
    const [representativePath, ...identicalPaths] = paths;
    if (representativePath.length === 0) {
      rootEqualityPaths = identicalPaths.map(stringifyPath);
    } else {
      result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
    }
  });
  if (rootEqualityPaths) {
    if (isEmptyObject(result)) {
      return [rootEqualityPaths];
    } else {
      return [rootEqualityPaths, result];
    }
  } else {
    return isEmptyObject(result) ? void 0 : result;
  }
}
var isDeep, walker;
var init_plainer = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/plainer.js"() {
    init_is2();
    init_pathstringifier();
    init_transformer();
    init_util();
    init_pathstringifier();
    init_accessDeep();
    isDeep = (object, superJson) => isPlainObject(object) || isArray(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
    walker = (object, identities, superJson, dedupe, path4 = [], objectsInThisPath = [], seenObjects = /* @__PURE__ */ new Map()) => {
      const primitive = isPrimitive(object);
      if (!primitive) {
        addIdentity(object, path4, identities);
        const seen = seenObjects.get(object);
        if (seen) {
          return dedupe ? {
            transformedValue: null
          } : seen;
        }
      }
      if (!isDeep(object, superJson)) {
        const transformed2 = transformValue(object, superJson);
        const result2 = transformed2 ? {
          transformedValue: transformed2.value,
          annotations: [transformed2.type]
        } : {
          transformedValue: object
        };
        if (!primitive) {
          seenObjects.set(object, result2);
        }
        return result2;
      }
      if (includes(objectsInThisPath, object)) {
        return {
          transformedValue: null
        };
      }
      const transformationResult = transformValue(object, superJson);
      const transformed = (transformationResult == null ? void 0 : transformationResult.value) ?? object;
      const transformedValue = isArray(transformed) ? [] : {};
      const innerAnnotations = {};
      forEach(transformed, (value, index5) => {
        if (index5 === "__proto__" || index5 === "constructor" || index5 === "prototype") {
          throw new Error(`Detected property ${index5}. This is a prototype pollution risk, please remove it from your object.`);
        }
        const recursiveResult = walker(value, identities, superJson, dedupe, [...path4, index5], [...objectsInThisPath, object], seenObjects);
        transformedValue[index5] = recursiveResult.transformedValue;
        if (isArray(recursiveResult.annotations)) {
          innerAnnotations[index5] = recursiveResult.annotations;
        } else if (isPlainObject(recursiveResult.annotations)) {
          forEach(recursiveResult.annotations, (tree, key) => {
            innerAnnotations[escapeKey(index5) + "." + key] = tree;
          });
        }
      });
      const result = isEmptyObject(innerAnnotations) ? {
        transformedValue,
        annotations: !!transformationResult ? [transformationResult.type] : void 0
      } : {
        transformedValue,
        annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
      };
      if (!primitive) {
        seenObjects.set(object, result);
      }
      return result;
    };
  }
});

// ../node_modules/.pnpm/is-what@4.1.16/node_modules/is-what/dist/index.js
function getType2(payload) {
  return Object.prototype.toString.call(payload).slice(8, -1);
}
function isArray2(payload) {
  return getType2(payload) === "Array";
}
function isPlainObject2(payload) {
  if (getType2(payload) !== "Object")
    return false;
  const prototype = Object.getPrototypeOf(payload);
  return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
}
function isNull2(payload) {
  return getType2(payload) === "Null";
}
function isOneOf(a, b, c, d, e2) {
  return (value) => a(value) || b(value) || !!c && c(value) || !!d && d(value) || !!e2 && e2(value);
}
function isUndefined2(payload) {
  return getType2(payload) === "Undefined";
}
var isNullOrUndefined;
var init_dist4 = __esm({
  "../node_modules/.pnpm/is-what@4.1.16/node_modules/is-what/dist/index.js"() {
    isNullOrUndefined = isOneOf(isNull2, isUndefined2);
  }
});

// ../node_modules/.pnpm/copy-anything@3.0.5/node_modules/copy-anything/dist/index.js
function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
  if (propType === "enumerable")
    carry[key] = newVal;
  if (includeNonenumerable && propType === "nonenumerable") {
    Object.defineProperty(carry, key, {
      value: newVal,
      enumerable: false,
      writable: true,
      configurable: true
    });
  }
}
function copy2(target, options = {}) {
  if (isArray2(target)) {
    return target.map((item) => copy2(item, options));
  }
  if (!isPlainObject2(target)) {
    return target;
  }
  const props = Object.getOwnPropertyNames(target);
  const symbols = Object.getOwnPropertySymbols(target);
  return [...props, ...symbols].reduce((carry, key) => {
    if (isArray2(options.props) && !options.props.includes(key)) {
      return carry;
    }
    const val2 = target[key];
    const newVal = copy2(val2, options);
    assignProp(carry, key, newVal, target, options.nonenumerable);
    return carry;
  }, {});
}
var init_dist5 = __esm({
  "../node_modules/.pnpm/copy-anything@3.0.5/node_modules/copy-anything/dist/index.js"() {
    init_dist4();
  }
});

// ../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/index.js
var SuperJSON, serialize2, deserialize, stringify2, parse4, registerClass, registerCustom, registerSymbol, allowErrorProps;
var init_dist6 = __esm({
  "../node_modules/.pnpm/superjson@2.2.1/node_modules/superjson/dist/index.js"() {
    init_class_registry();
    init_registry();
    init_custom_transformer_registry();
    init_plainer();
    init_dist5();
    SuperJSON = class {
      /**
       * @param dedupeReferentialEqualities  If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.
       */
      constructor({ dedupe = false } = {}) {
        this.classRegistry = new ClassRegistry();
        this.symbolRegistry = new Registry((s2) => s2.description ?? "");
        this.customTransformerRegistry = new CustomTransformerRegistry();
        this.allowedErrorProps = [];
        this.dedupe = dedupe;
      }
      serialize(object) {
        const identities = /* @__PURE__ */ new Map();
        const output = walker(object, identities, this, this.dedupe);
        const res = {
          json: output.transformedValue
        };
        if (output.annotations) {
          res.meta = {
            ...res.meta,
            values: output.annotations
          };
        }
        const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
        if (equalityAnnotations) {
          res.meta = {
            ...res.meta,
            referentialEqualities: equalityAnnotations
          };
        }
        return res;
      }
      deserialize(payload) {
        const { json, meta } = payload;
        let result = copy2(json);
        if (meta == null ? void 0 : meta.values) {
          result = applyValueAnnotations(result, meta.values, this);
        }
        if (meta == null ? void 0 : meta.referentialEqualities) {
          result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
        }
        return result;
      }
      stringify(object) {
        return JSON.stringify(this.serialize(object));
      }
      parse(string2) {
        return this.deserialize(JSON.parse(string2));
      }
      registerClass(v, options) {
        this.classRegistry.register(v, options);
      }
      registerSymbol(v, identifier) {
        this.symbolRegistry.register(v, identifier);
      }
      registerCustom(transformer, name) {
        this.customTransformerRegistry.register({
          name,
          ...transformer
        });
      }
      allowErrorProps(...props) {
        this.allowedErrorProps.push(...props);
      }
    };
    SuperJSON.defaultInstance = new SuperJSON();
    SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
    SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
    SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
    SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
    SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
    SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
    SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
    SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
    serialize2 = SuperJSON.serialize;
    deserialize = SuperJSON.deserialize;
    stringify2 = SuperJSON.stringify;
    parse4 = SuperJSON.parse;
    registerClass = SuperJSON.registerClass;
    registerCustom = SuperJSON.registerCustom;
    registerSymbol = SuperJSON.registerSymbol;
    allowErrorProps = SuperJSON.allowErrorProps;
  }
});

// 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_crypto9, import_drizzle_orm10, import_mysql_core3, import_pg_core3, import_singlestore_core3, import_sqlite_core3, import_fs12, import_node_https2, preparePgSchema, prepareMySqlSchema, prepareSQLiteSchema, prepareSingleStoreSchema, getCustomDefaults, drizzleForPostgres, drizzleForMySQL, drizzleForSQLite, drizzleForLibSQL, drizzleForSingleStore, extractRelations, init, proxySchema, defaultsSchema, schema5, jsonStringify, prepareServer;
var init_studio2 = __esm({
  "src/serializer/studio.ts"() {
    "use strict";
    init_dist2();
    init_esm();
    import_crypto9 = require("crypto");
    import_drizzle_orm10 = require("drizzle-orm");
    import_mysql_core3 = require("drizzle-orm/mysql-core");
    import_pg_core3 = require("drizzle-orm/pg-core");
    import_singlestore_core3 = require("drizzle-orm/singlestore-core");
    import_sqlite_core3 = require("drizzle-orm/sqlite-core");
    import_fs12 = __toESM(require("fs"));
    init_dist3();
    init_compress();
    init_cors();
    import_node_https2 = require("node:https");
    init_global();
    init_dist6();
    init_lib();
    init_utils3();
    init_serializer();
    preparePgSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const pgSchema2 = {};
      const relations4 = {};
      const files = imports.map((it, index5) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index5}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k, t2]) => {
          if ((0, import_drizzle_orm10.is)(t2, import_pg_core3.PgTable)) {
            const schema6 = (0, import_pg_core3.getTableConfig)(t2).schema || "public";
            pgSchema2[schema6] = pgSchema2[schema6] || {};
            pgSchema2[schema6][k] = t2;
          }
          if ((0, import_drizzle_orm10.is)(t2, import_drizzle_orm10.Relations)) {
            relations4[k] = t2;
          }
        });
      }
      unregister();
      return { schema: pgSchema2, relations: relations4, files };
    };
    prepareMySqlSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const mysqlSchema3 = {
        public: {}
      };
      const relations4 = {};
      const files = imports.map((it, index5) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index5}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k, t2]) => {
          if ((0, import_drizzle_orm10.is)(t2, import_mysql_core3.MySqlTable)) {
            const schema6 = (0, import_mysql_core3.getTableConfig)(t2).schema || "public";
            mysqlSchema3[schema6][k] = t2;
          }
          if ((0, import_drizzle_orm10.is)(t2, import_drizzle_orm10.Relations)) {
            relations4[k] = t2;
          }
        });
      }
      unregister();
      return { schema: mysqlSchema3, relations: relations4, files };
    };
    prepareSQLiteSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const sqliteSchema2 = {
        public: {}
      };
      const relations4 = {};
      const files = imports.map((it, index5) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index5}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k, t2]) => {
          if ((0, import_drizzle_orm10.is)(t2, import_sqlite_core3.SQLiteTable)) {
            const schema6 = "public";
            sqliteSchema2[schema6][k] = t2;
          }
          if ((0, import_drizzle_orm10.is)(t2, import_drizzle_orm10.Relations)) {
            relations4[k] = t2;
          }
        });
      }
      unregister();
      return { schema: sqliteSchema2, relations: relations4, files };
    };
    prepareSingleStoreSchema = async (path4) => {
      const imports = prepareFilenames(path4);
      const singlestoreSchema2 = {
        public: {}
      };
      const relations4 = {};
      const files = imports.map((it, index5) => ({
        // get the file name from the path
        name: it.split("/").pop() || `schema${index5}.ts`,
        content: import_fs12.default.readFileSync(it, "utf-8")
      }));
      const { unregister } = await safeRegister();
      for (let i2 = 0; i2 < imports.length; i2++) {
        const it = imports[i2];
        const i0 = require(`${it}`);
        const i0values = Object.entries(i0);
        i0values.forEach(([k, t2]) => {
          if ((0, import_drizzle_orm10.is)(t2, import_singlestore_core3.SingleStoreTable)) {
            const schema6 = (0, import_singlestore_core3.getTableConfig)(t2).schema || "public";
            singlestoreSchema2[schema6][k] = t2;
          }
          if ((0, import_drizzle_orm10.is)(t2, import_drizzle_orm10.Relations)) {
            relations4[k] = t2;
          }
        });
      }
      unregister();
      return { schema: singlestoreSchema2, relations: relations4, files };
    };
    getCustomDefaults = (schema6) => {
      const customDefaults = [];
      Object.entries(schema6).map(([schema7, tables]) => {
        Object.entries(tables).map(([, table5]) => {
          let tableConfig;
          if ((0, import_drizzle_orm10.is)(table5, import_pg_core3.PgTable)) {
            tableConfig = (0, import_pg_core3.getTableConfig)(table5);
          } else if ((0, import_drizzle_orm10.is)(table5, import_mysql_core3.MySqlTable)) {
            tableConfig = (0, import_mysql_core3.getTableConfig)(table5);
          } else if ((0, import_drizzle_orm10.is)(table5, import_sqlite_core3.SQLiteTable)) {
            tableConfig = (0, import_sqlite_core3.getTableConfig)(table5);
          } else {
            tableConfig = (0, import_singlestore_core3.getTableConfig)(table5);
          }
          tableConfig.columns.map((column9) => {
            if (column9.defaultFn) {
              customDefaults.push({
                schema: schema7,
                table: tableConfig.name,
                column: column9.name,
                func: column9.defaultFn
              });
            }
          });
        });
      });
      return customDefaults;
    };
    drizzleForPostgres = async (credentials2, pgSchema2, relations4, schemaFiles) => {
      const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const db = await preparePostgresDB2(credentials2);
      const customDefaults = getCustomDefaults(pgSchema2);
      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 = 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_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "postgresql",
        driver: "driver" in credentials2 ? credentials2.driver : void 0,
        proxy: db.proxy,
        customDefaults,
        schema: pgSchema2,
        relations: relations4,
        schemaFiles
      };
    };
    drizzleForMySQL = async (credentials2, mysqlSchema3, relations4, schemaFiles) => {
      const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { proxy } = await connectToMySQL2(credentials2);
      const customDefaults = getCustomDefaults(mysqlSchema3);
      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_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "mysql",
        proxy,
        customDefaults,
        schema: mysqlSchema3,
        relations: relations4,
        schemaFiles
      };
    };
    drizzleForSQLite = async (credentials2, sqliteSchema2, relations4, schemaFiles) => {
      const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const sqliteDB = await connectToSQLite2(credentials2);
      const customDefaults = getCustomDefaults(sqliteSchema2);
      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_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "sqlite",
        driver: "driver" in credentials2 ? credentials2.driver : void 0,
        proxy: sqliteDB.proxy,
        customDefaults,
        schema: sqliteSchema2,
        relations: relations4,
        schemaFiles
      };
    };
    drizzleForLibSQL = async (credentials2, sqliteSchema2, relations4, schemaFiles) => {
      const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const sqliteDB = await connectToLibSQL2(credentials2);
      const customDefaults = getCustomDefaults(sqliteSchema2);
      let dbUrl = `turso://${credentials2.url}/${credentials2.authToken}`;
      const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "sqlite",
        driver: void 0,
        proxy: sqliteDB.proxy,
        customDefaults,
        schema: sqliteSchema2,
        relations: relations4,
        schemaFiles
      };
    };
    drizzleForSingleStore = async (credentials2, singlestoreSchema2, relations4, schemaFiles) => {
      const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
      const { proxy } = await connectToSingleStore2(credentials2);
      const customDefaults = getCustomDefaults(singlestoreSchema2);
      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_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
      return {
        dbHash,
        dialect: "singlestore",
        proxy,
        customDefaults,
        schema: singlestoreSchema2,
        relations: relations4,
        schemaFiles
      };
    };
    extractRelations = (tablesConfig) => {
      const relations4 = Object.values(tablesConfig.tables).map(
        (it) => Object.entries(it.relations).map(([name, relation]) => {
          const normalized = (0, import_drizzle_orm10.normalizeRelation)(
            tablesConfig.tables,
            tablesConfig.tableNamesMap,
            relation
          );
          const rel = relation;
          const refTableName = rel.referencedTableName;
          const refTable = rel.referencedTable;
          const fields = normalized.fields.map((it2) => it2.name).flat();
          const refColumns = normalized.references.map((it2) => it2.name).flat();
          let refSchema;
          if ((0, import_drizzle_orm10.is)(refTable, import_pg_core3.PgTable)) {
            refSchema = (0, import_pg_core3.getTableConfig)(refTable).schema;
          } else if ((0, import_drizzle_orm10.is)(refTable, import_mysql_core3.MySqlTable)) {
            refSchema = (0, import_mysql_core3.getTableConfig)(refTable).schema;
          } else if ((0, import_drizzle_orm10.is)(refTable, import_sqlite_core3.SQLiteTable)) {
            refSchema = void 0;
          } else if ((0, import_drizzle_orm10.is)(refTable, import_singlestore_core3.SingleStoreTable)) {
            refSchema = (0, import_singlestore_core3.getTableConfig)(refTable).schema;
          } else {
            throw new Error("unsupported dialect");
          }
          let type;
          if ((0, import_drizzle_orm10.is)(rel, import_drizzle_orm10.One)) {
            type = "one";
          } else if ((0, import_drizzle_orm10.is)(rel, import_drizzle_orm10.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
          };
        })
      ).flat();
      return relations4;
    };
    init = z.object({
      type: z.literal("init")
    });
    proxySchema = z.object({
      type: z.literal("proxy"),
      data: z.object({
        sql: z.string(),
        params: z.array(z.any()).optional(),
        typings: z.string().array().optional(),
        mode: z.enum(["array", "object"]).default("object"),
        method: z.union([
          z.literal("values"),
          z.literal("get"),
          z.literal("all"),
          z.literal("run"),
          z.literal("execute")
        ])
      })
    });
    defaultsSchema = z.object({
      type: z.literal("defaults"),
      data: z.array(
        z.object({
          schema: z.string(),
          table: z.string(),
          column: z.string()
        })
      ).min(1)
    });
    schema5 = z.union([init, proxySchema, defaultsSchema]);
    SuperJSON.registerCustom(
      {
        isApplicable: (v) => v instanceof Buffer,
        serialize: (v) => [...v],
        deserialize: (v) => Buffer.from(v)
      },
      "buffer"
    );
    jsonStringify = (data) => {
      return JSON.stringify(data, (_key, value) => {
        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,
      proxy,
      customDefaults,
      schema: drizzleSchema,
      relations: relations4,
      dbHash,
      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, table5]) => {
                return [`__${schemaName}__.${tableName}`, table5];
              }
            );
            return mappedTableEntries;
          }).flat()
        ),
        ...relations4
      };
      const relationsConfig = (0, import_drizzle_orm10.extractTablesRelationalConfig)(
        relationalSchema,
        import_drizzle_orm10.createTableRelationsHelpers
      );
      app.post("/", zValidator("json", schema5), async (c) => {
        const body = c.req.valid("json");
        const { type } = body;
        if (type === "init") {
          const preparedDefaults = customDefaults.map((d) => ({
            schema: d.schema,
            table: d.table,
            column: d.column
          }));
          return c.json({
            version: "6",
            dialect: dialect6,
            driver: driver2,
            schemaFiles,
            customDefaults: preparedDefaults,
            relations: extractRelations(relationsConfig),
            dbHash
          });
        }
        if (type === "proxy") {
          const result = await proxy({
            ...body.data,
            params: body.data.params || []
          });
          return c.json(JSON.parse(jsonStringify(result)));
        }
        if (type === "defaults") {
          const columns = body.data;
          const result = columns.map((column9) => {
            const found = customDefaults.find((d) => {
              return d.schema === column9.schema && d.table === column9.table && d.column === column9.column;
            });
            if (!found) {
              throw new Error(
                `Custom default not found for ${column9.schema}.${column9.table}.${column9.column}`
              );
            }
            const value = found.func();
            return {
              ...column9,
              value
            };
          });
          return c.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}`)
          );
        }
      };
    };
  }
});

// ../node_modules/.pnpm/@drizzle-team+brocli@0.10.2/node_modules/@drizzle-team/brocli/index.js
var __create2 = Object.create;
var __defProp2 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __getProtoOf2 = Object.getPrototypeOf;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __commonJS2 = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps2 = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames2(from))
      if (!__hasOwnProp2.call(to, key) && key !== except)
        __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
  // 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 ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var require_clone = __commonJS2({
  "node_modules/.pnpm/clone@2.1.2/node_modules/clone/clone.js"(exports2, module2) {
    "use strict";
    var clone2 = function() {
      "use strict";
      function _instanceof(obj, type) {
        return type != null && obj instanceof type;
      }
      var nativeMap;
      try {
        nativeMap = Map;
      } catch (_2) {
        nativeMap = function() {
        };
      }
      var nativeSet;
      try {
        nativeSet = Set;
      } catch (_2) {
        nativeSet = function() {
        };
      }
      var nativePromise;
      try {
        nativePromise = Promise;
      } catch (_2) {
        nativePromise = function() {
        };
      }
      function clone3(parent, circular, depth, prototype, includeNonEnumerable) {
        if (typeof circular === "object") {
          depth = circular.depth;
          prototype = circular.prototype;
          includeNonEnumerable = circular.includeNonEnumerable;
          circular = circular.circular;
        }
        var allParents = [];
        var allChildren = [];
        var useBuffer = typeof Buffer != "undefined";
        if (typeof circular == "undefined")
          circular = true;
        if (typeof depth == "undefined")
          depth = Infinity;
        function _clone(parent2, depth2) {
          if (parent2 === null)
            return null;
          if (depth2 === 0)
            return parent2;
          var child;
          var proto2;
          if (typeof parent2 != "object") {
            return parent2;
          }
          if (_instanceof(parent2, nativeMap)) {
            child = new nativeMap();
          } else if (_instanceof(parent2, nativeSet)) {
            child = new nativeSet();
          } else if (_instanceof(parent2, nativePromise)) {
            child = new nativePromise(function(resolve2, reject) {
              parent2.then(function(value) {
                resolve2(_clone(value, depth2 - 1));
              }, function(err2) {
                reject(_clone(err2, depth2 - 1));
              });
            });
          } else if (clone3.__isArray(parent2)) {
            child = [];
          } else if (clone3.__isRegExp(parent2)) {
            child = new RegExp(parent2.source, __getRegExpFlags(parent2));
            if (parent2.lastIndex)
              child.lastIndex = parent2.lastIndex;
          } else if (clone3.__isDate(parent2)) {
            child = new Date(parent2.getTime());
          } else if (useBuffer && Buffer.isBuffer(parent2)) {
            if (Buffer.allocUnsafe) {
              child = Buffer.allocUnsafe(parent2.length);
            } else {
              child = new Buffer(parent2.length);
            }
            parent2.copy(child);
            return child;
          } else if (_instanceof(parent2, Error)) {
            child = Object.create(parent2);
          } else {
            if (typeof prototype == "undefined") {
              proto2 = Object.getPrototypeOf(parent2);
              child = Object.create(proto2);
            } else {
              child = Object.create(prototype);
              proto2 = prototype;
            }
          }
          if (circular) {
            var index5 = allParents.indexOf(parent2);
            if (index5 != -1) {
              return allChildren[index5];
            }
            allParents.push(parent2);
            allChildren.push(child);
          }
          if (_instanceof(parent2, nativeMap)) {
            parent2.forEach(function(value, key) {
              var keyChild = _clone(key, depth2 - 1);
              var valueChild = _clone(value, depth2 - 1);
              child.set(keyChild, valueChild);
            });
          }
          if (_instanceof(parent2, nativeSet)) {
            parent2.forEach(function(value) {
              var entryChild = _clone(value, depth2 - 1);
              child.add(entryChild);
            });
          }
          for (var i2 in parent2) {
            var attrs;
            if (proto2) {
              attrs = Object.getOwnPropertyDescriptor(proto2, i2);
            }
            if (attrs && attrs.set == null) {
              continue;
            }
            child[i2] = _clone(parent2[i2], depth2 - 1);
          }
          if (Object.getOwnPropertySymbols) {
            var symbols = Object.getOwnPropertySymbols(parent2);
            for (var i2 = 0; i2 < symbols.length; i2++) {
              var symbol = symbols[i2];
              var descriptor = Object.getOwnPropertyDescriptor(parent2, symbol);
              if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
                continue;
              }
              child[symbol] = _clone(parent2[symbol], depth2 - 1);
              if (!descriptor.enumerable) {
                Object.defineProperty(child, symbol, {
                  enumerable: false
                });
              }
            }
          }
          if (includeNonEnumerable) {
            var allPropertyNames = Object.getOwnPropertyNames(parent2);
            for (var i2 = 0; i2 < allPropertyNames.length; i2++) {
              var propertyName = allPropertyNames[i2];
              var descriptor = Object.getOwnPropertyDescriptor(parent2, propertyName);
              if (descriptor && descriptor.enumerable) {
                continue;
              }
              child[propertyName] = _clone(parent2[propertyName], depth2 - 1);
              Object.defineProperty(child, propertyName, {
                enumerable: false
              });
            }
          }
          return child;
        }
        return _clone(parent, depth);
      }
      clone3.clonePrototype = function clonePrototype(parent) {
        if (parent === null)
          return null;
        var c = function() {
        };
        c.prototype = parent;
        return new c();
      };
      function __objToStr(o) {
        return Object.prototype.toString.call(o);
      }
      clone3.__objToStr = __objToStr;
      function __isDate(o) {
        return typeof o === "object" && __objToStr(o) === "[object Date]";
      }
      clone3.__isDate = __isDate;
      function __isArray(o) {
        return typeof o === "object" && __objToStr(o) === "[object Array]";
      }
      clone3.__isArray = __isArray;
      function __isRegExp(o) {
        return typeof o === "object" && __objToStr(o) === "[object RegExp]";
      }
      clone3.__isRegExp = __isRegExp;
      function __getRegExpFlags(re) {
        var flags = "";
        if (re.global)
          flags += "g";
        if (re.ignoreCase)
          flags += "i";
        if (re.multiline)
          flags += "m";
        return flags;
      }
      clone3.__getRegExpFlags = __getRegExpFlags;
      return clone3;
    }();
    if (typeof module2 === "object" && module2.exports) {
      module2.exports = clone2;
    }
  }
});
var require_quote = __commonJS2({
  "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/quote.js"(exports2, module2) {
    "use strict";
    module2.exports = function quote(xs) {
      return xs.map(function(s2) {
        if (s2 && typeof s2 === "object") {
          return s2.op.replace(/(.)/g, "\\$1");
        }
        if (/["\s]/.test(s2) && !/'/.test(s2)) {
          return "'" + s2.replace(/(['\\])/g, "\\$1") + "'";
        }
        if (/["'\s]/.test(s2)) {
          return '"' + s2.replace(/(["\\$`!])/g, "\\$1") + '"';
        }
        return String(s2).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
      }).join(" ");
    };
  }
});
var require_parse = __commonJS2({
  "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/parse.js"(exports2, module2) {
    "use strict";
    var CONTROL = "(?:" + [
      "\\|\\|",
      "\\&\\&",
      ";;",
      "\\|\\&",
      "\\<\\(",
      "\\<\\<\\<",
      ">>",
      ">\\&",
      "<\\&",
      "[&;()|<>]"
    ].join("|") + ")";
    var controlRE = new RegExp("^" + CONTROL + "$");
    var META = "|&;()<> \\t";
    var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
    var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
    var hash = /^#$/;
    var SQ = "'";
    var DQ = '"';
    var DS = "$";
    var TOKEN = "";
    var mult = 4294967296;
    for (i2 = 0; i2 < 4; i2++) {
      TOKEN += (mult * Math.random()).toString(16);
    }
    var i2;
    var startsWithToken = new RegExp("^" + TOKEN);
    function matchAll(s2, r2) {
      var origIndex = r2.lastIndex;
      var matches = [];
      var matchObj;
      while (matchObj = r2.exec(s2)) {
        matches.push(matchObj);
        if (r2.lastIndex === matchObj.index) {
          r2.lastIndex += 1;
        }
      }
      r2.lastIndex = origIndex;
      return matches;
    }
    function getVar(env3, pre, key) {
      var r2 = typeof env3 === "function" ? env3(key) : env3[key];
      if (typeof r2 === "undefined" && key != "") {
        r2 = "";
      } else if (typeof r2 === "undefined") {
        r2 = "$";
      }
      if (typeof r2 === "object") {
        return pre + TOKEN + JSON.stringify(r2) + TOKEN;
      }
      return pre + r2;
    }
    function parseInternal(string2, env3, opts) {
      if (!opts) {
        opts = {};
      }
      var BS = opts.escape || "\\";
      var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
      var chunker = new RegExp([
        "(" + CONTROL + ")",
        // control chars
        "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
      ].join("|"), "g");
      var matches = matchAll(string2, chunker);
      if (matches.length === 0) {
        return [];
      }
      if (!env3) {
        env3 = {};
      }
      var commented = false;
      return matches.map(function(match2) {
        var s2 = match2[0];
        if (!s2 || commented) {
          return void 0;
        }
        if (controlRE.test(s2)) {
          return { op: s2 };
        }
        var quote = false;
        var esc = false;
        var out = "";
        var isGlob = false;
        var i22;
        function parseEnvVar() {
          i22 += 1;
          var varend;
          var varname;
          var char = s2.charAt(i22);
          if (char === "{") {
            i22 += 1;
            if (s2.charAt(i22) === "}") {
              throw new Error("Bad substitution: " + s2.slice(i22 - 2, i22 + 1));
            }
            varend = s2.indexOf("}", i22);
            if (varend < 0) {
              throw new Error("Bad substitution: " + s2.slice(i22));
            }
            varname = s2.slice(i22, varend);
            i22 = varend;
          } else if (/[*@#?$!_-]/.test(char)) {
            varname = char;
            i22 += 1;
          } else {
            var slicedFromI = s2.slice(i22);
            varend = slicedFromI.match(/[^\w\d_]/);
            if (!varend) {
              varname = slicedFromI;
              i22 = s2.length;
            } else {
              varname = slicedFromI.slice(0, varend.index);
              i22 += varend.index - 1;
            }
          }
          return getVar(env3, "", varname);
        }
        for (i22 = 0; i22 < s2.length; i22++) {
          var c = s2.charAt(i22);
          isGlob = isGlob || !quote && (c === "*" || c === "?");
          if (esc) {
            out += c;
            esc = false;
          } else if (quote) {
            if (c === quote) {
              quote = false;
            } else if (quote == SQ) {
              out += c;
            } else {
              if (c === BS) {
                i22 += 1;
                c = s2.charAt(i22);
                if (c === DQ || c === BS || c === DS) {
                  out += c;
                } else {
                  out += BS + c;
                }
              } else if (c === DS) {
                out += parseEnvVar();
              } else {
                out += c;
              }
            }
          } else if (c === DQ || c === SQ) {
            quote = c;
          } else if (controlRE.test(c)) {
            return { op: s2 };
          } else if (hash.test(c)) {
            commented = true;
            var commentObj = { comment: string2.slice(match2.index + i22 + 1) };
            if (out.length) {
              return [out, commentObj];
            }
            return [commentObj];
          } else if (c === BS) {
            esc = true;
          } else if (c === DS) {
            out += parseEnvVar();
          } else {
            out += c;
          }
        }
        if (isGlob) {
          return { op: "glob", pattern: out };
        }
        return out;
      }).reduce(function(prev, arg) {
        return typeof arg === "undefined" ? prev : prev.concat(arg);
      }, []);
    }
    module2.exports = function parse5(s2, env3, opts) {
      var mapped = parseInternal(s2, env3, opts);
      if (typeof env3 !== "function") {
        return mapped;
      }
      return mapped.reduce(function(acc, s22) {
        if (typeof s22 === "object") {
          return acc.concat(s22);
        }
        var xs = s22.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
        if (xs.length === 1) {
          return acc.concat(xs[0]);
        }
        return acc.concat(xs.filter(Boolean).map(function(x2) {
          if (startsWithToken.test(x2)) {
            return JSON.parse(x2.split(TOKEN)[1]);
          }
          return x2;
        }));
      }, []);
    };
  }
});
var require_shell_quote = __commonJS2({
  "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/index.js"(exports2) {
    "use strict";
    exports2.quote = require_quote();
    exports2.parse = require_parse();
  }
});
var BroCliError = class extends Error {
  constructor(message, event) {
    const errPrefix = "BroCli error: ";
    super(message === void 0 ? message : `${errPrefix}${message}`);
    this.event = event;
  }
};
var import_clone = __toESM2(require_clone(), 1);
var getOptionTypeText = (option) => {
  let result = "";
  switch (option.type) {
    case "boolean":
      result = "";
      break;
    case "number": {
      if ((option.minVal ?? option.maxVal) !== void 0) {
        let text = "";
        if (option.isInt)
          text = text + `integer `;
        if (option.minVal !== void 0)
          text = text + `[${option.minVal};`;
        else
          text = text + `(\u221E;`;
        if (option.maxVal !== void 0)
          text = text + `${option.maxVal}]`;
        else
          text = text + `\u221E)`;
        result = text;
        break;
      }
      if (option.isInt) {
        result = "integer";
        break;
      }
      result = "number";
      break;
    }
    case "string": {
      if (option.enumVals) {
        result = "[ " + option.enumVals.join(" | ") + " ]";
        break;
      }
      result = "string";
      break;
    }
    case "positional": {
      result = `${option.isRequired ? "<" : "["}${option.enumVals ? option.enumVals.join("|") : option.name}${option.isRequired ? ">" : "]"}`;
      break;
    }
  }
  if (option.isRequired && option.type !== "positional")
    result = "!" + result.length ? " " : "" + result;
  return result;
};
var defaultEventHandler = async (event) => {
  var _a;
  switch (event.type) {
    case "command_help": {
      const command3 = event.command;
      const commandName = getCommandNameWithParents(command3);
      const cliName = event.name;
      const desc = command3.desc ?? command3.shortDesc;
      const subs = (_a = command3.subcommands) == null ? void 0 : _a.filter((s2) => !s2.hidden);
      const subcommands = subs && subs.length ? subs : void 0;
      if (desc !== void 0) {
        console.log(`
${desc}`);
      }
      const opts = Object.values(command3.options ?? {}).filter(
        (opt) => !opt.config.isHidden
      );
      const positionals = opts.filter((opt) => opt.config.type === "positional");
      const options = opts.filter((opt) => opt.config.type !== "positional");
      console.log("\nUsage:");
      if (command3.handler) {
        console.log(
          `  ${cliName ? cliName + " " : ""}${commandName}${positionals.length ? " " + positionals.map(({ config: p }) => getOptionTypeText(p)).join(" ") : ""} [flags]`
        );
      } else
        console.log(`  ${cliName ? cliName + " " : ""}${commandName} [command]`);
      if (command3.aliases) {
        console.log(`
Aliases:`);
        console.log(`  ${[command3.name, ...command3.aliases].join(", ")}`);
      }
      if (subcommands) {
        console.log("\nAvailable Commands:");
        const padding = 3;
        const maxLength = subcommands.reduce((p, e2) => e2.name.length > p ? e2.name.length : p, 0);
        const paddedLength = maxLength + padding;
        const preDescPad = 2 + paddedLength;
        const data = subcommands.map(
          (s2) => `  ${s2.name.padEnd(paddedLength)}${(() => {
            const description = s2.shortDesc ?? s2.desc;
            if (!(description == null ? void 0 : description.length))
              return "";
            const split = description.split("\n");
            const first = split.shift();
            const final = [first, ...split.map((s22) => "".padEnd(preDescPad) + s22)].join("\n");
            return final;
          })()}`
        ).join("\n");
        console.log(data);
      }
      if (options.length) {
        const aliasLength = options.reduce((p, e2) => {
          const currentLength = e2.config.aliases.reduce((pa, a) => pa + a.length, 0) + (e2.config.aliases.length - 1) * 2 + 1;
          return currentLength > p ? currentLength : p;
        }, 0);
        const paddedAliasLength = aliasLength > 0 ? aliasLength + 1 : 0;
        const nameLength = options.reduce((p, e2) => {
          const typeLen = getOptionTypeText(e2.config).length;
          const length = typeLen > 0 ? e2.config.name.length + 1 + typeLen : e2.config.name.length;
          return length > p ? length : p;
        }, 0) + 3;
        const preDescPad = paddedAliasLength + nameLength + 2;
        const data = options.map(
          ({ config: opt }) => `  ${`${opt.aliases.length ? opt.aliases.join(", ") + "," : ""}`.padEnd(paddedAliasLength)}${`${opt.name}${(() => {
            const typeText = getOptionTypeText(opt);
            return typeText.length ? " " + typeText : "";
          })()}`.padEnd(nameLength)}${(() => {
            var _a2;
            if (!((_a2 = opt.description) == null ? void 0 : _a2.length)) {
              return opt.default !== void 0 ? `default: ${JSON.stringify(opt.default)}` : "";
            }
            const split = opt.description.split("\n");
            const first = split.shift();
            const def = opt.default !== void 0 ? ` (default: ${JSON.stringify(opt.default)})` : "";
            const final = [first, ...split.map((s2) => "".padEnd(preDescPad) + s2)].join("\n") + def;
            return final;
          })()}`
        ).join("\n");
        console.log("\nFlags:");
        console.log(data);
      }
      console.log("\nGlobal flags:");
      console.log(`  -h, --help      help for ${commandName}`);
      console.log(`  -v, --version   version${cliName ? ` for ${cliName}` : ""}`);
      if (subcommands) {
        console.log(
          `
Use "${cliName ? cliName + " " : ""}${commandName} [command] --help" for more information about a command.
`
        );
      }
      return true;
    }
    case "global_help": {
      const cliName = event.name;
      const desc = event.description;
      const commands = event.commands.filter((c) => !c.hidden);
      if (desc !== void 0) {
        console.log(`${desc}
`);
      }
      console.log("Usage:");
      console.log(`  ${cliName ? cliName + " " : ""}[command]`);
      if (commands.length) {
        console.log("\nAvailable Commands:");
        const padding = 3;
        const maxLength = commands.reduce((p, e2) => e2.name.length > p ? e2.name.length : p, 0);
        const paddedLength = maxLength + padding;
        const data = commands.map(
          (c) => `  ${c.name.padEnd(paddedLength)}${(() => {
            const desc2 = c.shortDesc ?? c.desc;
            if (!(desc2 == null ? void 0 : desc2.length))
              return "";
            const split = desc2.split("\n");
            const first = split.shift();
            const final = [first, ...split.map((s2) => "".padEnd(paddedLength + 2) + s2)].join("\n");
            return final;
          })()}`
        ).join("\n");
        console.log(data);
      } else {
        console.log("\nNo available commands.");
      }
      console.log("\nFlags:");
      console.log(`  -h, --help      help${cliName ? ` for ${cliName}` : ""}`);
      console.log(`  -v, --version   version${cliName ? ` for ${cliName}` : ""}`);
      console.log("\n");
      return true;
    }
    case "version": {
      return true;
    }
    case "error": {
      let msg;
      switch (event.violation) {
        case "above_max": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          const option = event.option;
          const max = option.maxVal;
          msg = `Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`;
          break;
        }
        case "below_min": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          const option = event.option;
          const min = option.minVal;
          msg = `Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`;
          break;
        }
        case "expected_int": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          msg = `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`;
          break;
        }
        case "invalid_boolean_syntax": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          msg = `Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.
Allowed values: true, false, 0, 1`;
          break;
        }
        case "invalid_string_syntax": {
          const matchedName = event.offender.namePart;
          msg = `Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
          break;
        }
        case "invalid_number_syntax": {
          const matchedName = event.offender.namePart;
          msg = `Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
          break;
        }
        case "invalid_number_value": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          msg = `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`;
          break;
        }
        case "enum_violation": {
          const matchedName = event.offender.namePart;
          const data = event.offender.dataPart;
          const option = event.option;
          const values = option.enumVals;
          msg = option.type === "positional" ? `Invalid value: value for the positional argument '${option.name}' must be either one of the following: ${values.join(", ")}; Received: ${data}` : `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`;
          break;
        }
        case "unknown_command_error": {
          const msg2 = `Unknown command: '${event.offender}'.
Type '--help' to get help on the cli.`;
          console.error(msg2);
          return true;
        }
        case "unknown_subcommand_error": {
          const cName = getCommandNameWithParents(event.command);
          const msg2 = `Unknown command: ${cName} ${event.offender}.
Type '${cName} --help' to get the help on command.`;
          console.error(msg2);
          return true;
        }
        case "missing_args_error": {
          const { missing: missingOpts, command: command3 } = event;
          msg = `Command '${command3.name}' is missing following required options: ${missingOpts.map((opt) => {
            const name = opt.shift();
            const aliases = opt;
            if (aliases.length)
              return `${name} [${aliases.join(", ")}]`;
            return name;
          }).join(", ")}`;
          break;
        }
        case "unrecognized_args_error": {
          const { command: command3, unrecognized } = event;
          msg = `Unrecognized options for command '${command3.name}': ${unrecognized.join(", ")}`;
          break;
        }
        case "unknown_error": {
          const e2 = event.error;
          console.error(typeof e2 === "object" && e2 !== null && "message" in e2 ? e2.message : e2);
          return true;
        }
      }
      console.error(msg);
      return true;
    }
  }
  return false;
};
var eventHandlerWrapper = (customEventHandler) => async (event) => await customEventHandler(event) ? true : await defaultEventHandler(event);
var import_shell_quote = __toESM2(require_shell_quote(), 1);
function isInt(value) {
  return value === Math.floor(value);
}
var executeOrLog = async (target) => typeof target === "string" ? console.log(target) : target ? await target() : void 0;
var generatePrefix = (name) => name.startsWith("-") ? name : name.length > 1 ? `--${name}` : `-${name}`;
var validateOptions = (config) => {
  const cloned = (0, import_clone.default)(config);
  const entries = [];
  const storedNames = [];
  const cfgEntries = Object.entries(cloned);
  for (const [key, value] of cfgEntries) {
    const cfg = value._.config;
    if (cfg.name === void 0)
      cfg.name = key;
    if (cfg.type === "positional")
      continue;
    if (cfg.name.includes("=")) {
      throw new BroCliError(
        `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
      );
    }
    for (const alias of cfg.aliases) {
      if (alias.includes("=")) {
        throw new BroCliError(
          `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
        );
      }
    }
    cfg.name = generatePrefix(cfg.name);
    cfg.aliases = cfg.aliases.map((a) => generatePrefix(a));
  }
  for (const [key, value] of cfgEntries) {
    const cfg = value._.config;
    if (cfg.type === "positional") {
      entries.push([key, { config: cfg, $output: void 0 }]);
      continue;
    }
    const reservedNames = ["--help", "-h", "--version", "-v"];
    const allNames = [cfg.name, ...cfg.aliases];
    for (const name of allNames) {
      const match2 = reservedNames.find((n) => n === name);
      if (match2)
        throw new BroCliError(`Can't define option '${cfg.name}' - name '${match2}' is reserved!`);
    }
    for (const storage of storedNames) {
      const nameOccupier = storage.find((e2) => e2 === cfg.name);
      if (!nameOccupier)
        continue;
      throw new BroCliError(
        `Can't define option '${cfg.name}' - name is already in use by option '${storage[0]}'!`
      );
    }
    for (const alias of cfg.aliases) {
      for (const storage of storedNames) {
        const nameOccupier = storage.find((e2) => e2 === alias);
        if (!nameOccupier)
          continue;
        throw new BroCliError(
          `Can't define option '${cfg.name}' - alias '${alias}' is already in use by option '${storage[0]}'!`
        );
      }
    }
    const currentNames = [cfg.name, ...cfg.aliases];
    storedNames.push(currentNames);
    currentNames.forEach((name, idx) => {
      if (currentNames.findIndex((e2) => e2 === name) === idx)
        return;
      throw new BroCliError(
        `Can't define option '${cfg.name}' - duplicate alias '${name}'!`
      );
    });
    entries.push([key, { config: cfg, $output: void 0 }]);
  }
  return Object.fromEntries(entries);
};
var assignParent = (parent, subcommands) => subcommands.forEach((e2) => {
  e2.parent = parent;
  if (e2.subcommands)
    assignParent(e2, e2.subcommands);
});
var command2 = (command3) => {
  var _a, _b, _c;
  const allNames = command3.aliases ? [command3.name, ...command3.aliases] : [command3.name];
  const cmd = (0, import_clone.default)(command3);
  if (command3.subcommands && command3.options && Object.values(command3.options).find((opt) => opt._.config.type === "positional")) {
    throw new BroCliError(
      `Can't define command '${cmd.name}' - command can't have subcommands and positional args at the same time!`
    );
  }
  if (!command3.handler && !command3.subcommands) {
    throw new BroCliError(
      `Can't define command '${cmd.name}' - command without subcommands must have a handler present!`
    );
  }
  const processedOptions = command3.options ? validateOptions(command3.options) : void 0;
  cmd.options = processedOptions;
  cmd.name = cmd.name ?? ((_a = cmd.aliases) == null ? void 0 : _a.shift());
  if (!cmd.name)
    throw new BroCliError(`Can't define command without name!`);
  cmd.aliases = ((_b = cmd.aliases) == null ? void 0 : _b.length) ? cmd.aliases : void 0;
  if (cmd.name.startsWith("-")) {
    throw new BroCliError(`Can't define command '${cmd.name}' - command name can't start with '-'!`);
  }
  (_c = cmd.aliases) == null ? void 0 : _c.forEach((a) => {
    if (a.startsWith("-")) {
      throw new BroCliError(`Can't define command '${cmd.name}' - command aliases can't start with '-'!`);
    }
  });
  allNames.forEach((n, i2) => {
    if (n === "help") {
      throw new BroCliError(
        `Can't define command '${cmd.name}' - 'help' is a reserved name. If you want to redefine help message - do so in runCli's config.`
      );
    }
    const lCaseName = n == null ? void 0 : n.toLowerCase();
    if (lCaseName === "0" || lCaseName === "1" || lCaseName === "true" || lCaseName === "false") {
      throw new BroCliError(
        `Can't define command '${cmd.name}' - '${n}' is a reserved for boolean values name!`
      );
    }
    const idx = allNames.findIndex((an) => an === n);
    if (idx !== i2)
      throw new BroCliError(`Can't define command '${cmd.name}' - duplicate alias '${n}'!`);
  });
  if (cmd.subcommands) {
    assignParent(cmd, cmd.subcommands);
  }
  return cmd;
};
var getCommandInner = (commands, candidates, args, cliName, cliDescription) => {
  const { data: arg, originalIndex: index5 } = candidates.shift();
  const command3 = commands.find((c) => {
    const names = c.aliases ? [c.name, ...c.aliases] : [c.name];
    const res = names.find((name) => name === arg);
    return res;
  });
  if (!command3) {
    return {
      command: command3,
      args
    };
  }
  const newArgs = removeByIndex(args, index5);
  if (!candidates.length || !command3.subcommands) {
    return {
      command: command3,
      args: newArgs
    };
  }
  const newCandidates = candidates.map((c) => ({ data: c.data, originalIndex: c.originalIndex - 1 }));
  const subcommand = getCommandInner(command3.subcommands, newCandidates, newArgs, cliName, cliDescription);
  if (!subcommand.command) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "unknown_subcommand_error",
      name: cliName,
      description: cliDescription,
      command: command3,
      offender: candidates[0].data
    });
  }
  return subcommand;
};
var getCommand = (commands, args, cliName, cliDescription) => {
  var _a;
  const candidates = [];
  for (let i2 = 0; i2 < args.length; ++i2) {
    const arg = args[i2];
    if (arg === "--help" || arg === "-h" || arg === "--version" || arg === "-v") {
      const lCaseNext = (_a = args[i2 + 1]) == null ? void 0 : _a.toLowerCase();
      if (lCaseNext === "0" || lCaseNext === "1" || lCaseNext === "true" || lCaseNext === "false")
        ++i2;
      continue;
    }
    if (arg == null ? void 0 : arg.startsWith("-")) {
      if (!arg.includes("="))
        ++i2;
      continue;
    }
    candidates.push({
      data: arg,
      originalIndex: i2
    });
  }
  if (!candidates.length) {
    return {
      command: void 0,
      args
    };
  }
  const firstCandidate = candidates[0];
  if (firstCandidate.data === "help") {
    return {
      command: "help",
      args: removeByIndex(args, firstCandidate.originalIndex)
    };
  }
  const { command: command3, args: argsRes } = getCommandInner(commands, candidates, args, cliName, cliDescription);
  if (!command3) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "unknown_command_error",
      commands,
      name: cliName,
      description: cliDescription,
      offender: firstCandidate.data
    });
  }
  return {
    command: command3,
    args: argsRes
  };
};
var parseArg = (command3, options, positionals, arg, nextArg, cliName, cliDescription) => {
  let data = void 0;
  const argSplit = arg.split("=");
  const hasEq = arg.includes("=");
  const namePart = argSplit.shift();
  const dataPart = hasEq ? argSplit.join("=") : nextArg;
  let skipNext = !hasEq;
  if (namePart === "--help" || namePart === "-h") {
    return {
      isHelp: true
    };
  }
  if (namePart === "--version" || namePart === "-v") {
    return {
      isVersion: true
    };
  }
  if (!arg.startsWith("-")) {
    if (!positionals.length)
      return {};
    const pos = positionals.shift();
    if (pos[1].enumVals && !pos[1].enumVals.find((val2) => val2 === arg)) {
      throw new BroCliError(void 0, {
        type: "error",
        name: cliName,
        description: cliDescription,
        violation: "enum_violation",
        command: command3,
        option: pos[1],
        offender: {
          dataPart: arg
        }
      });
    }
    data = arg;
    return {
      data,
      skipNext: false,
      name: pos[0],
      option: pos[1]
    };
  }
  const option = options.find(([optKey, opt]) => {
    const names = [opt.name, ...opt.aliases];
    if (opt.type === "boolean") {
      const match2 = names.find((name) => name === namePart);
      if (!match2)
        return false;
      let lcaseData = dataPart == null ? void 0 : dataPart.toLowerCase();
      if (!hasEq && (nextArg == null ? void 0 : nextArg.startsWith("-"))) {
        data = true;
        skipNext = false;
        return true;
      }
      if (lcaseData === void 0 || lcaseData === "" || lcaseData === "true" || lcaseData === "1") {
        data = true;
        return true;
      }
      if (lcaseData === "false" || lcaseData === "0") {
        data = false;
        return true;
      }
      if (!hasEq) {
        data = true;
        skipNext = false;
        return true;
      }
      throw new BroCliError(void 0, {
        type: "error",
        name: cliName,
        description: cliDescription,
        violation: "invalid_boolean_syntax",
        option: opt,
        command: command3,
        offender: {
          namePart,
          dataPart
        }
      });
    } else {
      const match2 = names.find((name) => name === namePart);
      if (!match2)
        return false;
      if (opt.type === "string") {
        if (!hasEq && nextArg === void 0) {
          throw new BroCliError(void 0, {
            type: "error",
            name: cliName,
            description: cliDescription,
            violation: "invalid_string_syntax",
            option: opt,
            command: command3,
            offender: {
              namePart,
              dataPart
            }
          });
        }
        if (opt.enumVals && !opt.enumVals.find((val2) => val2 === dataPart)) {
          throw new BroCliError(void 0, {
            type: "error",
            name: cliName,
            description: cliDescription,
            violation: "enum_violation",
            option: opt,
            command: command3,
            offender: {
              namePart,
              dataPart
            }
          });
        }
        data = dataPart;
        return true;
      }
      if (!hasEq && nextArg === void 0) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "invalid_number_syntax",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      const numData = Number(dataPart);
      if (isNaN(numData)) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "invalid_number_value",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      if (opt.isInt && !isInt(numData)) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "expected_int",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      if (opt.minVal !== void 0 && numData < opt.minVal) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "below_min",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      if (opt.maxVal !== void 0 && numData > opt.maxVal) {
        throw new BroCliError(void 0, {
          type: "error",
          name: cliName,
          description: cliDescription,
          violation: "above_max",
          option: opt,
          command: command3,
          offender: {
            namePart,
            dataPart
          }
        });
      }
      data = numData;
      return true;
    }
  });
  return {
    data,
    skipNext,
    name: option == null ? void 0 : option[0],
    option: option == null ? void 0 : option[1]
  };
};
var parseOptions = (command3, args, cliName, cliDescription, omitKeysOfUndefinedOptions) => {
  const options = command3.options;
  const optEntries = Object.entries(options ?? {}).map(
    (opt) => [opt[0], opt[1].config]
  );
  const nonPositionalEntries = optEntries.filter(([key, opt]) => opt.type !== "positional");
  const positionalEntries = optEntries.filter(([key, opt]) => opt.type === "positional");
  const result = {};
  const missingRequiredArr = [];
  const unrecognizedArgsArr = [];
  for (let i2 = 0; i2 < args.length; ++i2) {
    const arg = args[i2];
    const nextArg = args[i2 + 1];
    const {
      data,
      name,
      option,
      skipNext,
      isHelp,
      isVersion
    } = parseArg(command3, nonPositionalEntries, positionalEntries, arg, nextArg, cliName, cliDescription);
    if (!option)
      unrecognizedArgsArr.push(arg.split("=")[0]);
    if (skipNext)
      ++i2;
    if (isHelp)
      return "help";
    if (isVersion)
      return "version";
    result[name] = data;
  }
  for (const [optKey, option] of optEntries) {
    const data = result[optKey] ?? option.default;
    if (!omitKeysOfUndefinedOptions) {
      result[optKey] = data;
    } else {
      if (data !== void 0)
        result[optKey] = data;
    }
    if (option.isRequired && result[optKey] === void 0)
      missingRequiredArr.push([option.name, ...option.aliases]);
  }
  if (missingRequiredArr.length) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "missing_args_error",
      name: cliName,
      description: cliDescription,
      command: command3,
      missing: missingRequiredArr
    });
  }
  if (unrecognizedArgsArr.length) {
    throw new BroCliError(void 0, {
      type: "error",
      violation: "unrecognized_args_error",
      name: cliName,
      description: cliDescription,
      command: command3,
      unrecognized: unrecognizedArgsArr
    });
  }
  return Object.keys(result).length ? result : void 0;
};
var getCommandNameWithParents = (command3) => command3.parent ? `${getCommandNameWithParents(command3.parent)} ${command3.name}` : command3.name;
var validateCommands = (commands, parent) => {
  const storedNames = {};
  for (const cmd of commands) {
    const storageVals = Object.values(storedNames);
    for (const storage of storageVals) {
      const nameOccupier = storage.find((e2) => e2 === cmd.name);
      if (!nameOccupier)
        continue;
      throw new BroCliError(
        `Can't define command '${getCommandNameWithParents(cmd)}': name is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage[0]}'!`
      );
    }
    if (cmd.aliases) {
      for (const alias of cmd.aliases) {
        for (const storage of storageVals) {
          const nameOccupier = storage.find((e2) => e2 === alias);
          if (!nameOccupier)
            continue;
          throw new BroCliError(
            `Can't define command '${getCommandNameWithParents(cmd)}': alias '${alias}' is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage[0]}'!`
          );
        }
      }
    }
    storedNames[cmd.name] = cmd.aliases ? [cmd.name, ...cmd.aliases] : [cmd.name];
    if (cmd.subcommands)
      cmd.subcommands = validateCommands(cmd.subcommands, cmd);
  }
  return commands;
};
var removeByIndex = (arr, idx) => [...arr.slice(0, idx), ...arr.slice(idx + 1, arr.length)];
var run = async (commands, config) => {
  var _a, _b;
  const eventHandler = (config == null ? void 0 : config.theme) ? eventHandlerWrapper(config.theme) : defaultEventHandler;
  const argSource = (config == null ? void 0 : config.argSource) ?? process.argv;
  const version3 = config == null ? void 0 : config.version;
  const help = config == null ? void 0 : config.help;
  const omitKeysOfUndefinedOptions = (config == null ? void 0 : config.omitKeysOfUndefinedOptions) ?? false;
  const cliName = config == null ? void 0 : config.name;
  const cliDescription = config == null ? void 0 : config.description;
  try {
    const processedCmds = validateCommands(commands);
    let args = argSource.slice(2, argSource.length);
    if (!args.length) {
      return help !== void 0 ? await executeOrLog(help) : await eventHandler({
        type: "global_help",
        description: cliDescription,
        name: cliName,
        commands: processedCmds
      });
    }
    const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
    if (helpIndex !== -1 && (helpIndex > 0 ? ((_a = args[helpIndex - 1]) == null ? void 0 : _a.startsWith("-")) && !args[helpIndex - 1].includes("=") ? false : true : true)) {
      const command4 = getCommand(processedCmds, args, cliName, cliDescription).command;
      if (typeof command4 === "object") {
        return command4.help !== void 0 ? await executeOrLog(command4.help) : await eventHandler({
          type: "command_help",
          description: cliDescription,
          name: cliName,
          command: command4
        });
      } else {
        return help !== void 0 ? await executeOrLog(help) : await eventHandler({
          type: "global_help",
          description: cliDescription,
          name: cliName,
          commands: processedCmds
        });
      }
    }
    const versionIndex = args.findIndex((arg) => arg === "--version" || arg === "-v");
    if (versionIndex !== -1 && (versionIndex > 0 ? ((_b = args[versionIndex - 1]) == null ? void 0 : _b.startsWith("-")) ? false : true : true)) {
      return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
        type: "version",
        name: cliName,
        description: cliDescription
      });
    }
    const { command: command3, args: newArgs } = getCommand(processedCmds, args, cliName, cliDescription);
    if (!command3) {
      return help !== void 0 ? await executeOrLog(help) : await eventHandler({
        type: "global_help",
        description: cliDescription,
        name: cliName,
        commands: processedCmds
      });
    }
    if (command3 === "help") {
      let helpCommand;
      let newestArgs = newArgs;
      do {
        const res = getCommand(processedCmds, newestArgs, cliName, cliDescription);
        helpCommand = res.command;
        newestArgs = res.args;
      } while (helpCommand === "help");
      return helpCommand ? helpCommand.help !== void 0 ? await executeOrLog(helpCommand.help) : await eventHandler({
        type: "command_help",
        description: cliDescription,
        name: cliName,
        command: helpCommand
      }) : help !== void 0 ? await executeOrLog(help) : await eventHandler({
        type: "global_help",
        description: cliDescription,
        name: cliName,
        commands: processedCmds
      });
    }
    const optionResult = parseOptions(command3, newArgs, cliName, cliDescription, omitKeysOfUndefinedOptions);
    if (optionResult === "help") {
      return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
        type: "command_help",
        description: cliDescription,
        name: cliName,
        command: command3
      });
    }
    if (optionResult === "version") {
      return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
        type: "version",
        name: cliName,
        description: cliDescription
      });
    }
    if (command3.handler) {
      if (config == null ? void 0 : config.hook)
        await config.hook("before", command3);
      await command3.handler(command3.transform ? await command3.transform(optionResult) : optionResult);
      if (config == null ? void 0 : config.hook)
        await config.hook("after", command3);
      return;
    } else {
      return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
        type: "command_help",
        description: cliDescription,
        name: cliName,
        command: command3
      });
    }
  } catch (e2) {
    if (e2 instanceof BroCliError) {
      if (e2.event)
        await eventHandler(e2.event);
      else {
        if (!(config == null ? void 0 : config.noExit))
          console.error(e2.message);
        else
          return e2.message;
      }
    } else {
      await eventHandler({
        type: "error",
        violation: "unknown_error",
        name: cliName,
        description: cliDescription,
        error: e2
      });
    }
    if (!(config == null ? void 0 : config.noExit))
      process.exit(1);
    return;
  }
};
var OptionBuilderBase = class _OptionBuilderBase {
  _;
  config = () => this._.config;
  constructor(config) {
    this._ = {
      config: config ?? {
        aliases: [],
        type: "string"
      },
      $output: void 0
    };
  }
  string(name) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "string", name });
  }
  number(name) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "number", name });
  }
  boolean(name) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "boolean", name });
  }
  positional(displayName) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, type: "positional", name: displayName });
  }
  alias(...aliases) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, aliases });
  }
  desc(description) {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, description });
  }
  hidden() {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, isHidden: true });
  }
  required() {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, isRequired: true });
  }
  default(value) {
    const config = this.config();
    const enums = config.enumVals;
    if (enums && !enums.find((v) => value === v)) {
      throw new Error(
        `Option enums [ ${enums.join(", ")} ] are incompatible with default value ${value}`
      );
    }
    return new _OptionBuilderBase({ ...config, default: value });
  }
  enum(...values) {
    const config = this.config();
    const defaultVal = config.default;
    if (defaultVal !== void 0 && !values.find((v) => defaultVal === v)) {
      throw new Error(
        `Option enums [ ${values.join(", ")} ] are incompatible with default value ${defaultVal}`
      );
    }
    return new _OptionBuilderBase({ ...config, enumVals: values });
  }
  min(value) {
    const config = this.config();
    const maxVal = config.maxVal;
    if (maxVal !== void 0 && maxVal < value) {
      throw new BroCliError("Unable to define option's min value to be higher than max value!");
    }
    return new _OptionBuilderBase({ ...config, minVal: value });
  }
  max(value) {
    const config = this.config();
    const minVal = config.minVal;
    if (minVal !== void 0 && minVal > value) {
      throw new BroCliError("Unable to define option's max value to be lower than min value!");
    }
    return new _OptionBuilderBase({ ...config, maxVal: value });
  }
  int() {
    const config = this.config();
    return new _OptionBuilderBase({ ...config, isInt: true });
  }
};
function string(name) {
  return typeof name === "string" ? new OptionBuilderBase().string(name) : new OptionBuilderBase().string();
}
function number(name) {
  return typeof name === "string" ? new OptionBuilderBase().number(name) : new OptionBuilderBase().number();
}
function boolean(name) {
  return typeof name === "string" ? new OptionBuilderBase().boolean(name) : new OptionBuilderBase().boolean();
}

// src/cli/index.ts
init_source();

// src/cli/schema.ts
init_source();

// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/config.js
(function() {
  require_main().config(
    Object.assign(
      {},
      require_env_options(),
      require_cli_options()(process.argv)
    )
  );
})();

// src/cli/schema.ts
var import_fs13 = require("fs");
var import_hanji15 = __toESM(require_hanji());
init_schemaValidator();
init_utils();
init_global();
init_utils2();

// ../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
var import_node_path = __toESM(require("node:path"), 1);
var import_node_os2 = __toESM(require("node:os"), 1);
var import_node_process2 = __toESM(require("node: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("node:child_process");
var import_path2 = require("path");
function runCommand(command, options = {}) {
  return new Promise((resolve2) => {
    (0, import_node_child_process.exec)(command, options, (error2) => {
      return resolve2({ exitCode: (error2 == null ? void 0 : error2.code) ?? 0 });
    });
  });
}
var certs = async () => {
  const res = await runCommand("mkcert --help");
  if (res.exitCode === 0) {
    const p = envPaths("drizzle-studio", {
      suffix: ""
    });
    (0, import_fs2.mkdirSync)(p.data, { recursive: true });
    const keyPath = (0, import_path2.join)(p.data, "localhost-key.pem");
    const certPath = (0, import_path2.join)(p.data, "localhost.pem");
    try {
      await Promise.all([(0, import_promises.access)(keyPath), (0, import_promises.access)(certPath)]);
    } catch (e2) {
      await runCommand(`mkcert localhost`, { cwd: p.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/cli/commands/check.ts
init_utils2();
var checkHandler = (out, dialect6) => {
  const { snapshots } = prepareOutFolder(out, dialect6);
  const report = validateWithReport(snapshots, dialect6);
  if (report.nonLatest.length > 0) {
    console.log(
      report.nonLatest.map((it) => {
        return `${it} is not of the latest version, please run "drizzle-kit up"`;
      }).join("\n")
    );
    process.exit(1);
  }
  if (report.malformed.length) {
    const message2 = report.malformed.map((it) => {
      return `${it} data is malformed`;
    }).join("\n");
    console.log(message2);
  }
  const collisionEntries = Object.entries(report.idsMap).filter(
    (it) => it[1].snapshots.length > 1
  );
  const message = collisionEntries.map((it) => {
    const data = it[1];
    return `[${data.snapshots.join(
      ", "
    )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
  }).join("\n");
  if (message) {
    console.log(message);
  }
  const abort = report.malformed.length || collisionEntries.length > 0;
  if (abort) {
    process.exit(1);
  }
};

// src/cli/commands/drop.ts
init_source();
var import_fs7 = require("fs");
var import_fs8 = __toESM(require("fs"));
var import_hanji4 = __toESM(require_hanji());
var import_path6 = require("path");
init_views();
init_migrate();
var dropMigration = async ({
  out,
  bundle
}) => {
  const metaFilePath = (0, import_path6.join)(out, "meta", "_journal.json");
  const journal = JSON.parse((0, import_fs7.readFileSync)(metaFilePath, "utf-8"));
  if (journal.entries.length === 0) {
    console.log(
      `[${source_default.blue("i")}] no migration entries found in ${metaFilePath}`
    );
    return;
  }
  const result = await (0, import_hanji4.render)(new DropMigrationView(journal.entries));
  if (result.status === "aborted")
    return;
  delete journal.entries[journal.entries.indexOf(result.data)];
  const resultJournal = {
    ...journal,
    entries: journal.entries.filter(Boolean)
  };
  const sqlFilePath = (0, import_path6.join)(out, `${result.data.tag}.sql`);
  const snapshotFilePath = (0, import_path6.join)(
    out,
    "meta",
    `${result.data.tag.split("_")[0]}_snapshot.json`
  );
  (0, import_fs7.rmSync)(sqlFilePath);
  (0, import_fs7.rmSync)(snapshotFilePath);
  (0, import_fs7.writeFileSync)(metaFilePath, JSON.stringify(resultJournal, null, 2));
  if (bundle) {
    import_fs8.default.writeFileSync(
      (0, import_path6.join)(out, `migrations.js`),
      embeddedMigrations(resultJournal)
    );
  }
  console.log(
    `[${source_default.green("\u2713")}] ${source_default.bold(
      result.data.tag
    )} migration successfully dropped`
  );
};

// src/cli/commands/mysqlUp.ts
var upMysqlHandler = (out) => {
};

// src/cli/commands/pgUp.ts
init_source();
var import_fs9 = require("fs");
init_pgSchema();
init_utils2();
var upPgHandler = (out) => {
  const { snapshots } = prepareOutFolder(out, "postgresql");
  const report = validateWithReport(snapshots, "postgresql");
  report.nonLatest.map((it) => ({
    path: it,
    raw: report.rawMap[it]
  })).forEach((it) => {
    const path4 = it.path;
    let resultV6 = it.raw;
    if (it.raw.version === "5") {
      resultV6 = updateUpToV6(it.raw);
    }
    const result = updateUpToV7(resultV6);
    console.log(`[${source_default.green("\u2713")}] ${path4}`);
    (0, import_fs9.writeFileSync)(path4, JSON.stringify(result, null, 2));
  });
  console.log("Everything's fine \u{1F436}\u{1F525}");
};
var updateUpToV6 = (json) => {
  const schema6 = pgSchemaV5.parse(json);
  const tables = Object.fromEntries(
    Object.entries(schema6.tables).map((it) => {
      const table5 = it[1];
      const schema7 = table5.schema || "public";
      return [`${schema7}.${table5.name}`, table5];
    })
  );
  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 table5 = it[1];
      const mappedIndexes = Object.fromEntries(
        Object.entries(table5.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], { ...table5, indexes: mappedIndexes, policies: {}, isRLSEnabled: false, checkConstraints: {} }];
    })
  );
  return {
    ...schema6,
    version: "7",
    dialect: "postgresql",
    sequences: {},
    tables,
    policies: {},
    views: {},
    roles: {}
  };
};

// src/cli/commands/singlestoreUp.ts
var upSinglestoreHandler = (out) => {
};

// src/cli/commands/sqliteUp.ts
init_source();
var import_fs10 = require("fs");
init_global();
init_sqliteSchema();
init_utils2();
var upSqliteHandler = (out) => {
  const { snapshots } = prepareOutFolder(out, "sqlite");
  const report = validateWithReport(snapshots, "sqlite");
  report.nonLatest.map((it) => ({
    path: it,
    raw: report.rawMap[it]
  })).forEach((it) => {
    const path4 = it.path;
    const result = updateUpToV62(it.raw);
    console.log(`[${source_default.green("\u2713")}] ${path4}`);
    (0, import_fs10.writeFileSync)(path4, JSON.stringify(result, null, 2));
  });
  console.log("Everything's fine \u{1F436}\u{1F525}");
};
var updateUpToV62 = (json) => {
  const schema6 = sqliteSchemaV5.parse(json);
  const tables = mapEntries(schema6.tables, (tableKey2, table5) => {
    const columns = mapEntries(table5.columns, (key, value) => {
      if (value.default && (typeof value.default === "object" || Array.isArray(value.default))) {
        value.default = `'${JSON.stringify(value.default)}'`;
      }
      return [key, value];
    });
    table5.columns = columns;
    return [tableKey2, table5];
  });
  return {
    ...schema6,
    version: "6",
    dialect: "sqlite",
    tables,
    views: {}
  };
};

// src/cli/schema.ts
init_utils3();
init_utils5();
init_common();
init_outputs();
init_views();
var optionDialect = string("dialect").enum(...dialects).desc(
  `Database dialect: 'postgresql', 'mysql', 'sqlite', 'turso' or 'singlestore'`
);
var optionOut = string().desc("Output folder, 'drizzle' by default");
var optionConfig = string().desc("Path to drizzle config file");
var optionBreakpoints = boolean().desc(
  `Prepare SQL statements with breakpoints`
);
var optionDriver = string().enum(...drivers).desc("Database driver");
var optionCasing = string().enum("camelCase", "snake_case").desc("Casing for serialization");
var generate = command2({
  name: "generate",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    driver: optionDriver,
    casing: optionCasing,
    schema: string().desc("Path to a schema file or folder"),
    out: optionOut,
    name: string().desc("Migration file name"),
    breakpoints: optionBreakpoints,
    custom: boolean().desc("Prepare empty migration file for custom SQL").default(false),
    prefix: string().enum(...prefixes).default("index")
  },
  transform: async (opts) => {
    const from = assertCollisions(
      "generate",
      opts,
      ["prefix", "name", "custom"],
      ["driver", "breakpoints", "schema", "out", "dialect", "casing"]
    );
    return prepareGenerateConfig(opts, from);
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    const {
      prepareAndMigratePg: prepareAndMigratePg2,
      prepareAndMigrateMysql: prepareAndMigrateMysql2,
      prepareAndMigrateSqlite: prepareAndMigrateSqlite2,
      prepareAndMigrateLibSQL: prepareAndMigrateLibSQL2,
      prepareAndMigrateSingleStore: prepareAndMigrateSingleStore2
    } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
    const dialect6 = opts.dialect;
    if (dialect6 === "postgresql") {
      await prepareAndMigratePg2(opts);
    } else if (dialect6 === "mysql") {
      await prepareAndMigrateMysql2(opts);
    } else if (dialect6 === "sqlite") {
      await prepareAndMigrateSqlite2(opts);
    } else if (dialect6 === "turso") {
      await prepareAndMigrateLibSQL2(opts);
    } else if (dialect6 === "singlestore") {
      await prepareAndMigrateSingleStore2(opts);
    } else {
      assertUnreachable(dialect6);
    }
  }
});
var migrate = command2({
  name: "migrate",
  options: {
    config: optionConfig
  },
  transform: async (opts) => {
    return await prepareMigrateConfig(opts.config);
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    const { dialect: dialect6, schema: schema6, table: table5, out, credentials: credentials2 } = opts;
    try {
      if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await preparePostgresDB2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: out,
            migrationsTable: table5,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "mysql") {
        const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToMySQL2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: out,
            migrationsTable: table5,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "singlestore") {
        const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToSingleStore2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: out,
            migrationsTable: table5,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "sqlite") {
        const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToSQLite2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: opts.out,
            migrationsTable: table5,
            migrationsSchema: schema6
          })
        );
      } else if (dialect6 === "turso") {
        const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
        const { migrate: migrate2 } = await connectToLibSQL2(credentials2);
        await (0, import_hanji15.renderWithTask)(
          new MigrateProgress(),
          migrate2({
            migrationsFolder: opts.out,
            migrationsTable: table5,
            migrationsSchema: schema6
          })
        );
      } else {
        assertUnreachable(dialect6);
      }
    } catch (e2) {
      console.error(e2);
      process.exit(1);
    }
    process.exit(0);
  }
});
var optionsFilters = {
  tablesFilter: string().desc("Table name filters"),
  schemaFilters: string().desc("Schema name filters"),
  extensionsFilters: string().desc(
    "`Database extensions internal database filters"
  )
};
var optionsDatabaseCredentials = {
  url: string().desc("Database connection URL"),
  host: string().desc("Database host"),
  port: string().desc("Database port"),
  user: string().desc("Database user"),
  password: string().desc("Database password"),
  database: string().desc("Database name"),
  ssl: string().desc("ssl mode"),
  // Turso
  authToken: string("auth-token").desc("Database auth token [Turso]"),
  // specific cases
  driver: optionDriver
};
var push = command2({
  name: "push",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    casing: optionCasing,
    schema: string().desc("Path to a schema file or folder"),
    ...optionsFilters,
    ...optionsDatabaseCredentials,
    verbose: boolean().desc("Print all statements for each push").default(false),
    strict: boolean().desc("Always ask for confirmation").default(false),
    force: boolean().desc(
      "Auto-approve all data loss statements. Note: Data loss statements may truncate your tables and data"
    ).default(false)
  },
  transform: async (opts) => {
    const from = assertCollisions(
      "push",
      opts,
      ["force", "verbose", "strict"],
      [
        "schema",
        "dialect",
        "driver",
        "url",
        "host",
        "port",
        "user",
        "password",
        "database",
        "ssl",
        "authToken",
        "schemaFilters",
        "extensionsFilters",
        "tablesFilter",
        "casing"
      ]
    );
    return preparePushConfig(opts, from);
  },
  handler: async (config) => {
    await assertPackages("drizzle-orm");
    await assertOrmCoreVersion();
    const {
      dialect: dialect6,
      schemaPath,
      strict,
      verbose,
      credentials: credentials2,
      tablesFilter,
      schemasFilter,
      force,
      casing: casing2,
      entities
    } = config;
    try {
      if (dialect6 === "mysql") {
        const { mysqlPush: mysqlPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await mysqlPush2(
          schemaPath,
          credentials2,
          tablesFilter,
          strict,
          verbose,
          force,
          casing2
        );
      } else if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { pgPush: pgPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await pgPush2(
          schemaPath,
          verbose,
          strict,
          credentials2,
          tablesFilter,
          schemasFilter,
          entities,
          force,
          casing2
        );
      } else if (dialect6 === "sqlite") {
        const { sqlitePush: sqlitePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await sqlitePush2(
          schemaPath,
          verbose,
          strict,
          credentials2,
          tablesFilter,
          force,
          casing2
        );
      } else if (dialect6 === "turso") {
        const { libSQLPush: libSQLPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await libSQLPush2(
          schemaPath,
          verbose,
          strict,
          credentials2,
          tablesFilter,
          force,
          casing2
        );
      } else if (dialect6 === "singlestore") {
        const { singlestorePush: singlestorePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
        await singlestorePush2(
          schemaPath,
          credentials2,
          tablesFilter,
          strict,
          verbose,
          force,
          casing2
        );
      } else {
        assertUnreachable(dialect6);
      }
    } catch (e2) {
      console.error(e2);
    }
    process.exit(0);
  }
});
var check = command2({
  name: "check",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    out: optionOut
  },
  transform: async (opts) => {
    const from = assertCollisions("check", opts, [], ["dialect", "out"]);
    return prepareCheckParams(opts, from);
  },
  handler: async (config) => {
    await assertOrmCoreVersion();
    const { out, dialect: dialect6 } = config;
    checkHandler(out, dialect6);
    console.log("Everything's fine \u{1F436}\u{1F525}");
  }
});
var up = command2({
  name: "up",
  options: {
    config: optionConfig,
    dialect: optionDialect,
    out: optionOut
  },
  transform: async (opts) => {
    const from = assertCollisions("check", opts, [], ["dialect", "out"]);
    return prepareCheckParams(opts, from);
  },
  handler: async (config) => {
    await assertOrmCoreVersion();
    const { out, dialect: dialect6 } = config;
    await assertPackages("drizzle-orm");
    if (dialect6 === "postgresql") {
      upPgHandler(out);
    }
    if (dialect6 === "mysql") {
      upMysqlHandler(out);
    }
    if (dialect6 === "sqlite" || dialect6 === "turso") {
      upSqliteHandler(out);
    }
    if (dialect6 === "singlestore") {
      upSinglestoreHandler(out);
    }
  }
});
var pull = command2({
  name: "introspect",
  aliases: ["pull"],
  options: {
    config: optionConfig,
    dialect: optionDialect,
    out: optionOut,
    breakpoints: optionBreakpoints,
    casing: string("introspect-casing").enum("camel", "preserve"),
    ...optionsFilters,
    ...optionsDatabaseCredentials
  },
  transform: async (opts) => {
    const from = assertCollisions(
      "introspect",
      opts,
      [],
      [
        "dialect",
        "driver",
        "out",
        "url",
        "host",
        "port",
        "user",
        "password",
        "database",
        "ssl",
        "authToken",
        "casing",
        "breakpoints",
        "tablesFilter",
        "schemaFilters",
        "extensionsFilters"
      ]
    );
    return preparePullConfig(opts, from);
  },
  handler: async (config) => {
    await assertPackages("drizzle-orm");
    await assertOrmCoreVersion();
    const {
      dialect: dialect6,
      credentials: credentials2,
      out,
      casing: casing2,
      breakpoints,
      tablesFilter,
      schemasFilter,
      prefix: prefix2,
      entities
    } = config;
    (0, import_fs13.mkdirSync)(out, { recursive: true });
    console.log(
      grey(
        `Pulling from [${schemasFilter.map((it) => `'${it}'`).join(", ")}] list of schemas`
      )
    );
    console.log();
    try {
      if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { introspectPostgres: introspectPostgres2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectPostgres2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          schemasFilter,
          prefix2,
          entities
        );
      } else if (dialect6 === "mysql") {
        const { introspectMysql: introspectMysql2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectMysql2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else if (dialect6 === "sqlite") {
        const { introspectSqlite: introspectSqlite2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectSqlite2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else if (dialect6 === "turso") {
        const { introspectLibSQL: introspectLibSQL2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectLibSQL2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else if (dialect6 === "singlestore") {
        const { introspectSingleStore: introspectSingleStore2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
        await introspectSingleStore2(
          casing2,
          out,
          breakpoints,
          credentials2,
          tablesFilter,
          prefix2
        );
      } else {
        assertUnreachable(dialect6);
      }
    } catch (e2) {
      console.error(e2);
    }
    process.exit(0);
  }
});
var drop = command2({
  name: "drop",
  options: {
    config: optionConfig,
    out: optionOut,
    driver: optionDriver
  },
  transform: async (opts) => {
    const from = assertCollisions("check", opts, [], ["driver", "out"]);
    return prepareDropParams(opts, from);
  },
  handler: async (config) => {
    await assertOrmCoreVersion();
    assertV1OutFolder(config.out);
    await dropMigration(config);
  }
});
var studio = command2({
  name: "studio",
  options: {
    config: optionConfig,
    port: number().desc("Custom port for drizzle studio [default=4983]"),
    host: string().desc("Custom host for drizzle studio [default=0.0.0.0]"),
    verbose: boolean().default(false).desc("Print all stataments that are executed by Studio")
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    assertStudioNodeVersion();
    const {
      dialect: dialect6,
      schema: schemaPath,
      port,
      host,
      credentials: credentials2
    } = await prepareStudioConfig(opts);
    const {
      drizzleForPostgres: drizzleForPostgres2,
      preparePgSchema: preparePgSchema2,
      prepareMySqlSchema: prepareMySqlSchema2,
      drizzleForMySQL: drizzleForMySQL2,
      prepareSQLiteSchema: prepareSQLiteSchema2,
      drizzleForSQLite: drizzleForSQLite2,
      prepareSingleStoreSchema: prepareSingleStoreSchema2,
      drizzleForSingleStore: drizzleForSingleStore2,
      drizzleForLibSQL: drizzleForLibSQL2
    } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
    let setup;
    try {
      if (dialect6 === "postgresql") {
        if ("driver" in credentials2) {
          const { driver: driver2 } = credentials2;
          if (driver2 === "aws-data-api") {
            if (!await ormVersionGt("0.30.10")) {
              console.log(
                "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else if (driver2 === "pglite") {
            if (!await ormVersionGt("0.30.6")) {
              console.log(
                "To use 'pglite' driver - please update drizzle-orm to the latest version"
              );
              process.exit(1);
            }
          } else {
            assertUnreachable(driver2);
          }
        }
        const { schema: schema6, relations: relations4, files } = schemaPath ? await preparePgSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForPostgres2(credentials2, schema6, relations4, files);
      } else if (dialect6 === "mysql") {
        const { schema: schema6, relations: relations4, files } = schemaPath ? await prepareMySqlSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForMySQL2(credentials2, schema6, relations4, files);
      } else if (dialect6 === "sqlite") {
        const { schema: schema6, relations: relations4, files } = schemaPath ? await prepareSQLiteSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForSQLite2(credentials2, schema6, relations4, files);
      } else if (dialect6 === "turso") {
        const { schema: schema6, relations: relations4, files } = schemaPath ? await prepareSQLiteSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForLibSQL2(credentials2, schema6, relations4, files);
      } else if (dialect6 === "singlestore") {
        const { schema: schema6, relations: relations4, files } = schemaPath ? await prepareSingleStoreSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
        setup = await drizzleForSingleStore2(
          credentials2,
          schema6,
          relations4,
          files
        );
      } else {
        assertUnreachable(dialect6);
      }
      const { prepareServer: prepareServer2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
      const server = await prepareServer2(setup);
      console.log();
      console.log(
        withStyle.fullWarning(
          "Drizzle Studio is currently in Beta. If you find anything that is not working as expected or should be improved, feel free to create an issue on GitHub: https://github.com/drizzle-team/drizzle-kit-mirror/issues/new or write to us on Discord: https://discord.gg/WcRKz2FFxN"
        )
      );
      const { key, cert } = await certs() || {};
      server.start({
        host,
        port,
        key,
        cert,
        cb: (err2, address) => {
          if (err2) {
            console.error(err2);
          } else {
            const queryParams = {};
            if (port !== 4983) {
              queryParams.port = port;
            }
            if (host !== "127.0.0.1") {
              queryParams.host = host;
            }
            const queryString = Object.keys(queryParams).map((key2) => {
              return `${key2}=${queryParams[key2]}`;
            }).join("&");
            console.log(
              `
Drizzle Studio is up and running on ${source_default.blue(
                `https://local.drizzle.studio${queryString ? `?${queryString}` : ""}`
              )}`
            );
          }
        }
      });
    } catch (e2) {
      console.error(e2);
      process.exit(0);
    }
  }
});
var exportRaw = command2({
  name: "export",
  desc: "Generate diff between current state and empty state in specified formats: sql",
  options: {
    sql: boolean("sql").default(true).desc("Generate as sql"),
    config: optionConfig,
    dialect: optionDialect,
    schema: string().desc("Path to a schema file or folder")
  },
  transform: async (opts) => {
    const from = assertCollisions("export", opts, ["sql"], ["dialect", "schema"]);
    return prepareExportConfig(opts, from);
  },
  handler: async (opts) => {
    await assertOrmCoreVersion();
    await assertPackages("drizzle-orm");
    const {
      prepareAndExportPg: prepareAndExportPg2,
      prepareAndExportMysql: prepareAndExportMysql2,
      prepareAndExportSqlite: prepareAndExportSqlite2,
      prepareAndExportLibSQL: prepareAndExportLibSQL2,
      prepareAndExportSinglestore: prepareAndExportSinglestore2
    } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
    const dialect6 = opts.dialect;
    if (dialect6 === "postgresql") {
      await prepareAndExportPg2(opts);
    } else if (dialect6 === "mysql") {
      await prepareAndExportMysql2(opts);
    } else if (dialect6 === "sqlite") {
      await prepareAndExportSqlite2(opts);
    } else if (dialect6 === "turso") {
      await prepareAndExportLibSQL2(opts);
    } else if (dialect6 === "singlestore") {
      await prepareAndExportSinglestore2(opts);
    } else {
      assertUnreachable(dialect6);
    }
  }
});

// src/cli/index.ts
init_utils5();
var version2 = async () => {
  const { npmVersion } = await ormCoreVersions();
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
  const envVersion = "0.30.4";
  const kitVersion = envVersion ? `v${envVersion}` : "--";
  const versions = `drizzle-kit: ${kitVersion}
${ormVersion}`;
  console.log(source_default.gray(versions), "\n");
};
var legacyCommand = (name, newName) => {
  return command2({
    name,
    hidden: true,
    handler: () => {
      console.log(
        `This command is deprecated, please use updated '${newName}' command (see https://orm.drizzle.team/kit-docs/upgrade-21#how-to-migrate-to-0210)`
      );
    }
  });
};
var legacy = [
  legacyCommand("generate:pg", "generate"),
  legacyCommand("generate:mysql", "generate"),
  legacyCommand("generate:sqlite", "generate"),
  legacyCommand("push:pg", "push"),
  legacyCommand("push:mysql", "push"),
  legacyCommand("push:sqlite", "push"),
  legacyCommand("introspect:pg", "introspect"),
  legacyCommand("introspect:mysql", "introspect"),
  legacyCommand("introspect:sqlite", "introspect"),
  legacyCommand("up:pg", "up"),
  legacyCommand("up:mysql", "up"),
  legacyCommand("up:sqlite", "up"),
  legacyCommand("check:pg", "check"),
  legacyCommand("check:mysql", "check"),
  legacyCommand("check:sqlite", "check")
];
run([generate, migrate, pull, push, studio, up, check, drop, exportRaw, ...legacy], {
  name: "drizzle-kit",
  version: version2
});
/*! Bundled license information:

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> *)
*/
