/
ai_sampletext
/
DiplomWork
Обзор
Документация
Войти
/
ai_sampletext
/
DiplomWork
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
node_modules/drizzle-kit/bin.cjs
94 520 строк
4 MB
boolyshareyo
Initial commit
08 июн 2026, 16:00
08 июн 2026, 16:00
6216a29
Код
Авторство
О чём код?
#!/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.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js function assembleStyles() { const codes = /* @__PURE__ */ new Map(); for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\x1B[${style[0]}m`, close: `\x1B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, "codes", { value: codes, enumerable: false }); styles.color.close = "\x1B[39m"; styles.bgColor.close = "\x1B[49m"; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); Object.defineProperties(styles, { rgbToAnsi256: { value(red, green, blue) { if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round((red - 8) / 247 * 24) + 232; } return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); }, enumerable: false }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map((character) => character + character).join(""); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ integer >> 16 & 255, integer >> 8 & 255, integer & 255 /* eslint-enable no-bitwise */ ]; }, enumerable: false }, hexToAnsi256: { value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = ((code - 232) * 10 + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = remainder % 6 / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false }, hexToAnsi: { value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false } }); return styles; } var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default; var init_ansi_styles = __esm({ "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js"() { ANSI_BACKGROUND_OFFSET = 10; wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`; wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`; wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`; styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; modifierNames = Object.keys(styles.modifier); foregroundColorNames = Object.keys(styles.color); backgroundColorNames = Object.keys(styles.bgColor); colorNames = [...foregroundColorNames, ...backgroundColorNames]; ansiStyles = assembleStyles(); ansi_styles_default = ansiStyles; } }); // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) { const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; const position = argv.indexOf(prefix2 + flag); const terminatorPosition = argv.indexOf("--"); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } function envForceColor() { if ("FORCE_COLOR" in env) { if (env.FORCE_COLOR === "true") { return 1; } if (env.FORCE_COLOR === "false") { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== void 0) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { return 3; } if (hasFlag("color=256")) { return 2; } } if ("TF_BUILD" in env && "AGENT_NAME" in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === void 0) { return 0; } const min = forceColor || 0; if (env.TERM === "dumb") { return min; } if (import_node_process.default.platform === "win32") { const osRelease = import_node_os.default.release().split("."); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ("CI" in env) { if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) { return 3; } if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { return 1; } return min; } if ("TEAMCITY_VERSION" in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === "truecolor") { return 3; } if (env.TERM === "xterm-kitty") { return 3; } if ("TERM_PROGRAM" in env) { const 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.4.1/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.4.1/node_modules/chalk/source/utilities.js function stringReplaceAll(string2, substring, replacer) { let index6 = string2.indexOf(substring); if (index6 === -1) { return string2; } const substringLength = substring.length; let endIndex = 0; let returnValue = ""; do { returnValue += string2.slice(endIndex, index6) + substring + replacer; endIndex = index6 + substringLength; index6 = string2.indexOf(substring, endIndex); } while (index6 !== -1); returnValue += string2.slice(endIndex); return returnValue; } function stringEncaseCRLFWithFirstIndex(string2, prefix2, postfix, index6) { let endIndex = 0; let returnValue = ""; do { const gotCR = string2[index6 - 1] === "\r"; returnValue += string2.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix; endIndex = index6 + 1; index6 = string2.indexOf("\n", endIndex); } while (index6 !== -1); returnValue += string2.slice(endIndex); return returnValue; } var init_utilities = __esm({ "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js"() { } }); // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js function createChalk(options) { return chalkFactory(options); } var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default; var init_source = __esm({ "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js"() { 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.5.0/node_modules/dotenv/package.json var require_package = __commonJS({ "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json"(exports2, module2) { module2.exports = { name: "dotenv", version: "16.5.0", description: "Loads environment variables from .env file", main: "lib/main.js", types: "lib/main.d.ts", exports: { ".": { types: "./lib/main.d.ts", require: "./lib/main.js", default: "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }, scripts: { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", pretest: "npm run lint && npm run dts-check", test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000", "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov", prerelease: "npm test", release: "standard-version" }, repository: { type: "git", url: "git://github.com/motdotla/dotenv.git" }, homepage: "https://github.com/motdotla/dotenv#readme", funding: "https://dotenvx.com", keywords: [ "dotenv", "env", ".env", "environment", "variables", "config", "settings" ], readmeFilename: "README.md", license: "BSD-2-Clause", devDependencies: { "@types/node": "^18.11.3", decache: "^4.6.2", sinon: "^14.0.1", standard: "^17.0.0", "standard-version": "^9.5.0", tap: "^19.2.0", typescript: "^4.8.4" }, engines: { node: ">=12" }, browser: { fs: false } }; } }); // ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/main.js var require_main = __commonJS({ "../node_modules/.pnpm/dotenv@16.5.0/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 parse4(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 i4 = 0; i4 < length; i4++) { try { const key = keys[i4].trim(); const attrs = _instructions(result, key); decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); break; } catch (error2) { if (i4 + 1 >= length) { throw error2; } } } return DotenvModule.parse(decrypted); } 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) { const debug = Boolean(options && options.debug); if (debug) { _debug("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 (e4) { if (debug) { _debug(`Failed to load ${path5} ${e4.message}`); } lastError = e4; } } 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: parse4, 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.5.0/node_modules/dotenv/lib/env-options.js var require_env_options = __commonJS({ "../node_modules/.pnpm/dotenv@16.5.0/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.5.0/node_modules/dotenv/lib/cli-options.js var require_cli_options = __commonJS({ "../node_modules/.pnpm/dotenv@16.5.0/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(x4, y2) { if (!y2) return `${CSI}${x4 + 1}G`; return `${CSI}${y2 + 1};${x4 + 1}H`; }, move(x4, y2) { let ret = ""; if (x4 < 0) ret += `${CSI}${-x4}D`; else if (x4 > 0) ret += `${CSI}${x4}C`; if (y2 < 0) ret += `${CSI}${-y2}A`; else if (y2 > 0) ret += `${CSI}${y2}B`; return ret; }, up: (count = 1) => `${CSI}${count}A`, down: (count = 1) => `${CSI}${count}B`, forward: (count = 1) => `${CSI}${count}C`, backward: (count = 1) => `${CSI}${count}D`, nextLine: (count = 1) => `${CSI}E`.repeat(count), prevLine: (count = 1) => `${CSI}F`.repeat(count), left: `${CSI}G`, hide: `${CSI}?25l`, show: `${CSI}?25h`, save: `${ESC}7`, restore: `${ESC}8` }; var scroll = { up: (count = 1) => `${CSI}S`.repeat(count), down: (count = 1) => `${CSI}T`.repeat(count) }; var erase = { screen: `${CSI}2J`, up: (count = 1) => `${CSI}1J`.repeat(count), down: (count = 1) => `${CSI}J`.repeat(count), line: `${CSI}2K`, lineEnd: `${CSI}K`, lineStart: `${CSI}1K`, lines(count) { let clear = ""; for (let i4 = 0; i4 < count; i4++) clear += this.line + (i4 < count - 1 ? cursor.up() : ""); if (count) clear += cursor.left; return clear; } }; module2.exports = { cursor, scroll, erase, beep }; } }); // ../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 isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; } function toNumber(value) { if (typeof value == "number") { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == "function" ? value.valueOf() : value; value = isObject(other) ? other + "" : other; } if (typeof value != "string") { return value === 0 ? value : +value; } value = value.replace(reTrim, ""); var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } module2.exports = throttle; } }); // ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js var require_hanji = __commonJS({ "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports2) { "use strict"; var __awaiter2 = 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 (e4) { reject(e4); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e4) { reject(e4); } } function step(result) { result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault2 = 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 = __importDefault2(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(view5, stdin, stdout, closable) { this.view = view5; this.stdin = stdin; this.stdout = stdout; this.closable = closable; this.text = ""; this.status = "idle"; if (this.stdin.isTTY) this.stdin.setRawMode(true); const keypress = (str, key) => { if (key.name === "c" && key.ctrl === true) { this.requestLayout(); this.view.detach(this); this.tearDown(keypress); if (terminateHandler) { terminateHandler(this.stdin, this.stdout); return; } this.stdout.write(` ^C `); process.exit(1); } if (key.name === "escape") { this.status = "aborted"; this.requestLayout(); this.view.detach(this); this.tearDown(keypress); this.resolve({ status: "aborted", data: void 0 }); return; } if (key.name === "return") { this.status = "submitted"; this.requestLayout(); this.view.detach(this); this.tearDown(keypress); this.resolve({ status: "submitted", data: this.view.result() }); return; } view5.input(str, key); }; this.stdin.on("keypress", keypress); this.view.attach(this); const { resolve: 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(state2) { if (state2 === "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(view5, stdout) { this.view = view5; 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(view5) { const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)(); if (view5 instanceof Prompt3) { const terminal = new Terminal(view5, stdin, stdout, closable); terminal.requestLayout(); return terminal.result(); } stdout.write(`${view5} `); closable.close(); return; } exports2.render = render10; function renderWithTask7(view5, task) { return __awaiter2(this, void 0, void 0, function* () { const terminal = new TaskTerminal(view5, process.stdout); terminal.requestLayout(); const result = yield task; terminal.clear(); return result; }); } exports2.renderWithTask = renderWithTask7; var terminateHandler; function onTerminate(callback) { terminateHandler = callback; } exports2.onTerminate = onTerminate; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js var util, objectUtil, ZodParsedType, getParsedType; var init_util = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js"() { (function(util2) { util2.assertEqual = (_3) => { }; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number"); const filtered = {}; for (const k3 of validKeys) { filtered[k3] = obj[k3]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e4) { return obj[e4]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2; function joinValues(array2, separator = " | ") { return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_3, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); getParsedType = (data) => { const t4 = typeof data; switch (t4) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js var ZodIssueCode, quotelessJson, ZodError; var init_ZodError = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js"() { init_util(); ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; ZodError = class _ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error2) => { for (const issue of error2.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i4 = 0; while (i4 < issue.path.length) { const el = issue.path[i4]; const terminal = i4 === 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]; i4++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError.create = (issues) => { const error2 = new ZodError(issues); return error2; }; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js var errorMap, en_default; var init_en = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js"() { init_ZodError(); init_util(); errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; en_default = errorMap; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js function setErrorMap(map2) { overrideErrorMap = map2; } function getErrorMap() { return overrideErrorMap; } var overrideErrorMap; var init_errors = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js"() { init_en(); overrideErrorMap = en_default; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === en_default ? void 0 : en_default // then global default map ].filter((x4) => !!x4) }); ctx.common.issues.push(issue); } var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync; var init_parseUtil = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js"() { init_errors(); init_en(); 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((m4) => !!m4).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; EMPTY_PATH = []; ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s4 of results) { if (s4.status === "aborted") return INVALID; if (s4.status === "dirty") status.dirty(); arrayValue.push(s4.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 = (x4) => x4.status === "aborted"; isDirty = (x4) => x4.status === "dirty"; isValid = (x4) => x4.status === "valid"; isAsync = (x4) => typeof Promise !== "undefined" && x4 instanceof Promise; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js var init_typeAliases = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js"() { } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js var errorUtil; var init_errorUtil = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js"() { (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message; })(errorUtil || (errorUtil = {})); } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } function timeRegexSource(args) { let secondsRegexSource = `[0-5]\\d`; if (args.precision) { secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } else if (args.precision == null) { secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } const secondsQuantifier = args.precision ? "+" : "?"; return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } function isValidIP(ip, version3) { if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) { return true; } if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT(jwt, alg) { if (!jwtRegex.test(jwt)) return false; try { const [header] = jwt.split("."); const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base64)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version3) { if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) { return true; } if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) { return true; } return false; } function floatSafeRemainder(val2, step) { const valDecCount = (val2.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / 10 ** decCount; } function deepPartialify(schema6) { if (schema6 instanceof ZodObject) { const newShape = {}; for (const key in schema6.shape) { const fieldSchema = schema6.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema6._def, shape: () => newShape }); } else if (schema6 instanceof ZodArray) { return new ZodArray({ ...schema6._def, type: deepPartialify(schema6.element) }); } else if (schema6 instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema6.unwrap())); } else if (schema6 instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema6.unwrap())); } else if (schema6 instanceof ZodTuple) { return ZodTuple.create(schema6.items.map((item) => deepPartialify(item))); } else { return schema6; } } function mergeValues(a3, b3) { const aType = getParsedType(a3); const bType = getParsedType(b3); if (a3 === b3) { return { valid: true, data: a3 }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b3); const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a3, ...b3 }; for (const key of sharedKeys) { const sharedValue = mergeValues(a3[key], b3[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 (a3.length !== b3.length) { return { valid: false }; } const newArray = []; for (let index6 = 0; index6 < a3.length; index6++) { const itemA = a3[index6]; const itemB = b3[index6]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b3) { return { valid: true, data: a3 }; } else { return { valid: false }; } } function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } function cleanParams(params, data) { const p3 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const p22 = typeof p3 === "string" ? { message: p3 } : p3; return p22; } function custom(check2, _params = {}, fatal) { if (check2) return ZodAny.create().superRefine((data, ctx) => { const r4 = check2(data); if (r4 instanceof Promise) { return r4.then((r5) => { if (!r5) { const params = cleanParams(_params, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } }); } if (!r4) { const params = cleanParams(_params, data); const _fatal = params.fatal ?? fatal ?? true; ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } return; }); return ZodAny.create(); } var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER; var init_types = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js"() { init_ZodError(); init_errors(); init_errorUtil(); init_parseUtil(); init_util(); 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 (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error2 = new ZodError(ctx.common.issues); this._error = error2; return this._error; } }; } }; ZodType = class { get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { const ctx = { common: { issues: [], async: (params == null ? void 0 : params.async) ?? false, contextualErrorMap: params == null ? void 0 : params.errorMap }, path: (params == null ? 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); } "~validate"(data) { var _a2, _b; const ctx = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; if (!this["~standard"].async) { try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; } catch (err2) { if ((_b = (_a2 = err2 == null ? void 0 : err2.message) == null ? void 0 : _a2.toLowerCase()) == null ? void 0 : _b.includes("encountered")) { this["~standard"].async = true; } ctx.common = { issues: [], async: true }; } } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params == null ? void 0 : params.errorMap, async: true }, path: (params == null ? 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); } constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data) }; } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; cuidRegex = /^c[^\s-]{8,}$/i; cuid2Regex = /^[0-9a-z]+$/; ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; nanoidRegex = /^[a-z0-9_-]{21}$/i; jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; dateRegex = new RegExp(`^${dateRegexSource}$`); ZodString = class _ZodString extends ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.length < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.length > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "length") { const tooBig = input.data.length > check2.value; const tooSmall = input.data.length < check2.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } status.dirty(); } } else if (check2.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "url") { try { new URL(input.data); } catch { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "regex") { check2.regex.lastIndex = 0; const testResult = check2.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "trim") { input.data = input.data.trim(); } else if (check2.kind === "includes") { if (!input.data.includes(check2.value, check2.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check2.value, position: check2.position }, message: check2.message }); status.dirty(); } } else if (check2.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check2.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check2.kind === "startsWith") { if (!input.data.startsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "endsWith") { if (!input.data.endsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "datetime") { const 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 === "jwt") { if (!isValidJWT(input.data, check2.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cidr") { if (!isValidCidr(input.data, check2.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode.invalid_string, message: check2.message }); status.dirty(); } } else { 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) }); } base64url(message) { return this._addCheck({ kind: "base64url", ...errorUtil.errToObj(message) }); } jwt(options) { return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } cidr(options) { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision, offset: (options == null ? void 0 : options.offset) ?? false, local: (options == null ? void 0 : options.local) ?? false, ...errorUtil.errToObj(options == null ? 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 ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision, ...errorUtil.errToObj(options == null ? 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 ? void 0 : options.position, ...errorUtil.errToObj(options == null ? 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) }); } /** * Equivalent to `.min(1)` */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new _ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isCIDR() { return !!this._def.checks.find((ch) => ch.kind === "cidr"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get isBase64url() { return !!this._def.checks.find((ch) => ch.kind === "base64url"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodString.create = (params) => { return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (params == null ? void 0 : params.coerce) ?? false, ...processCreateParams(params) }); }; ZodNumber = class _ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const 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; let min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } }; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params == null ? 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) { try { input.data = BigInt(input.data); } catch { return this._getInvalidInput(input); } } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = void 0; const status = new ParseStatus(); for (const 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 }; } _getInvalidInput(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType }); return INVALID; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check2) { return new _ZodBigInt({ ...this._def, checks: [...this._def.checks, check2] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodBigInt.create = (params) => { return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (params == null ? void 0 : params.coerce) ?? false, ...processCreateParams(params) }); }; ZodBoolean = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params == null ? 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 (Number.isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.getTime() < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check2.message, inclusive: true, exact: false, minimum: check2.value, type: "date" }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.getTime() > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check2.message, inclusive: true, exact: false, maximum: check2.value, type: "date" }); status.dirty(); } } else { 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 ? 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, i4) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i4)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i4) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i4)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new _ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new _ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new _ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray.create = (schema6, params) => { return new ZodArray({ type: schema6, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; ZodObject = class _ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse( new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new _ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue, ctx) => { var _a2, _b; const defaultError = ((_b = (_a2 = this._def).errorMap) == null ? void 0 : _b.call(_a2, issue, ctx).message) ?? ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new _ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new _ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // <Def extends ZodObjectDef>(def: Def) => // <Augmentation extends ZodRawShape>( // augmentation: Augmentation // ): ZodObject< // extendShape<ReturnType<Def["shape"]>, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema6) { return this.augment({ [key]: schema6 }); } // merge<Incoming extends AnyZodObject>( // merging: Incoming // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => { // ZodObject< // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index6) { return new _ZodObject({ ...this._def, catchall: index6 }); } pick(mask) { const shape = {}; for (const key of util.objectKeys(mask)) { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; for (const key of util.objectKeys(this.shape)) { if (!mask[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new _ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } } return new _ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion.create = (types3, params) => { return new ZodUnion({ options: types3, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; getDiscriminator = (type) => { if (type instanceof ZodLazy) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral) { return [type.value]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { return util.objectValues(type.enum); } else if (type instanceof ZodDefault) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined) { return [void 0]; } else if (type instanceof ZodNull) { return [null]; } else if (type instanceof ZodOptional) { return [void 0, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch) { return getDiscriminator(type._def.innerType); } else { return []; } }; ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new _ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; ZodIntersection = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; ZodTuple = class _ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema6 = this._def.items[itemIndex] || this._def.rest; if (!schema6) return null; return schema6._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x4) => !!x4); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new _ZodTuple({ ...this._def, rest }); } }; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; ZodRecord = class _ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new _ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new _ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; ZodMap = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index6) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; ZodSet = class _ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i4) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i4))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new _ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new _ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; ZodFunction = class _ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error2) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x4) => !!x4), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error2 } }); } function makeReturnsIssue(returns, error2) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x4) => !!x4), 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((e4) => { error2.addIssue(makeArgsIssue(args, e4)); throw error2; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e4) => { error2.addIssue(makeReturnsIssue(result, e4)); throw error2; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new _ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()) }); } returns(returnType) { return new _ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new _ZodFunction({ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; ZodLiteral = class extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; ZodEnum = class _ZodEnum extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(this._def.values); } if (!this._cache.has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val2 of this._def.values) { enumValues[val2] = val2; } return enumValues; } get Values() { const enumValues = {}; for (const val2 of this._def.values) { enumValues[val2] = val2; } return enumValues; } get Enum() { const enumValues = {}; for (const val2 of this._def.values) { enumValues[val2] = val2; } return enumValues; } extract(values, newDef = this._def) { return _ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } }; ZodEnum.create = createZodEnum; ZodNativeEnum = class extends ZodType { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(util.getValidEnumValues(this._def.values)); } if (!this._cache.has(input.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } }; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; ZodPromise = class extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; ZodPromise.create = (schema6, params) => { return new ZodPromise({ type: schema6, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; ZodEffects = class extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base)) return INVALID; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return INVALID; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema6, effect, params) => { return new ZodEffects({ schema: schema6, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess, schema6, params) => { return new ZodEffects({ schema: schema6, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; ZodOptional = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; ZodNullable = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; ZodDefault = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } }; ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; ZodCatch = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; ZodNaN = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } }; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; BRAND = Symbol("zod_brand"); ZodBranded = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; ZodPipeline = class _ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a3, b3) { return new _ZodPipeline({ in: a3, out: b3, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; ZodReadonly = class extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } }; ZodReadonly.create = (type, params) => { return new ZodReadonly({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; late = { object: ZodObject.lazycreate }; (function(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); stringType = ZodString.create; numberType = ZodNumber.create; nanType = ZodNaN.create; bigIntType = ZodBigInt.create; booleanType = ZodBoolean.create; dateType = ZodDate.create; symbolType = ZodSymbol.create; undefinedType = ZodUndefined.create; nullType = ZodNull.create; anyType = ZodAny.create; unknownType = ZodUnknown.create; neverType = ZodNever.create; voidType = ZodVoid.create; arrayType = ZodArray.create; objectType = ZodObject.create; strictObjectType = ZodObject.strictCreate; unionType = ZodUnion.create; discriminatedUnionType = ZodDiscriminatedUnion.create; intersectionType = ZodIntersection.create; tupleType = ZodTuple.create; recordType = ZodRecord.create; mapType = ZodMap.create; setType = ZodSet.create; functionType = ZodFunction.create; lazyType = ZodLazy.create; literalType = ZodLiteral.create; enumType = ZodEnum.create; nativeEnumType = ZodNativeEnum.create; promiseType = ZodPromise.create; effectsType = ZodEffects.create; optionalType = ZodOptional.create; nullableType = ZodNullable.create; preprocessType = ZodEffects.createWithPreprocess; pipelineType = ZodPipeline.create; ostring = () => stringType().optional(); onumber = () => numberType().optional(); oboolean = () => booleanType().optional(); coerce = { string: (arg) => ZodString.create({ ...arg, coerce: true }), number: (arg) => ZodNumber.create({ ...arg, coerce: true }), boolean: (arg) => ZodBoolean.create({ ...arg, coerce: true }), bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), date: (arg) => ZodDate.create({ ...arg, coerce: true }) }; NEVER = INVALID; } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js var external_exports = {}; __export(external_exports, { BRAND: () => BRAND, DIRTY: () => DIRTY, EMPTY_PATH: () => EMPTY_PATH, INVALID: () => INVALID, NEVER: () => NEVER, OK: () => OK, ParseStatus: () => ParseStatus, Schema: () => ZodType, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBigInt: () => ZodBigInt, ZodBoolean: () => ZodBoolean, ZodBranded: () => ZodBranded, ZodCatch: () => ZodCatch, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodEffects: () => ZodEffects, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNativeEnum: () => ZodNativeEnum, ZodNever: () => ZodNever, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodParsedType: () => ZodParsedType, ZodPipeline: () => ZodPipeline, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRecord: () => ZodRecord, ZodSchema: () => ZodType, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodSymbol: () => ZodSymbol, ZodTransformer: () => ZodEffects, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, addIssueToContext: () => addIssueToContext, any: () => anyType, array: () => arrayType, bigint: () => bigIntType, boolean: () => booleanType, coerce: () => coerce, custom: () => custom, date: () => dateType, datetimeRegex: () => datetimeRegex, defaultErrorMap: () => en_default, discriminatedUnion: () => discriminatedUnionType, effect: () => effectsType, enum: () => enumType, function: () => functionType, getErrorMap: () => getErrorMap, getParsedType: () => getParsedType, instanceof: () => instanceOfType, intersection: () => intersectionType, isAborted: () => isAborted, isAsync: () => isAsync, isDirty: () => isDirty, isValid: () => isValid, late: () => late, lazy: () => lazyType, literal: () => literalType, makeIssue: () => makeIssue, map: () => mapType, nan: () => nanType, nativeEnum: () => nativeEnumType, never: () => neverType, null: () => nullType, nullable: () => nullableType, number: () => numberType, object: () => objectType, objectUtil: () => objectUtil, oboolean: () => oboolean, onumber: () => onumber, optional: () => optionalType, ostring: () => ostring, pipeline: () => pipelineType, preprocess: () => preprocessType, promise: () => promiseType, quotelessJson: () => quotelessJson, record: () => recordType, set: () => setType, setErrorMap: () => setErrorMap, strictObject: () => strictObjectType, string: () => stringType, symbol: () => symbolType, transformer: () => effectsType, tuple: () => tupleType, undefined: () => undefinedType, union: () => unionType, unknown: () => unknownType, util: () => util, void: () => voidType }); var init_external = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js"() { init_errors(); init_parseUtil(); init_typeAliases(); init_util(); init_types(); init_ZodError(); } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js var init_v3 = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js"() { init_external(); init_external(); } }); // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js var init_esm = __esm({ "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js"() { init_v3(); init_v3(); } }); // src/global.ts function assertUnreachable(x4) { throw new Error("Didn't expect to get here"); } function softAssertUnreachable(x4) { 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, map2) => { const result = Object.keys(obj).reduce(function(result2, key) { result2[key] = map2(obj[key]); return result2; }, {}); return result; }; mapKeys = (obj, map2) => { const result = Object.fromEntries( Object.entries(obj).map(([key, val2]) => { const newKey = map2(key, val2); return [newKey, val2]; }) ); return result; }; mapEntries = (obj, map2) => { const result = Object.fromEntries( Object.entries(obj).map(([key, val2]) => { const [newKey, newVal] = map2(key, val2); return [newKey, newVal]; }) ); return result; }; customMapEntries = (obj, map2) => { const result = Object.fromEntries( Object.entries(obj).map(([key, val2]) => { const [newKey, newVal] = map2(key, val2); return [newKey, newVal]; }) ); return result; }; } }); // 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_esm(); 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: (fk5) => { return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`; }, unsquashFK: (input) => { const [ name, tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete ] = input.split(";"); const result = 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: (view5) => { return `${view5.algorithm};${view5.sqlSecurity};${view5.withCheckOption}`; }, unsquashView: (meta) => { const [algorithm, sqlSecurity, withCheckOption] = meta.split(";"); const toReturn = { algorithm, sqlSecurity, withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0 }; return viewMeta.parse(toReturn); } }; squashMysqlScheme = (json) => { const mappedTables = Object.fromEntries( Object.entries(json.tables).map((it) => { const squashedIndexes = mapValues(it[1].indexes, (index6) => { return MySqlSquasher.squashIdx(index6); }); const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => { return MySqlSquasher.squashFK(fk5); }); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return MySqlSquasher.squashPK(pk); }); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return MySqlSquasher.squashUnique(unq); } ); const squashedCheckConstraints = mapValues(it[1].checkConstraint, (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_esm(); indexV2 = objectType({ name: stringType(), columns: recordType( stringType(), objectType({ name: stringType() }) ), isUnique: booleanType() }).strict(); columnV2 = objectType({ name: stringType(), type: stringType(), primaryKey: booleanType(), notNull: booleanType(), default: anyType().optional(), references: stringType().optional() }).strict(); tableV2 = objectType({ name: stringType(), columns: recordType(stringType(), columnV2), indexes: recordType(stringType(), indexV2) }).strict(); 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( (c3) => `${c3.expression}--${c3.isExpression}--${c3.asc}--${c3.nulls}--${c3.opclass ? c3.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 column11 of columnString) { const [expression, isExpression, asc, nulls, opclass] = column11.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((c3) => `${c3.isExpression ? "" : c3.expression}--${c3.asc}--${c3.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 column11 of columnString) { const [expression, asc, nulls, opclass] = column11.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: (fk5) => { return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""};${fk5.schemaTo || "public"}`; }, squashPolicy: (policy5) => { var _a2; return `${policy5.name}--${policy5.as}--${policy5.for}--${(_a2 = policy5.to) == null ? void 0 : _a2.join(",")}--${policy5.using}--${policy5.withCheck}--${policy5.on}`; }, unsquashPolicy: (policy5) => { const splitted = policy5.split("--"); return { name: splitted[0], as: splitted[1], for: splitted[2], to: splitted[3].split(","), using: splitted[4] !== "undefined" ? splitted[4] : void 0, withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0, on: splitted[6] !== "undefined" ? splitted[6] : void 0 }; }, squashPolicyPush: (policy5) => { var _a2; return `${policy5.name}--${policy5.as}--${policy5.for}--${(_a2 = policy5.to) == null ? void 0 : _a2.join(",")}--${policy5.on}`; }, unsquashPolicyPush: (policy5) => { const splitted = policy5.split("--"); return { name: splitted[0], as: splitted[1], for: splitted[2], to: splitted[3].split(","), on: splitted[4] !== "undefined" ? splitted[4] : void 0 }; }, squashPK: (pk) => { return `${pk.columns.join(",")};${pk.name}`; }, unsquashPK: (pk) => { const splitted = pk.split(";"); return { name: splitted[1], columns: splitted[0].split(",") }; }, squashUnique: (unq) => { return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`; }, unsquashUnique: (unq) => { const [name, columns, nullsNotDistinct] = unq.split(";"); return { name, columns: columns.split(","), nullsNotDistinct: nullsNotDistinct === "true" }; }, unsquashFK: (input) => { const [ name, tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete, schemaTo ] = input.split(";"); const result = 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, (index6) => { return action === "push" ? PgSquasher.squashIdxPush(index6) : PgSquasher.squashIdx(index6); }); const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => { return PgSquasher.squashFK(fk5); }); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return PgSquasher.squashPK(pk); }); const mappedColumns = Object.fromEntries( Object.entries(it[1].columns).map((it2) => { const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0; return [ it2[0], { ...it2[1], identity: mappedIdentity } ]; }) ); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return PgSquasher.squashUnique(unq); } ); const squashedPolicies = mapValues(it[1].policies, (policy5) => { return action === "push" ? PgSquasher.squashPolicyPush(policy5) : PgSquasher.squashPolicy(policy5); }); const squashedChecksContraints = mapValues( it[1].checkConstraints, (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_esm(); 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, (index6) => { return SingleStoreSquasher.squashIdx(index6); }); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return SingleStoreSquasher.squashPK(pk); }); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return SingleStoreSquasher.squashUnique(unq); } ); return [ it[0], { name: it[1].name, columns: it[1].columns, indexes: squashedIndexes, compositePrimaryKeys: squashedPKs, uniqueConstraints: squashedUniqueConstraints } ]; }) ); return { version: "1", dialect: json.dialect, tables: mappedTables /* views: mappedViews, */ }; }; singlestoreSchema = schema2; singlestoreSchemaSquashed = schemaSquashed2; backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]); drySingleStore = singlestoreSchema.parse({ version: "1", dialect: "singlestore", id: originUUID, prevId: "", tables: {}, schemas: {}, /* views: {}, */ _meta: { schemas: {}, tables: {}, columns: {} } }); } }); // src/serializer/sqliteSchema.ts var 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_esm(); 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: (fk5) => { return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`; }, unsquashFK: (input) => { const [ name, tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete ] = input.split(";"); const result = fk3.parse({ name, tableFrom, columnsFrom: columnsFromStr.split(","), tableTo, columnsTo: columnsToStr.split(","), onUpdate, onDelete }); return result; }, squashPushFK: (fk5) => { return `${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`; }, unsquashPushFK: (input) => { const [ tableFrom, columnsFromStr, tableTo, columnsToStr, onUpdate, onDelete ] = input.split(";"); const result = 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, (index6) => { return SQLiteSquasher.squashIdx(index6); }); const squashedFKs = customMapEntries( it[1].foreignKeys, (key, value) => { return action === "push" ? [ SQLiteSquasher.squashPushFK(value), SQLiteSquasher.squashPushFK(value) ] : [key, SQLiteSquasher.squashFK(value)]; } ); const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => { return SQLiteSquasher.squashPK(pk); }); const squashedUniqueConstraints = mapValues( it[1].uniqueConstraints, (unq) => { return SQLiteSquasher.squashUnique(unq); } ); const squashedCheckConstraints = mapValues( it[1].checkConstraints, (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_esm(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore", "gel"]; dialect4 = enumType(dialects); commonSquashedSchema = unionType([ pgSchemaSquashed, mysqlSchemaSquashed, SQLiteSchemaSquashed, singlestoreSchemaSquashed ]); commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]); } }); // ../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((x4) => x4.trim()).filter((x4) => x4.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 index6 = 0; index6 < string2.length; index6++) { const character = string2[index6]; isLastLastCharPreserved = index6 > 2 ? string2[index6 - 3] === "-" : true; if (isLastCharLower && UPPERCASE.test(character)) { string2 = string2.slice(0, index6) + "-" + string2.slice(index6); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; index6++; } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) { string2 = string2.slice(0, index6 - 1) + "-" + string2.slice(index6 - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; } } return 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, (_3, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m4) => toUpperCase(m4)); }; } }); // 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((t4) => { const columnsCount = Object.values(t4.columns).length; const indexesCount = Object.values(t4.indexes).length; let foreignKeys = 0; if (schema6.dialect !== "singlestore") { foreignKeys = Object.values(t4.foreignKeys).length; } return `${source_default.bold.blue(t4.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((a3, b3) => { if (a3 > b3) { return a3; } return b3; }, 0); this.data.items.forEach((it, idx) => { const isSelected = idx === this.data.selectedIdx; const isRenamed = isRenamePromptItem(it); const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " "); const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`; text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`; text += idx != this.data.items.length - 1 ? "\n" : ""; }); return text; } result() { return this.data.items[this.data.selectedIdx]; } }; tableKey = (it) => { return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`; }; ResolveSelectNamed = class extends import_hanji.Prompt { constructor(base, data, entityType) { super(); this.base = base; this.entityType = entityType; this.on("attach", (terminal) => terminal.toggleCursor("hide")); this.state = new import_hanji.SelectState(data); this.state.bind(this); this.base = base; } render(status) { if (status === "submitted" || status === "aborted") { return ""; } const key = this.base.name; let text = ` Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}? `; const isSelectedRenamed = isRenamePromptItem( this.state.items[this.state.selectedIdx] ); const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F "); const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => { const it = _3; const keyFrom = it.from.name; return key.length + 3 + keyFrom.length; }).reduce((a3, b3) => { if (a3 > b3) { return a3; } return b3; }, 0); const entityType = this.entityType; this.state.items.forEach((it, idx) => { const isSelected = idx === this.state.selectedIdx; const isRenamed = isRenamePromptItem(it); const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " "); const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`; text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`; text += idx != this.state.items.length - 1 ? "\n" : ""; }); return text; } result() { return this.state.items[this.state.selectedIdx]; } }; ResolveSelect = class extends import_hanji.Prompt { constructor(base, data, entityType) { super(); this.base = base; this.entityType = entityType; this.on("attach", (terminal) => terminal.toggleCursor("hide")); this.state = new import_hanji.SelectState(data); this.state.bind(this); this.base = base; } render(status) { if (status === "submitted" || status === "aborted") { return ""; } const key = tableKey(this.base); let text = ` Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}? `; const isSelectedRenamed = isRenamePromptItem( this.state.items[this.state.selectedIdx] ); const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F "); const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => { const it = _3; const keyFrom = tableKey(it.from); return key.length + 3 + keyFrom.length; }).reduce((a3, b3) => { if (a3 > b3) { return a3; } return b3; }, 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((a3, b3) => { if (a3 > b3) { return a3; } return b3; }, 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((a3, b3) => { if (a3 > b3) { return a3; } return b3; }, 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, index6, limitLines) => { const limit = limitLines - 2; const sideLimit = Math.round(limit / 2); const endTrimmed = arr.length - sideLimit > index6; const startTrimmed = index6 > sideLimit - 1; const paddingStart = Math.max(index6 + sideLimit - arr.length, 0); const paddingEnd = Math.min(index6 - sideLimit + 1, 0); const d1 = endTrimmed ? 1 : 0; const d22 = startTrimmed ? 0 : 1; const start = Math.max(0, index6 - sideLimit + d1 - paddingStart); const end = Math.min(arr.length, index6 + sideLimit + d22 - paddingEnd); return { trimmed: arr.slice(start, end), offset: start, startTrimmed, endTrimmed }; }; } }); // src/serializer/gelSchema.ts var enumSchema2, enumSchemaV12, indexColumn2, index5, fk4, sequenceSchema2, roleSchema2, sequenceSquashed2, column5, checkConstraint4, columnSquashed2, compositePK5, uniqueConstraint5, policy2, policySquashed2, viewWithOption2, matViewWithOption2, mergedViewWithOption2, view4, table5, schemaHash5, kitInternals5, gelSchemaExternal, gelSchemaInternal, tableSquashed5, gelSchemaSquashed, gelSchema, backwardCompatibleGelSchema, dryGel; var init_gelSchema = __esm({ "src/serializer/gelSchema.ts"() { "use strict"; init_global(); init_esm(); enumSchema2 = objectType({ name: stringType(), schema: stringType(), values: stringType().array() }).strict(); enumSchemaV12 = objectType({ name: stringType(), values: recordType(stringType(), stringType()) }).strict(); indexColumn2 = objectType({ expression: stringType(), isExpression: booleanType(), asc: booleanType(), nulls: stringType().optional(), opclass: stringType().optional() }); index5 = objectType({ name: stringType(), columns: indexColumn2.array(), isUnique: booleanType(), with: recordType(stringType(), anyType()).optional(), method: stringType().default("btree"), where: stringType().optional(), concurrently: booleanType().default(false) }).strict(); fk4 = objectType({ name: stringType(), tableFrom: stringType(), columnsFrom: stringType().array(), tableTo: stringType(), schemaTo: stringType().optional(), columnsTo: stringType().array(), onUpdate: stringType().optional(), onDelete: stringType().optional() }).strict(); sequenceSchema2 = objectType({ name: stringType(), increment: stringType().optional(), minValue: stringType().optional(), maxValue: stringType().optional(), startWith: stringType().optional(), cache: stringType().optional(), cycle: booleanType().optional(), schema: stringType() }).strict(); roleSchema2 = objectType({ name: stringType(), createDb: booleanType().optional(), createRole: booleanType().optional(), inherit: booleanType().optional() }).strict(); sequenceSquashed2 = objectType({ name: stringType(), schema: stringType(), values: stringType() }).strict(); column5 = objectType({ name: stringType(), type: stringType(), typeSchema: stringType().optional(), primaryKey: booleanType(), notNull: booleanType(), default: anyType().optional(), isUnique: anyType().optional(), uniqueName: stringType().optional(), nullsNotDistinct: booleanType().optional(), generated: objectType({ type: literalType("stored"), as: stringType() }).optional(), identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional() }).strict(); checkConstraint4 = objectType({ name: stringType(), value: stringType() }).strict(); columnSquashed2 = objectType({ name: stringType(), type: stringType(), typeSchema: stringType().optional(), primaryKey: booleanType(), notNull: booleanType(), default: anyType().optional(), isUnique: anyType().optional(), uniqueName: stringType().optional(), nullsNotDistinct: booleanType().optional(), generated: objectType({ type: literalType("stored"), as: stringType() }).optional(), identity: stringType().optional() }).strict(); compositePK5 = objectType({ name: stringType(), columns: stringType().array() }).strict(); uniqueConstraint5 = objectType({ name: stringType(), columns: stringType().array(), nullsNotDistinct: booleanType() }).strict(); policy2 = objectType({ name: stringType(), as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(), for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(), to: stringType().array().optional(), using: stringType().optional(), withCheck: stringType().optional(), on: stringType().optional(), schema: stringType().optional() }).strict(); policySquashed2 = objectType({ name: stringType(), values: stringType() }).strict(); viewWithOption2 = objectType({ checkOption: enumType(["local", "cascaded"]).optional(), securityBarrier: booleanType().optional(), securityInvoker: booleanType().optional() }).strict(); matViewWithOption2 = objectType({ fillfactor: numberType().optional(), toastTupleTarget: numberType().optional(), parallelWorkers: numberType().optional(), autovacuumEnabled: booleanType().optional(), vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(), vacuumTruncate: booleanType().optional(), autovacuumVacuumThreshold: numberType().optional(), autovacuumVacuumScaleFactor: numberType().optional(), autovacuumVacuumCostDelay: numberType().optional(), autovacuumVacuumCostLimit: numberType().optional(), autovacuumFreezeMinAge: numberType().optional(), autovacuumFreezeMaxAge: numberType().optional(), autovacuumFreezeTableAge: numberType().optional(), autovacuumMultixactFreezeMinAge: numberType().optional(), autovacuumMultixactFreezeMaxAge: numberType().optional(), autovacuumMultixactFreezeTableAge: numberType().optional(), logAutovacuumMinDuration: numberType().optional(), userCatalogTable: booleanType().optional() }).strict(); mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict(); view4 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column5), definition: stringType().optional(), materialized: booleanType(), with: mergedViewWithOption2.optional(), isExisting: booleanType(), withNoData: booleanType().optional(), using: stringType().optional(), tablespace: stringType().optional() }).strict(); table5 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), column5), indexes: recordType(stringType(), index5), foreignKeys: recordType(stringType(), fk4), compositePrimaryKeys: recordType(stringType(), compositePK5), uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}), policies: recordType(stringType(), policy2).default({}), checkConstraints: recordType(stringType(), checkConstraint4).default({}), isRLSEnabled: booleanType().default(false) }).strict(); schemaHash5 = objectType({ id: stringType(), prevId: stringType() }); kitInternals5 = objectType({ tables: recordType( stringType(), objectType({ columns: recordType( stringType(), objectType({ isArray: booleanType().optional(), dimensions: numberType().optional(), rawType: stringType().optional(), isDefaultAnExpression: booleanType().optional() }).optional() ) }).optional() ) }).optional(); gelSchemaExternal = objectType({ version: literalType("1"), dialect: literalType("gel"), tables: arrayType(table5), enums: arrayType(enumSchemaV12), schemas: arrayType(objectType({ name: stringType() })), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }) }).strict(); gelSchemaInternal = objectType({ version: literalType("1"), dialect: literalType("gel"), tables: recordType(stringType(), table5), enums: recordType(stringType(), enumSchema2), schemas: recordType(stringType(), stringType()), views: recordType(stringType(), view4).default({}), sequences: recordType(stringType(), sequenceSchema2).default({}), roles: recordType(stringType(), roleSchema2).default({}), policies: recordType(stringType(), policy2).default({}), _meta: objectType({ schemas: recordType(stringType(), stringType()), tables: recordType(stringType(), stringType()), columns: recordType(stringType(), stringType()) }), internal: kitInternals5 }).strict(); tableSquashed5 = objectType({ name: stringType(), schema: stringType(), columns: recordType(stringType(), columnSquashed2), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()), compositePrimaryKeys: recordType(stringType(), stringType()), uniqueConstraints: recordType(stringType(), stringType()), policies: recordType(stringType(), stringType()), checkConstraints: recordType(stringType(), stringType()), isRLSEnabled: booleanType().default(false) }).strict(); gelSchemaSquashed = objectType({ version: literalType("1"), dialect: literalType("gel"), tables: recordType(stringType(), tableSquashed5), enums: recordType(stringType(), enumSchema2), schemas: recordType(stringType(), stringType()), views: recordType(stringType(), view4), sequences: recordType(stringType(), sequenceSquashed2), roles: recordType(stringType(), roleSchema2).default({}), policies: recordType(stringType(), policySquashed2).default({}) }).strict(); gelSchema = gelSchemaInternal.merge(schemaHash5); backwardCompatibleGelSchema = gelSchema; dryGel = gelSchema.parse({ version: "1", dialect: "gel", id: originUUID, prevId: "", tables: {}, enums: {}, schemas: {}, policies: {}, roles: {}, sequences: {}, _meta: { schemas: {}, tables: {}, columns: {} } }); } }); // 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_gelSchema(); 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 }; case "gel": return { validator: backwardCompatibleGelSchema, 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 = (table6, schema6, column11) => { const out = schema6 ? `"${schema6}"."${table6}"."${column11}"` : `"${table6}"."${column11}"`; 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 (e4) { 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(p3, cache3) { p3 = pathModule.resolve(p3); if (cache3 && Object.prototype.hasOwnProperty.call(cache3, p3)) { return cache3[p3]; } var original = p3, seenLinks = {}, knownHard = {}; var pos; var current; var base; var previous; start(); function start() { var m4 = splitRootRe.exec(p3); pos = m4[0].length; current = m4[0]; base = m4[0]; previous = ""; if (isWindows && !knownHard[base]) { fs7.lstatSync(base); knownHard[base] = true; } } while (pos < p3.length) { nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p3); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; if (knownHard[base] || cache3 && cache3[base] === base) { continue; } var resolvedLink; if (cache3 && Object.prototype.hasOwnProperty.call(cache3, base)) { resolvedLink = cache3[base]; } else { var stat2 = fs7.lstatSync(base); if (!stat2.isSymbolicLink()) { knownHard[base] = true; if (cache3) cache3[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 (cache3) cache3[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } p3 = pathModule.resolve(resolvedLink, p3.slice(pos)); start(); } if (cache3) cache3[original] = p3; return p3; }; exports2.realpath = function realpath(p3, cache3, cb) { if (typeof cb !== "function") { cb = maybeCallback(cache3); cache3 = null; } p3 = pathModule.resolve(p3); if (cache3 && Object.prototype.hasOwnProperty.call(cache3, p3)) { return process.nextTick(cb.bind(null, null, cache3[p3])); } var original = p3, seenLinks = {}, knownHard = {}; var pos; var current; var base; var previous; start(); function start() { var m4 = splitRootRe.exec(p3); pos = m4[0].length; current = m4[0]; base = m4[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 >= p3.length) { if (cache3) cache3[original] = p3; return cb(null, p3); } nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p3); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; if (knownHard[base] || cache3 && cache3[base] === base) { return process.nextTick(LOOP); } if (cache3 && Object.prototype.hasOwnProperty.call(cache3, base)) { return gotResolvedLink(cache3[base]); } return fs7.lstat(base, gotStat); } function gotStat(err2, stat2) { if (err2) return cb(err2); if (!stat2.isSymbolicLink()) { knownHard[base] = true; if (cache3) cache3[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 (cache3) cache3[base2] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { p3 = pathModule.resolve(resolvedLink, p3.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(p3, cache3, cb) { if (ok) { return origRealpath(p3, cache3, cb); } if (typeof cache3 === "function") { cb = cache3; cache3 = null; } origRealpath(p3, cache3, function(er, result) { if (newError(er)) { old.realpath(p3, cache3, cb); } else { cb(er, result); } }); } function realpathSync(p3, cache3) { if (ok) { return origRealpathSync(p3, cache3); } try { return origRealpathSync(p3, cache3); } catch (er) { if (newError(er)) { return old.realpathSync(p3, cache3); } 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(a3, b3, str) { if (a3 instanceof RegExp) a3 = maybeMatch(a3, str); if (b3 instanceof RegExp) b3 = maybeMatch(b3, str); var r4 = range(a3, b3, str); return r4 && { start: r4[0], end: r4[1], pre: str.slice(0, r4[0]), body: str.slice(r4[0] + a3.length, r4[1]), post: str.slice(r4[1] + b3.length) }; } function maybeMatch(reg, str) { var m4 = str.match(reg); return m4 ? m4[0] : null; } balanced.range = range; function range(a3, b3, str) { var begs, beg, left, right, result; var ai = str.indexOf(a3); var bi = str.indexOf(b3, ai + 1); var i4 = ai; if (ai >= 0 && bi > 0) { if (a3 === b3) { return [ai, bi]; } begs = []; left = str.length; while (i4 >= 0 && !result) { if (i4 == ai) { begs.push(i4); ai = str.indexOf(a3, i4 + 1); } else if (begs.length == 1) { result = [begs.pop(), bi]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b3, i4 + 1); } i4 = 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 m4 = balanced("{", "}", str); if (!m4) return str.split(","); var pre = m4.pre; var body = m4.body; var post = m4.post; var p3 = pre.split(","); p3[p3.length - 1] += "{" + body + "}"; var postParts = parseCommaParts(post); if (post.length) { p3[p3.length - 1] += postParts.shift(); p3.push.apply(p3, postParts); } parts.push.apply(parts, p3); 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(i4, y2) { return i4 <= y2; } function gte(i4, y2) { return i4 >= y2; } function expand2(str, isTop) { var expansions = []; var m4 = balanced("{", "}", str); if (!m4) return [str]; var pre = m4.pre; var post = m4.post.length ? expand2(m4.post, false) : [""]; if (/\$$/.test(m4.pre)) { for (var k3 = 0; k3 < post.length; k3++) { var expansion = pre + "{" + m4.body + "}" + post[k3]; expansions.push(expansion); } } else { var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m4.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m4.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m4.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { if (m4.post.match(/,.*\}/)) { str = m4.pre + "{" + m4.body + escClose + m4.post; return expand2(str); } return [str]; } var n3; if (isSequence) { n3 = m4.body.split(/\.\./); } else { n3 = parseCommaParts(m4.body); if (n3.length === 1) { n3 = expand2(n3[0], false).map(embrace); if (n3.length === 1) { return post.map(function(p3) { return m4.pre + n3[0] + p3; }); } } } var N; if (isSequence) { var x4 = numeric(n3[0]); var y2 = numeric(n3[1]); var width = Math.max(n3[0].length, n3[1].length); var incr = n3.length == 3 ? Math.abs(numeric(n3[2])) : 1; var test = lte; var reverse = y2 < x4; if (reverse) { incr *= -1; test = gte; } var pad = n3.some(isPadded); N = []; for (var i4 = x4; test(i4, y2); i4 += incr) { var c3; if (isAlphaSequence) { c3 = String.fromCharCode(i4); if (c3 === "\\") c3 = ""; } else { c3 = String(i4); if (pad) { var need = width - c3.length; if (need > 0) { var z2 = new Array(need + 1).join("0"); if (i4 < 0) c3 = "-" + z2 + c3.slice(1); else c3 = z2 + c3; } } } N.push(c3); } } else { N = []; for (var j3 = 0; j3 < n3.length; j3++) { N.push.apply(N, expand2(n3[j3], false)); } } for (var j3 = 0; j3 < N.length; j3++) { for (var k3 = 0; k3 < post.length; k3++) { var expansion = pre + N[j3] + post[k3]; 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 = (p3, pattern, options = {}) => { assertValidPattern2(pattern); if (!options.nocomment && pattern.charAt(0) === "#") { return false; } return new Minimatch2(pattern, options).match(p3); }; 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 = (s4) => s4.split("").reduce((set, c3) => { set[c3] = true; return set; }, {}); var reSpecials2 = charSet2("().*{}+?[]^$\\!"); var addPatternStartSet2 = charSet2("[.("); var slashSplit = /\/+/; minimatch2.filter = (pattern, options = {}) => (p3, i4, list) => minimatch2(p3, pattern, options); var ext2 = (a3, b3 = {}) => { const t4 = {}; Object.keys(a3).forEach((k3) => t4[k3] = a3[k3]); Object.keys(b3).forEach((k3) => t4[k3] = b3[k3]); return t4; }; minimatch2.defaults = (def) => { if (!def || typeof def !== "object" || !Object.keys(def).length) { return minimatch2; } const orig = minimatch2; const m4 = (p3, pattern, options) => orig(p3, pattern, ext2(def, options)); m4.Minimatch = class Minimatch extends orig.Minimatch { constructor(pattern, options) { super(pattern, ext2(def, options)); } }; m4.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch; m4.filter = (pattern, options) => orig.filter(pattern, ext2(def, options)); m4.defaults = (options) => orig.defaults(ext2(def, options)); m4.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options)); m4.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options)); m4.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options)); return m4; }; 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((f5) => mm.match(f5)); if (mm.options.nonull && !list.length) { list.push(pattern); } return list; }; var globUnescape2 = (s4) => s4.replace(/\\(.)/g, "$1"); var charUnescape = (s4) => s4.replace(/\\([^-\]])/g, "$1"); var regExpEscape2 = (s4) => s4.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); var braExpEscape = (s4) => s4.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((s4) => s4.split(slashSplit)); this.debug(this.pattern, set); set = set.map((s4, si, set2) => s4.map(this.parse, this)); this.debug(this.pattern, set); set = set.filter((s4) => s4.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 i4 = 0; i4 < pattern.length && pattern.charAt(i4) === "!"; i4++) { negate = !negate; negateOffset++; } if (negateOffset) this.pattern = pattern.slice(negateOffset); this.negate = negate; } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. matchOne(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 p3 = pattern[pi]; var f5 = file[fi]; this.debug(pattern, p3, f5); if (p3 === false) return false; if (p3 === GLOBSTAR2) { this.debug("GLOBSTAR", [pattern, p3, f5]); 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 p3 === "string") { hit = f5 === p3; this.debug("string match", p3, f5, hit); } else { hit = f5.match(p3); this.debug("pattern match", p3, f5, 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 = (p3) => p3.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 i4 = 0, c3; i4 < pattern.length && (c3 = pattern.charAt(i4)); i4++) { this.debug("%s %s %s %j", pattern, i4, re, c3); if (escaping) { if (c3 === "/") { return false; } if (reSpecials2[c3]) { re += "\\"; } re += c3; escaping = false; continue; } switch (c3) { /* istanbul ignore next */ case "/": { return false; } case "\\": if (inClass && pattern.charAt(i4 + 1) === "-") { re += c3; continue; } clearStateChar(); escaping = true; continue; // the various stateChar values // for the "extglob" stuff. case "?": case "*": case "+": case "@": case "!": this.debug("%s %s %s %j <-- stateChar", pattern, i4, re, c3); if (inClass) { this.debug(" in class"); if (c3 === "!" && i4 === classStart + 1) c3 = "^"; re += c3; continue; } this.debug("call clearStateChar %j", stateChar); clearStateChar(); stateChar = c3; if (options.noext) clearStateChar(); continue; case "(": { if (inClass) { re += "("; continue; } if (!stateChar) { re += "\\("; continue; } const plEntry = { type: stateChar, start: i4 - 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(i4 + 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(i4 + 1)); } continue; } // these are mostly the same in regexp and glob case "[": clearStateChar(); if (inClass) { re += "\\" + c3; continue; } inClass = true; classStart = i4; reClassStart = re.length; re += c3; continue; case "]": if (i4 === classStart + 1 || !inClass) { re += "\\" + c3; continue; } cs = pattern.substring(classStart + 1, i4); try { RegExp("[" + braExpEscape(charUnescape(cs)) + "]"); re += c3; } catch (er) { re = re.substring(0, reClassStart) + "(?:$.)"; } hasMagic = true; inClass = false; continue; default: clearStateChar(); if (reSpecials2[c3] && !(c3 === "^" && inClass)) { re += "\\"; } re += c3; break; } } if (inClass) { cs = pattern.slice(classStart + 1); sp = this.parse(cs, SUBPARSE); re = re.substring(0, reClassStart) + "\\[" + sp[0]; hasMagic = hasMagic || sp[1]; } for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { let tail; tail = re.slice(pl.reStart + pl.open.length); this.debug("setting tail", re, pl); tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => { if (!$2) { $2 = "\\"; } return $1 + $1 + $2 + "|"; }); this.debug("tail=%j\n %s", tail, tail, pl, re); const t4 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t4 + "\\(" + tail; } clearStateChar(); if (escaping) { re += "\\\\"; } const addPatternStart = addPatternStartSet2[re.charAt(0)]; for (let n3 = negativeLists.length - 1; n3 > -1; n3--) { const nl = negativeLists[n3]; 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 i4 = 0; i4 < openParensBefore; i4++) { 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( (p3) => typeof p3 === "string" ? regExpEscape2(p3) : p3 === GLOBSTAR2 ? GLOBSTAR2 : p3._src ).reduce((set2, p3) => { if (!(set2[set2.length - 1] === GLOBSTAR2 && p3 === GLOBSTAR2)) { set2.push(p3); } return set2; }, []); pattern.forEach((p3, i4) => { if (p3 !== GLOBSTAR2 || pattern[i4 - 1] === GLOBSTAR2) { return; } if (i4 === 0) { if (pattern.length > 1) { pattern[i4 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i4 + 1]; } else { pattern[i4] = twoStar; } } else if (i4 === pattern.length - 1) { pattern[i4 - 1] += "(?:\\/|" + twoStar + ")?"; } else { pattern[i4 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i4 + 1]; pattern[i4 + 1] = GLOBSTAR2; } }); return pattern.filter((p3) => p3 !== 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(f5, partial = this.partial) { this.debug("match", f5, this.pattern); if (this.comment) return false; if (this.empty) return f5 === ""; if (f5 === "/" && partial) return true; const options = this.options; if (path4.sep !== "/") { f5 = f5.split(path4.sep).join("/"); } f5 = f5.split(slashSplit); this.debug(this.pattern, "split", f5); const set = this.set; this.debug(this.pattern, "set", set); let filename; for (let i4 = f5.length - 1; i4 >= 0; i4--) { filename = f5[i4]; if (filename) break; } for (let i4 = 0; i4 < set.length; i4++) { const pattern = set[i4]; let file = f5; 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 (e4) { 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(a3, b3) { return a3.localeCompare(b3, "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 i4 = 0, l3 = self2.matches.length; i4 < l3; i4++) { var matches = self2.matches[i4]; if (!matches || Object.keys(matches).length === 0) { if (self2.nonull) { var literal = self2.minimatch.globSet[i4]; if (nou) all.push(literal); else all[literal] = true; } } else { var m4 = Object.keys(matches); if (nou) all.push.apply(all, m4); else m4.forEach(function(m5) { all[m5] = true; }); } } if (!nou) all = Object.keys(all); if (!self2.nosort) all = all.sort(alphasort); if (self2.mark) { for (var i4 = 0; i4 < all.length; i4++) { all[i4] = self2._mark(all[i4]); } if (self2.nodir) { all = all.filter(function(e4) { var notDir = !/\/$/.test(e4); var c3 = self2.cache[e4] || self2.cache[makeAbs(self2, e4)]; if (notDir && c3) notDir = c3 !== "DIR" && !Array.isArray(c3); return notDir; }); } } if (self2.ignore.length) all = all.filter(function(m5) { return !isIgnored(self2, m5); }); self2.found = all; } function mark(self2, p3) { var abs = makeAbs(self2, p3); var c3 = self2.cache[abs]; var m4 = p3; if (c3) { var isDir = c3 === "DIR" || Array.isArray(c3); var slash = p3.slice(-1) === "/"; if (isDir && !slash) m4 += "/"; else if (!isDir && slash) m4 = m4.slice(0, -1); if (m4 !== p3) { var mabs = makeAbs(self2, m4); self2.statCache[mabs] = self2.statCache[abs]; self2.cache[mabs] = self2.cache[abs]; } } return m4; } function makeAbs(self2, f5) { var abs = f5; if (f5.charAt(0) === "/") { abs = path4.join(self2.root, f5); } else if (isAbsolute(f5) || f5 === "") { abs = f5; } else if (self2.changedCwd) { abs = path4.resolve(self2.cwd, f5); } else { abs = path4.resolve(f5); } 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 n3 = this.minimatch.set.length; this.matches = new Array(n3); for (var i4 = 0; i4 < n3; i4++) { this._process(this.minimatch.set[i4], i4, false); } this._finish(); } GlobSync.prototype._finish = function() { assert.ok(this instanceof GlobSync); if (this.realpath) { var self2 = this; this.matches.forEach(function(matchset, index6) { var set = self2.matches[index6] = /* @__PURE__ */ Object.create(null); for (var p3 in matchset) { try { p3 = self2._makeAbs(p3); var real = rp.realpathSync(p3, self2.realpathCache); set[real] = true; } catch (er) { if (er.syscall === "stat") set[self2._makeAbs(p3)] = true; else throw er; } } }); } common.finish(this); }; GlobSync.prototype._process = function(pattern, index6, inGlobStar) { assert.ok(this instanceof GlobSync); var n3 = 0; while (typeof pattern[n3] === "string") { n3++; } var prefix2; switch (n3) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join("/"), index6); return; case 0: prefix2 = null; break; default: prefix2 = pattern.slice(0, n3).join("/"); break; } var remain = pattern.slice(n3); var read; if (prefix2 === null) read = "."; else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p3) { return typeof p3 === "string" ? p3 : "[*]"; }).join("/"))) { if (!prefix2 || !isAbsolute(prefix2)) prefix2 = "/" + prefix2; read = prefix2; } else read = prefix2; var abs = this._makeAbs(read); if (childrenIgnored(this, read)) return; var isGlobStar = remain[0] === minimatch2.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar); else this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar); }; GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar) { var entries = this._readdir(abs, inGlobStar); if (!entries) return; var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === "."; var matchedEntries = []; for (var i4 = 0; i4 < entries.length; i4++) { var e4 = entries[i4]; if (e4.charAt(0) !== "." || dotOk) { var m4; if (negate && !prefix2) { m4 = !e4.match(pn); } else { m4 = e4.match(pn); } if (m4) matchedEntries.push(e4); } } var len = matchedEntries.length; if (len === 0) return; if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); for (var i4 = 0; i4 < len; i4++) { var e4 = matchedEntries[i4]; if (prefix2) { if (prefix2.slice(-1) !== "/") e4 = prefix2 + "/" + e4; else e4 = prefix2 + e4; } if (e4.charAt(0) === "/" && !this.nomount) { e4 = path4.join(this.root, e4); } this._emitMatch(index6, e4); } return; } remain.shift(); for (var i4 = 0; i4 < len; i4++) { var e4 = matchedEntries[i4]; var newPattern; if (prefix2) newPattern = [prefix2, e4]; else newPattern = [e4]; this._process(newPattern.concat(remain), index6, inGlobStar); } }; GlobSync.prototype._emitMatch = function(index6, e4) { if (isIgnored(this, e4)) return; var abs = this._makeAbs(e4); if (this.mark) e4 = this._mark(e4); if (this.absolute) { e4 = abs; } if (this.matches[index6][e4]) return; if (this.nodir) { var c3 = this.cache[abs]; if (c3 === "DIR" || Array.isArray(c3)) return; } this.matches[index6][e4] = true; if (this.stat) this._stat(e4); }; 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 c3 = this.cache[abs]; if (!c3 || c3 === "FILE") return null; if (Array.isArray(c3)) return c3; } 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 i4 = 0; i4 < entries.length; i4++) { var e4 = entries[i4]; if (abs === "/") e4 = abs + e4; else e4 = abs + "/" + e4; this.cache[e4] = true; } } this.cache[abs] = entries; return entries; }; GlobSync.prototype._readdirError = function(f5, er) { switch (er.code) { case "ENOTSUP": // https://github.com/isaacs/node-glob/issues/205 case "ENOTDIR": var abs = this._makeAbs(f5); this.cache[abs] = "FILE"; if (abs === this.cwdAbs) { var error2 = new Error(er.code + " invalid cwd " + this.cwd); error2.path = this.cwd; error2.code = er.code; throw error2; } break; case "ENOENT": // not terribly unusual case "ELOOP": case "ENAMETOOLONG": case "UNKNOWN": this.cache[this._makeAbs(f5)] = false; break; default: this.cache[this._makeAbs(f5)] = false; if (this.strict) throw er; if (!this.silent) console.error("glob error", er); break; } }; GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar) { var entries = this._readdir(abs, inGlobStar); if (!entries) return; var remainWithoutGlobStar = remain.slice(1); var gspref = prefix2 ? [prefix2] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); this._process(noGlobStar, index6, false); var len = entries.length; var isSym = this.symlinks[abs]; if (isSym && inGlobStar) return; for (var i4 = 0; i4 < len; i4++) { var e4 = entries[i4]; if (e4.charAt(0) === "." && !this.dot) continue; var instead = gspref.concat(entries[i4], remainWithoutGlobStar); this._process(instead, index6, true); var below = gspref.concat(entries[i4], remain); this._process(below, index6, true); } }; GlobSync.prototype._processSimple = function(prefix2, index6) { var exists = this._stat(prefix2); if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); if (!exists) return; if (prefix2 && isAbsolute(prefix2) && !this.nomount) { var trail = /[\/\\]$/.test(prefix2); if (prefix2.charAt(0) === "/") { prefix2 = 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(index6, prefix2); }; GlobSync.prototype._stat = function(f5) { var abs = this._makeAbs(f5); var needDir = f5.slice(-1) === "/"; if (f5.length > this.maxLength) return false; if (!this.stat && ownProp(this.cache, abs)) { var c3 = this.cache[abs]; if (Array.isArray(c3)) c3 = "DIR"; if (!needDir || c3 === "DIR") return c3; if (needDir && c3 === "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 c3 = true; if (stat2) c3 = stat2.isDirectory() ? "DIR" : "FILE"; this.cache[abs] = this.cache[abs] || c3; if (needDir && c3 === "FILE") return false; return c3; }; GlobSync.prototype._mark = function(p3) { return common.mark(this, p3); }; GlobSync.prototype._makeAbs = function(f5) { return common.makeAbs(this, f5); }; } }); // ../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(k3) { wrapper[k3] = fn[k3]; }); return wrapper; function wrapper() { var args = new Array(arguments.length); for (var i4 = 0; i4 < args.length; i4++) { args[i4] = arguments[i4]; } var ret = fn.apply(this, args); var cb2 = args[args.length - 1]; if (typeof ret === "function" && ret !== cb2) { Object.keys(cb2).forEach(function(k3) { ret[k3] = cb2[k3]; }); } 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 f5 = function() { if (f5.called) return f5.value; f5.called = true; return f5.value = fn.apply(this, arguments); }; f5.called = false; return f5; } function onceStrict(fn) { var f5 = function() { if (f5.called) throw new Error(f5.onceError); f5.called = true; return f5.value = fn.apply(this, arguments); }; var name = fn.name || "Function wrapped with `once`"; f5.onceError = name + " shouldn't be called more than once"; f5.called = false; return f5; } } }); // ../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 i4 = 0; i4 < len; i4++) { cbs[i4].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 i4 = 0; i4 < length; i4++) array2[i4] = args[i4]; 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 i4 = keys.length; while (i4--) { origin[keys[i4]] = add[keys[i4]]; } return origin; } glob2.hasMagic = function(pattern, options_) { var options = extend({}, options_); options.noprocess = true; var g3 = new Glob(pattern, options); var set = g3.minimatch.set; if (!pattern) return false; if (set.length > 1) return true; for (var j3 = 0; j3 < set[0].length; j3++) { if (typeof set[0][j3] !== "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 n3 = this.minimatch.set.length; this.matches = new Array(n3); 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 (n3 === 0) return done(); var sync2 = true; for (var i4 = 0; i4 < n3; i4++) { this._process(this.minimatch.set[i4], i4, 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 n3 = this.matches.length; if (n3 === 0) return this._finish(); var self2 = this; for (var i4 = 0; i4 < this.matches.length; i4++) this._realpathSet(i4, next); function next() { if (--n3 === 0) self2._finish(); } }; Glob.prototype._realpathSet = function(index6, cb) { var matchset = this.matches[index6]; if (!matchset) return cb(); var found = Object.keys(matchset); var self2 = this; var n3 = found.length; if (n3 === 0) return cb(); var set = this.matches[index6] = /* @__PURE__ */ Object.create(null); found.forEach(function(p3, i4) { p3 = self2._makeAbs(p3); rp.realpath(p3, self2.realpathCache, function(er, real) { if (!er) set[real] = true; else if (er.syscall === "stat") set[p3] = true; else self2.emit("error", er); if (--n3 === 0) { self2.matches[index6] = set; cb(); } }); }); }; Glob.prototype._mark = function(p3) { return common.mark(this, p3); }; Glob.prototype._makeAbs = function(f5) { return common.makeAbs(this, f5); }; 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 i4 = 0; i4 < eq.length; i4++) { var e4 = eq[i4]; this._emitMatch(e4[0], e4[1]); } } if (this._processQueue.length) { var pq = this._processQueue.slice(0); this._processQueue.length = 0; for (var i4 = 0; i4 < pq.length; i4++) { var p3 = pq[i4]; this._processing--; this._process(p3[0], p3[1], p3[2], p3[3]); } } } }; Glob.prototype._process = function(pattern, index6, inGlobStar, cb) { assert(this instanceof Glob); assert(typeof cb === "function"); if (this.aborted) return; this._processing++; if (this.paused) { this._processQueue.push([pattern, index6, inGlobStar, cb]); return; } var n3 = 0; while (typeof pattern[n3] === "string") { n3++; } var prefix2; switch (n3) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join("/"), index6, cb); return; case 0: prefix2 = null; break; default: prefix2 = pattern.slice(0, n3).join("/"); break; } var remain = pattern.slice(n3); var read; if (prefix2 === null) read = "."; else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p3) { return typeof p3 === "string" ? p3 : "[*]"; }).join("/"))) { if (!prefix2 || !isAbsolute(prefix2)) prefix2 = "/" + prefix2; read = prefix2; } else read = prefix2; var abs = this._makeAbs(read); if (childrenIgnored(this, read)) return cb(); var isGlobStar = remain[0] === minimatch2.GLOBSTAR; if (isGlobStar) this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar, cb); else this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar, cb); }; Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar, cb) { var self2 = this; this._readdir(abs, inGlobStar, function(er, entries) { return self2._processReaddir2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb); }); }; Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) { if (!entries) return cb(); var pn = remain[0]; var negate = !!this.minimatch.negate; var rawGlob = pn._glob; var dotOk = this.dot || rawGlob.charAt(0) === "."; var matchedEntries = []; for (var i4 = 0; i4 < entries.length; i4++) { var e4 = entries[i4]; if (e4.charAt(0) !== "." || dotOk) { var m4; if (negate && !prefix2) { m4 = !e4.match(pn); } else { m4 = e4.match(pn); } if (m4) matchedEntries.push(e4); } } var len = matchedEntries.length; if (len === 0) return cb(); if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); for (var i4 = 0; i4 < len; i4++) { var e4 = matchedEntries[i4]; if (prefix2) { if (prefix2 !== "/") e4 = prefix2 + "/" + e4; else e4 = prefix2 + e4; } if (e4.charAt(0) === "/" && !this.nomount) { e4 = path4.join(this.root, e4); } this._emitMatch(index6, e4); } return cb(); } remain.shift(); for (var i4 = 0; i4 < len; i4++) { var e4 = matchedEntries[i4]; var newPattern; if (prefix2) { if (prefix2 !== "/") e4 = prefix2 + "/" + e4; else e4 = prefix2 + e4; } this._process([e4].concat(remain), index6, inGlobStar, cb); } cb(); }; Glob.prototype._emitMatch = function(index6, e4) { if (this.aborted) return; if (isIgnored(this, e4)) return; if (this.paused) { this._emitQueue.push([index6, e4]); return; } var abs = isAbsolute(e4) ? e4 : this._makeAbs(e4); if (this.mark) e4 = this._mark(e4); if (this.absolute) e4 = abs; if (this.matches[index6][e4]) return; if (this.nodir) { var c3 = this.cache[abs]; if (c3 === "DIR" || Array.isArray(c3)) return; } this.matches[index6][e4] = true; var st = this.statCache[abs]; if (st) this.emit("stat", e4, st); this.emit("match", e4); }; 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 c3 = this.cache[abs]; if (!c3 || c3 === "FILE") return cb(); if (Array.isArray(c3)) return cb(null, c3); } 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 i4 = 0; i4 < entries.length; i4++) { var e4 = entries[i4]; if (abs === "/") e4 = abs + e4; else e4 = abs + "/" + e4; this.cache[e4] = true; } } this.cache[abs] = entries; return cb(null, entries); }; Glob.prototype._readdirError = function(f5, er, cb) { if (this.aborted) return; switch (er.code) { case "ENOTSUP": // https://github.com/isaacs/node-glob/issues/205 case "ENOTDIR": var abs = this._makeAbs(f5); this.cache[abs] = "FILE"; if (abs === this.cwdAbs) { var error2 = new Error(er.code + " invalid cwd " + this.cwd); error2.path = this.cwd; error2.code = er.code; this.emit("error", error2); this.abort(); } break; case "ENOENT": // not terribly unusual case "ELOOP": case "ENAMETOOLONG": case "UNKNOWN": this.cache[this._makeAbs(f5)] = false; break; default: this.cache[this._makeAbs(f5)] = false; if (this.strict) { this.emit("error", er); this.abort(); } if (!this.silent) console.error("glob error", er); break; } return cb(); }; Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar, cb) { var self2 = this; this._readdir(abs, inGlobStar, function(er, entries) { self2._processGlobStar2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb); }); }; Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) { if (!entries) return cb(); var remainWithoutGlobStar = remain.slice(1); var gspref = prefix2 ? [prefix2] : []; var noGlobStar = gspref.concat(remainWithoutGlobStar); this._process(noGlobStar, index6, false, cb); var isSym = this.symlinks[abs]; var len = entries.length; if (isSym && inGlobStar) return cb(); for (var i4 = 0; i4 < len; i4++) { var e4 = entries[i4]; if (e4.charAt(0) === "." && !this.dot) continue; var instead = gspref.concat(entries[i4], remainWithoutGlobStar); this._process(instead, index6, true, cb); var below = gspref.concat(entries[i4], remain); this._process(below, index6, true, cb); } cb(); }; Glob.prototype._processSimple = function(prefix2, index6, cb) { var self2 = this; this._stat(prefix2, function(er, exists) { self2._processSimple2(prefix2, index6, er, exists, cb); }); }; Glob.prototype._processSimple2 = function(prefix2, index6, er, exists, cb) { if (!this.matches[index6]) this.matches[index6] = /* @__PURE__ */ Object.create(null); if (!exists) return cb(); if (prefix2 && isAbsolute(prefix2) && !this.nomount) { var trail = /[\/\\]$/.test(prefix2); if (prefix2.charAt(0) === "/") { prefix2 = 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(index6, prefix2); cb(); }; Glob.prototype._stat = function(f5, cb) { var abs = this._makeAbs(f5); var needDir = f5.slice(-1) === "/"; if (f5.length > this.maxLength) return cb(); if (!this.stat && ownProp(this.cache, abs)) { var c3 = this.cache[abs]; if (Array.isArray(c3)) c3 = "DIR"; if (!needDir || c3 === "DIR") return cb(null, c3); if (needDir && c3 === "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(f5, abs, null, lstat, cb); else self2._stat2(f5, abs, er2, stat3, cb); }); } else { self2._stat2(f5, abs, er, lstat, cb); } } }; Glob.prototype._stat2 = function(f5, abs, er, stat2, cb) { if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) { this.statCache[abs] = false; return cb(); } var needDir = f5.slice(-1) === "/"; this.statCache[abs] = stat2; if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory()) return cb(null, false, stat2); var c3 = true; if (stat2) c3 = stat2.isDirectory() ? "DIR" : "FILE"; this.cache[abs] = this.cache[abs] || c3; if (needDir && c3 === "FILE") return cb(); return cb(null, c3, 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_esm(); 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 _3 = ""; } casingTypes = ["snake_case", "camelCase"]; casingType = enumType(casingTypes); sqliteDriver = unionType(sqliteDriversLiterals); postgresDriver = unionType(postgresqlDriversLiterals); driver = unionType([sqliteDriver, postgresDriver]); configMigrations = objectType({ table: stringType().optional(), schema: stringType().optional(), prefix: prefix.optional().default("index") }).optional(); configCommonSchema = objectType({ dialect: dialect4, schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional(), breakpoints: booleanType().optional().default(true), verbose: booleanType().optional().default(false), driver: driver.optional(), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), migrations: configMigrations, dbCredentials: anyType().optional(), casing: casingType.optional(), sql: booleanType().default(true) }).passthrough(); casing = unionType([literalType("camel"), literalType("preserve")]).default( "camel" ); introspectParams = objectType({ schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional().default("./drizzle"), breakpoints: booleanType().default(true), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), introspect: objectType({ casing }).default({ casing: "camel" }) }); configIntrospectCliSchema = objectType({ schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional().default("./drizzle"), breakpoints: booleanType().default(true), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default( "camel" ) }); configGenerateSchema = objectType({ schema: unionType([stringType(), stringType().array()]), out: stringType().optional().default("./drizzle"), breakpoints: booleanType().default(true) }); configPushSchema = objectType({ dialect: dialect4, schema: unionType([stringType(), stringType().array()]), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]), verbose: booleanType().default(false), strict: booleanType().default(false), out: stringType().optional() }); 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_esm(); init_schemaValidator(); init_common(); cliConfigGenerate = objectType({ dialect: dialect4.optional(), schema: unionType([stringType(), stringType().array()]).optional(), out: stringType().optional().default("./drizzle"), config: stringType().optional(), name: stringType().optional(), prefix: prefix.optional(), breakpoints: booleanType().optional().default(true), custom: booleanType().optional().default(false) }).strict(); pushParams = objectType({ dialect: dialect4, casing: casingType.optional(), schema: unionType([stringType(), stringType().array()]), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]), extensionsFilters: literalType("postgis").array().optional(), verbose: booleanType().optional(), strict: booleanType().optional(), entities: objectType({ roles: booleanType().or(objectType({ provider: stringType().optional(), include: stringType().array().optional(), exclude: stringType().array().optional() })).optional().default(false) }).optional() }).passthrough(); pullParams = objectType({ config: stringType().optional(), dialect: dialect4, out: stringType().optional().default("drizzle"), tablesFilter: unionType([stringType(), stringType().array()]).optional(), schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]), extensionsFilters: literalType("postgis").array().optional(), casing, breakpoints: booleanType().optional().default(true), migrations: objectType({ prefix: prefix.optional().default("index") }).optional(), entities: objectType({ roles: booleanType().or(objectType({ provider: stringType().optional(), include: stringType().array().optional(), exclude: stringType().array().optional() })).optional().default(false) }).optional() }).passthrough(); configCheck = objectType({ dialect: dialect4.optional(), out: stringType().optional() }); cliConfigCheck = intersectionType( objectType({ config: stringType().optional() }), configCheck ); } }); // src/cli/validations/gel.ts var gelCredentials, printConfigConnectionIssues; var init_gel = __esm({ "src/cli/validations/gel.ts"() { "use strict"; init_esm(); init_views(); init_common(); gelCredentials = unionType([ objectType({ driver: undefinedType(), host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), tlsSecurity: unionType([ literalType("insecure"), literalType("no_host_verification"), literalType("strict"), literalType("default") ]).optional() }).transform((o3) => { delete o3.driver; return o3; }), objectType({ driver: undefinedType(), url: stringType().min(1), tlsSecurity: unionType([ literalType("insecure"), literalType("no_host_verification"), literalType("strict"), literalType("default") ]).optional() }).transform((o3) => { delete o3.driver; return o3; }), objectType({ driver: undefinedType() }).transform((o3) => { return void 0; }) ]); printConfigConnectionIssues = (options) => { if ("url" in options) { let text = `Please provide required params for Gel 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 Gel 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("tlsSecurity", options.tlsSecurity, true)); process.exit(1); } console.log( error( `Either connection "url" or "host", "database" are required for Gel database connection` ) ); process.exit(1); }; } }); // src/cli/validations/libsql.ts var libSQLCredentials, printConfigConnectionIssues2; var init_libsql = __esm({ "src/cli/validations/libsql.ts"() { "use strict"; init_esm(); init_views(); init_common(); libSQLCredentials = objectType({ url: stringType().min(1), authToken: stringType().min(1).optional() }); printConfigConnectionIssues2 = (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, printConfigConnectionIssues3; var init_mysql = __esm({ "src/cli/validations/mysql.ts"() { "use strict"; init_esm(); init_views(); init_common(); init_outputs(); mysqlCredentials = unionType([ objectType({ host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), ssl: unionType([ stringType(), objectType({ pfx: stringType().optional(), key: stringType().optional(), passphrase: stringType().optional(), cert: stringType().optional(), ca: unionType([stringType(), stringType().array()]).optional(), crl: unionType([stringType(), stringType().array()]).optional(), ciphers: stringType().optional(), rejectUnauthorized: booleanType().optional() }) ]).optional() }), objectType({ url: stringType().min(1) }) ]); printConfigConnectionIssues3 = (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, printConfigConnectionIssues4; var init_postgres = __esm({ "src/cli/validations/postgres.ts"() { "use strict"; init_esm(); init_views(); init_common(); postgresCredentials = unionType([ objectType({ driver: undefinedType(), host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), ssl: unionType([ literalType("require"), literalType("allow"), literalType("prefer"), literalType("verify-full"), booleanType(), objectType({}).passthrough() ]).optional() }).transform((o3) => { delete o3.driver; return o3; }), objectType({ driver: undefinedType(), url: stringType().min(1) }).transform((o3) => { delete o3.driver; return o3; }), 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) }) ]); printConfigConnectionIssues4 = (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, printConfigConnectionIssues5; var init_singlestore = __esm({ "src/cli/validations/singlestore.ts"() { "use strict"; init_esm(); init_views(); init_common(); init_outputs(); singlestoreCredentials = unionType([ objectType({ host: stringType().min(1), port: coerce.number().min(1).optional(), user: stringType().min(1).optional(), password: stringType().min(1).optional(), database: stringType().min(1), ssl: unionType([ stringType(), objectType({ pfx: stringType().optional(), key: stringType().optional(), passphrase: stringType().optional(), cert: stringType().optional(), ca: unionType([stringType(), stringType().array()]).optional(), crl: unionType([stringType(), stringType().array()]).optional(), ciphers: stringType().optional(), rejectUnauthorized: booleanType().optional() }) ]).optional() }), objectType({ url: stringType().min(1) }) ]); printConfigConnectionIssues5 = (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, printConfigConnectionIssues6; var init_sqlite = __esm({ "src/cli/validations/sqlite.ts"() { "use strict"; init_global(); init_esm(); init_views(); init_common(); sqliteCredentials = unionType([ objectType({ driver: literalType("turso"), url: stringType().min(1), authToken: stringType().min(1).optional() }), objectType({ driver: literalType("d1-http"), accountId: stringType().min(1), databaseId: stringType().min(1), token: stringType().min(1) }), objectType({ driver: undefinedType(), url: stringType().min(1) }).transform((o3) => { delete o3.driver; return o3; }) ]); printConfigConnectionIssues6 = (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 'studio' 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_esm(); init_schemaValidator(); init_common(); init_mysql(); init_postgres(); init_sqlite(); credentials = intersectionType( postgresCredentials, mysqlCredentials, sqliteCredentials ); studioCliParams = objectType({ port: coerce.number().optional().default(4983), host: stringType().optional().default("127.0.0.1"), config: stringType().optional() }); studioConfig = objectType({ dialect: dialect4, schema: unionType([stringType(), stringType().array()]).optional(), casing: casingType.optional() }); } }); // src/cli/commands/_es5.ts var es5_exports = {}; __export(es5_exports, { default: () => es5_default }); var _, es5_default; var init_es5 = __esm({ "src/cli/commands/_es5.ts"() { "use strict"; _ = ""; es5_default = _; } }); // ../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js var require_ms = __commonJS({ "../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports2, module2) { var s4 = 1e3; var m4 = s4 * 60; var h4 = m4 * 60; var d3 = h4 * 24; var w3 = d3 * 7; var y2 = d3 * 365.25; module2.exports = function(val2, options) { options = options || {}; var type = typeof val2; if (type === "string" && val2.length > 0) { return parse4(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 parse4(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 n3 = parseFloat(match2[1]); var type = (match2[2] || "ms").toLowerCase(); switch (type) { case "years": case "year": case "yrs": case "yr": case "y": return n3 * y2; case "weeks": case "week": case "w": return n3 * w3; case "days": case "day": case "d": return n3 * d3; case "hours": case "hour": case "hrs": case "hr": case "h": return n3 * h4; case "minutes": case "minute": case "mins": case "min": case "m": return n3 * m4; case "seconds": case "second": case "secs": case "sec": case "s": return n3 * s4; case "milliseconds": case "millisecond": case "msecs": case "msec": case "ms": return n3; default: return void 0; } } function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d3) { return Math.round(ms / d3) + "d"; } if (msAbs >= h4) { return Math.round(ms / h4) + "h"; } if (msAbs >= m4) { return Math.round(ms / m4) + "m"; } if (msAbs >= s4) { return Math.round(ms / s4) + "s"; } return ms + "ms"; } function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d3) { return plural2(ms, msAbs, d3, "day"); } if (msAbs >= h4) { return plural2(ms, msAbs, h4, "hour"); } if (msAbs >= m4) { return plural2(ms, msAbs, m4, "minute"); } if (msAbs >= s4) { return plural2(ms, msAbs, s4, "second"); } return ms + " ms"; } function plural2(ms, msAbs, n3, name) { var isPlural = msAbs >= n3 * 1.5; return Math.round(ms / n3) + " " + name + (isPlural ? "s" : ""); } } }); // ../node_modules/.pnpm/debug@4.4.1/node_modules/debug/src/common.js var require_common2 = __commonJS({ "../node_modules/.pnpm/debug@4.4.1/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 i4 = 0; i4 < namespace.length; i4++) { hash = (hash << 5) - hash + namespace.charCodeAt(i4); 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 index6 = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format) => { if (match2 === "%%") { return "%"; } index6++; const formatter = createDebug.formatters[format]; if (typeof formatter === "function") { const val2 = args[index6]; match2 = formatter.call(self2, val2); args.splice(index6, 1); index6--; } 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: (v6) => { enableOverride = v6; } }); 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 = []; const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); for (const ns of split) { if (ns[0] === "-") { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { if (template[templateIndex] === "*") { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; } } while (templateIndex < template.length && template[templateIndex] === "*") { templateIndex++; } return templateIndex === template.length; } function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace) ].join(","); createDebug.enable(""); return namespaces; } function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } function 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.4.1/node_modules/debug/src/browser.js var require_browser = __commonJS({ "../node_modules/.pnpm/debug@4.4.1/node_modules/debug/src/browser.js"(exports2, module2) { exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load; exports2.useColors = useColors; exports2.storage = localstorage(); exports2.destroy = /* @__PURE__ */ (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } }; })(); exports2.colors = [ "#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33" ]; function useColors() { if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { return true; } if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m4; 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 && (m4 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m4[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 c3 = "color: " + this.color; args.splice(1, 0, c3, "color: inherit"); let index6 = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, (match2) => { if (match2 === "%%") { return; } index6++; if (match2 === "%c") { lastC = index6; } }); args.splice(lastC, 0, c3); } 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 r4; try { r4 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); } catch (error2) { } if (!r4 && typeof process !== "undefined" && "env" in process) { r4 = process.env.DEBUG; } return r4; } function localstorage() { try { return localStorage; } catch (error2) { } } module2.exports = require_common2()(exports2); var { formatters } = module2.exports; formatters.j = function(v6) { try { return JSON.stringify(v6); } 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.4.1/node_modules/debug/src/node.js var require_node = __commonJS({ "../node_modules/.pnpm/debug@4.4.1/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, (_3, k3) => { return k3.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 c3 = this.color; const colorCode = "\x1B[3" + (c3 < 8 ? c3 : "8;5;" + c3); 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.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); } function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { delete process.env.DEBUG; } } function load() { return process.env.DEBUG; } function init2(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports2.inspectOpts); for (let i4 = 0; i4 < keys.length; i4++) { debug.inspectOpts[keys[i4]] = exports2.inspectOpts[keys[i4]]; } } module2.exports = require_common2()(exports2); var { formatters } = module2.exports; formatters.o = function(v6) { this.inspectOpts.colors = this.useColors; return util2.inspect(v6, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); }; formatters.O = function(v6) { this.inspectOpts.colors = this.useColors; return util2.inspect(v6, this.inspectOpts); }; } }); // ../node_modules/.pnpm/debug@4.4.1/node_modules/debug/src/index.js var require_src2 = __commonJS({ "../node_modules/.pnpm/debug@4.4.1/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.6.0_esbuild@0.25.5/node_modules/esbuild-register/dist/node.js var require_node2 = __commonJS({ "../node_modules/.pnpm/esbuild-register@3.6.0_esbuild@0.25.5/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 __exportStar2 = (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 __exportStar2(__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_util4 = __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, i4 = parts.length - 1; i4 >= 0; i4--) { part = parts[i4]; if (part === ".") { parts.splice(i4, 1); } else if (part === "..") { up2++; } else if (up2 > 0) { if (part === "") { parts.splice(i4 + 1, up2); up2 = 0; } else { parts.splice(i4, 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 index6 = aRoot.lastIndexOf("/"); if (index6 < 0) { return aPath; } aRoot = aRoot.slice(0, index6); 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(s4) { return s4; } 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(s4) { if (!s4) { return false; } var length = s4.length; if (length < 9) { return false; } if (s4.charCodeAt(length - 1) !== 95 || s4.charCodeAt(length - 2) !== 95 || s4.charCodeAt(length - 3) !== 111 || s4.charCodeAt(length - 4) !== 116 || s4.charCodeAt(length - 5) !== 111 || s4.charCodeAt(length - 6) !== 114 || s4.charCodeAt(length - 7) !== 112 || s4.charCodeAt(length - 8) !== 95 || s4.charCodeAt(length - 9) !== 95) { return false; } for (var i4 = length - 10; i4 >= 0; i4--) { if (s4.charCodeAt(i4) !== 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 index6 = parsed.path.lastIndexOf("/"); if (index6 >= 0) { parsed.path = parsed.path.substring(0, index6 + 1); } } sourceURL = join22(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports3.computeSourceURL = computeSourceURL; }); var require_array_set = __commonJS3((exports3) => { var util2 = require_util4(); 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 i4 = 0, len = aArray.length; i4 < len; i4++) { set.add(aArray[i4], 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_util4(); 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_util4(); 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 i4 = 0, len = mappings.length; i4 < len; i4++) { mapping = mappings[i4]; next = ""; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ";"; previousGeneratedLine++; } } else { if (i4 > 0) { if (!util2.compareByGeneratedPositionsInflated(mapping, mappings[i4 - 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 map22 = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map22.file = this._file; } if (this._sourceRoot != null) { map22.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map22.sourcesContent = this._generateSourcesContent(map22.sources, map22.sourceRoot); } return map22; }; 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 index6 = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports3.GREATEST_LOWER_BOUND); if (index6 < 0) { return -1; } while (index6 - 1 >= 0) { if (aCompare(aHaystack[index6], aHaystack[index6 - 1], true) !== 0) { break; } --index6; } return index6; }; }); var require_quick_sort = __commonJS3((exports3) => { function swap(ary, x4, y2) { var temp = ary[x4]; ary[x4] = ary[y2]; ary[y2] = temp; } function randomIntInRange(low, high) { return Math.round(low + Math.random() * (high - low)); } function doQuickSort(ary, comparator, p3, r4) { if (p3 < r4) { var pivotIndex = randomIntInRange(p3, r4); var i4 = p3 - 1; swap(ary, pivotIndex, r4); var pivot = ary[r4]; for (var j3 = p3; j3 < r4; j3++) { if (comparator(ary[j3], pivot) <= 0) { i4 += 1; swap(ary, i4, j3); } } swap(ary, i4 + 1, j3); var q3 = i4 + 1; doQuickSort(ary, comparator, p3, q3 - 1); doQuickSort(ary, comparator, q3 + 1, r4); } } exports3.quickSort = function(ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; }); var require_source_map_consumer = __commonJS3((exports3) => { var util2 = require_util4(); 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, index6) { var c3 = aStr.charAt(index6); return c3 === ";" || c3 === ","; }; 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 index6 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index6 >= 0) { var mapping = this._originalMappings[index6]; 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[++index6]; } } 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[++index6]; } } } 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(s4) { return util2.computeSourceURL(sourceRoot, s4, 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 i4; for (i4 = 0; i4 < this._absoluteSources.length; ++i4) { if (this._absoluteSources[i4] == aSource) { return i4; } } 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(s4) { return util2.computeSourceURL(smc.sourceRoot, s4, aSourceMapURL); }); var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i4 = 0, length = generatedMappings.length; i4 < length; i4++) { var srcMapping = generatedMappings[i4]; 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 index6 = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index6 < length) { if (aStr.charAt(index6) === ";") { generatedLine++; index6++; previousGeneratedColumn = 0; } else if (aStr.charAt(index6) === ",") { index6++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; for (end = index6; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index6, end); segment = cachedSegments[str]; if (segment) { index6 += str.length; } else { segment = []; while (index6 < end) { base64VLQ.decode(aStr, index6, temp); value = temp.value; index6 = 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 index6 = 0; index6 < this._generatedMappings.length; ++index6) { var mapping = this._generatedMappings[index6]; if (index6 + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index6 + 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 index6 = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util2.compareByGeneratedPositionsDeflated, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)); if (index6 >= 0) { var mapping = this._generatedMappings[index6]; 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 index6 = this._findSourceIndex(aSource); if (index6 >= 0) { return this.sourcesContent[index6]; } 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 index6 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)); if (index6 >= 0) { var mapping = this._originalMappings[index6]; 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(s4) { if (s4.url) { throw new Error("Support for url field in sections not implemented."); } var offset = util2.getArg(s4, "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(s4, "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 i4 = 0; i4 < this._sections.length; i4++) { for (var j3 = 0; j3 < this._sections[i4].consumer.sources.length; j3++) { sources.push(this._sections[i4].consumer.sources[j3]); } } 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(s4) { return s4.consumer.hasContentsOfAllSources(); }); }; IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i4 = 0; i4 < this._sections.length; i4++) { var section = this._sections[i4]; 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 i4 = 0; i4 < this._sections.length; i4++) { var section = this._sections[i4]; 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 i4 = 0; i4 < this._sections.length; i4++) { var section = this._sections[i4]; var sectionMappings = section.consumer._generatedMappings; for (var j3 = 0; j3 < sectionMappings.length; j3++) { var mapping = sectionMappings[j3]; 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_util4(); 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 i4 = aChunk.length - 1; i4 >= 0; i4--) { this.prepend(aChunk[i4]); } } 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 i4 = 0, len = this.children.length; i4 < len; i4++) { chunk = this.children[i4]; 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 i4; var len = this.children.length; if (len > 0) { newChildren = []; for (i4 = 0; i4 < len - 1; i4++) { newChildren.push(this.children[i4]); newChildren.push(aSep); } newChildren.push(this.children[i4]); 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 i4 = 0, len = this.children.length; i4 < len; i4++) { if (this.children[i4][isSourceNode]) { this.children[i4].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i4 = 0, len = sources.length; i4 < len; i4++) { aFn(util2.fromSetString(sources[i4]), this.sourceContents[sources[i4]]); } }; 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 map22 = 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) { map22.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) { map22.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) { map22.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) { map22.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map22 }; }; 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 i4 = 0; i4 < list.length; i4++) { var ret = list[i4](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 (e4) { } } 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, i4) { var contents = sourceMap.map.sourcesContent[i4]; 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, state2) { if (state2 === void 0) { state2 = { nextPosition: null, curPosition: null }; } if (frame.isNative()) { state2.curPosition = null; return frame; } var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); if (source) { var line = frame.getLineNumber(); var column11 = 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 && column11 > headerLength && !isInBrowser() && !frame.isEval()) { column11 -= headerLength; } var position = mapSourcePosition({ source, line, column: column11 }); state2.curPosition = position; frame = cloneCallSite(frame); var originalFunctionName = frame.getFunctionName; frame.getFunctionName = function() { if (state2.nextPosition == null) { return originalFunctionName(); } return state2.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 state2 = { nextPosition: null, curPosition: null }; var processedStack = []; for (var i4 = stack.length - 1; i4 >= 0; i4--) { processedStack.push("\n at " + wrapCallSite(stack[i4], state2)); state2.nextPosition = state2.curPosition; } state2.curPosition = state2.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 column11 = +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(column11).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 (e4) { } 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_lib3 = __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(a3, b3) { return getPrefixLength(b3) - getPrefixLength(a3); }); } 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(e4) { return { type: "extension", path: physicalPath + e4 }; })); pathsToTry.push({ type: "package", path: path4.join(physicalPath, "/package.json") }); var indexPath = path4.join(physicalPath, "/index"); pathsToTry.push.apply(pathsToTry, extensions.map(function(e4) { return { type: "index", path: indexPath + e4 }; })); }; for (var _a2 = 0, _b = entry.paths; _a2 < _b.length; _a2++) { var physicalPathPattern = _b[_a2]; _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 index6 = 0; index6 < mainFields.length; index6++) { var mainFieldSelector = mainFields[index6]; 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, index6) { if (index6 === void 0) { index6 = 0; } if (index6 >= mainFields.length) { return doneCallback(void 0, void 0); } var tryNext = function() { return findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExistsAsync, doneCallback, index6 + 1); }; var mainFieldSelector = mainFields[index6]; 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, index6, mainFields) { if (index6 === void 0) { index6 = 0; } if (mainFields === void 0) { mainFields = ["main"]; } var tryPath = tryPaths[index6]; 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 (index6 === tryPaths.length - 1) { return doneCallback(); } return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index6 + 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, index6 + 1, mainFields); }); } return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index6 + 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(c3) { return typeof c3 === "string" && unicode.Space_Separator.test(c3); }, isIdStartChar(c3) { return typeof c3 === "string" && (c3 >= "a" && c3 <= "z" || c3 >= "A" && c3 <= "Z" || c3 === "$" || c3 === "_" || unicode.ID_Start.test(c3)); }, isIdContinueChar(c3) { return typeof c3 === "string" && (c3 >= "a" && c3 <= "z" || c3 >= "A" && c3 <= "Z" || c3 >= "0" && c3 <= "9" || c3 === "$" || c3 === "_" || c3 === "\u200C" || c3 === "\u200D" || unicode.ID_Continue.test(c3)); }, isDigit(c3) { return typeof c3 === "string" && /[0-9]/.test(c3); }, isHexDigit(c3) { return typeof c3 === "string" && /[0-9A-Fa-f]/.test(c3); } }; }); var require_parse3 = __commonJS3((exports3, module22) => { var util2 = require_util22(); var source; var parseState; var stack; var pos; var line; var column11; var token; var key; var root; module22.exports = function parse4(text, reviver) { source = String(text); parseState = "start"; stack = []; pos = 0; line = 1; column11 = 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 i4 = 0; i4 < value.length; i4++) { const key2 = String(i4); 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 c3; function lex() { lexState = "default"; buffer = ""; doubleQuote = false; sign = 1; for (; ; ) { c3 = peek(); const token2 = lexStates[lexState](); if (token2) { return token2; } } } function peek() { if (source[pos]) { return String.fromCodePoint(source.codePointAt(pos)); } } function read() { const c22 = peek(); if (c22 === "\n") { line++; column11 = 0; } else if (c22) { column11 += c22.length; } else { column11++; } if (c22) { pos += c22.length; } return c22; } var lexStates = { default() { switch (c3) { 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(c3)) { read(); return; } return lexStates[parseState](); }, comment() { switch (c3) { case "*": read(); lexState = "multiLineComment"; return; case "/": read(); lexState = "singleLineComment"; return; } throw invalidChar(read()); }, multiLineComment() { switch (c3) { case "*": read(); lexState = "multiLineCommentAsterisk"; return; case void 0: throw invalidChar(read()); } read(); }, multiLineCommentAsterisk() { switch (c3) { case "*": read(); return; case "/": read(); lexState = "default"; return; case void 0: throw invalidChar(read()); } read(); lexState = "multiLineComment"; }, singleLineComment() { switch (c3) { case "\n": case "\r": case "\u2028": case "\u2029": read(); lexState = "default"; return; case void 0: read(); return newToken("eof"); } read(); }, value() { switch (c3) { 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 (c3 !== "u") { throw invalidChar(read()); } read(); const u3 = unicodeEscape(); switch (u3) { case "$": case "_": break; default: if (!util2.isIdStartChar(u3)) { throw invalidIdentifier(); } break; } buffer += u3; lexState = "identifierName"; }, identifierName() { switch (c3) { case "$": case "_": case "\u200C": case "\u200D": buffer += read(); return; case "\\": read(); lexState = "identifierNameEscape"; return; } if (util2.isIdContinueChar(c3)) { buffer += read(); return; } return newToken("identifier", buffer); }, identifierNameEscape() { if (c3 !== "u") { throw invalidChar(read()); } read(); const u3 = unicodeEscape(); switch (u3) { case "$": case "_": case "\u200C": case "\u200D": break; default: if (!util2.isIdContinueChar(u3)) { throw invalidIdentifier(); } break; } buffer += u3; lexState = "identifierName"; }, sign() { switch (c3) { 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 (c3) { 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 (c3) { case ".": buffer += read(); lexState = "decimalPoint"; return; case "e": case "E": buffer += read(); lexState = "decimalExponent"; return; } if (util2.isDigit(c3)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, decimalPointLeading() { if (util2.isDigit(c3)) { buffer += read(); lexState = "decimalFraction"; return; } throw invalidChar(read()); }, decimalPoint() { switch (c3) { case "e": case "E": buffer += read(); lexState = "decimalExponent"; return; } if (util2.isDigit(c3)) { buffer += read(); lexState = "decimalFraction"; return; } return newToken("numeric", sign * Number(buffer)); }, decimalFraction() { switch (c3) { case "e": case "E": buffer += read(); lexState = "decimalExponent"; return; } if (util2.isDigit(c3)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, decimalExponent() { switch (c3) { case "+": case "-": buffer += read(); lexState = "decimalExponentSign"; return; } if (util2.isDigit(c3)) { buffer += read(); lexState = "decimalExponentInteger"; return; } throw invalidChar(read()); }, decimalExponentSign() { if (util2.isDigit(c3)) { buffer += read(); lexState = "decimalExponentInteger"; return; } throw invalidChar(read()); }, decimalExponentInteger() { if (util2.isDigit(c3)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, hexadecimal() { if (util2.isHexDigit(c3)) { buffer += read(); lexState = "hexadecimalInteger"; return; } throw invalidChar(read()); }, hexadecimalInteger() { if (util2.isHexDigit(c3)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, string() { switch (c3) { 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(c3); break; case void 0: throw invalidChar(read()); } buffer += read(); }, start() { switch (c3) { case "{": case "[": return newToken("punctuator", read()); } lexState = "value"; }, beforePropertyName() { switch (c3) { 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(c3)) { buffer += read(); lexState = "identifierName"; return; } throw invalidChar(read()); }, afterPropertyName() { if (c3 === ":") { return newToken("punctuator", read()); } throw invalidChar(read()); }, beforePropertyValue() { lexState = "value"; }, afterPropertyValue() { switch (c3) { case ",": case "}": return newToken("punctuator", read()); } throw invalidChar(read()); }, beforeArrayValue() { if (c3 === "]") { return newToken("punctuator", read()); } lexState = "value"; }, afterArrayValue() { switch (c3) { case ",": case "]": return newToken("punctuator", read()); } throw invalidChar(read()); }, end() { throw invalidChar(read()); } }; function newToken(type, value) { return { type, value, line, column: column11 }; } function literal(s4) { for (const c22 of s4) { const p3 = peek(); if (p3 !== c22) { throw invalidChar(read()); } read(); } } function escape2() { const c22 = peek(); switch (c22) { 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 c22 = peek(); if (!util2.isHexDigit(c22)) { throw invalidChar(read()); } buffer2 += read(); c22 = peek(); if (!util2.isHexDigit(c22)) { throw invalidChar(read()); } buffer2 += read(); return String.fromCodePoint(parseInt(buffer2, 16)); } function unicodeEscape() { let buffer2 = ""; let count = 4; while (count-- > 0) { const c22 = peek(); if (!util2.isHexDigit(c22)) { 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(c22) { if (c22 === void 0) { return syntaxError(`JSON5: invalid end of input at ${line}:${column11}`); } return syntaxError(`JSON5: invalid character '${formatChar(c22)}' at ${line}:${column11}`); } function invalidEOF() { return syntaxError(`JSON5: invalid end of input at ${line}:${column11}`); } function invalidIdentifier() { column11 -= 5; return syntaxError(`JSON5: invalid identifier character at ${line}:${column11}`); } function separatorChar(c22) { console.warn(`JSON5: '${formatChar(c22)}' in strings is not valid ECMAScript; consider escaping`); } function formatChar(c22) { const replacements = { "'": "\\'", '"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", " ": "\\t", "\v": "\\v", "\0": "\\0", "\u2028": "\\u2028", "\u2029": "\\u2029" }; if (replacements[c22]) { return replacements[c22]; } if (c22 < " ") { const hexString = c22.charCodeAt(0).toString(16); return "\\x" + ("00" + hexString).substring(hexString.length); } return c22; } function syntaxError(message) { const err2 = new SyntaxError(message); err2.lineNumber = line; err2.columnNumber = column11; return err2; } }); var require_stringify = __commonJS3((exports3, module22) => { var util2 = require_util22(); module22.exports = function stringify2(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 v6 of replacer) { let item; if (typeof v6 === "string") { item = v6; } else if (typeof v6 === "number" || v6 instanceof String || v6 instanceof Number) { item = String(v6); } 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 i4 = 0; i4 < value2.length; i4++) { const c3 = value2[i4]; switch (c3) { case "'": case '"': quotes[c3]++; product += c3; continue; case "\0": if (util2.isDigit(value2[i4 + 1])) { product += "\\x00"; continue; } } if (replacements[c3]) { product += replacements[c3]; continue; } if (c3 < " ") { let hexString = c3.charCodeAt(0).toString(16); product += "\\x" + ("00" + hexString).substring(hexString.length); continue; } product += c3; } const quoteChar = quote || Object.keys(quotes).reduce((a3, b3) => quotes[a3] < quotes[b3] ? a3 : b3); 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 i4 = firstChar.length; i4 < key.length; i4++) { if (!util2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i4)))) { 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 i4 = 0; i4 < value2.length; i4++) { const propertyString = serializeProperty(String(i4), 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_lib32 = __commonJS3((exports3, module22) => { var parse4 = require_parse3(); var stringify2 = require_stringify(); var JSON5 = { parse: parse4, stringify: stringify2 }; module22.exports = JSON5; }); var require_strip_bom = __commonJS3((exports3, module22) => { "use strict"; module22.exports = (x4) => { if (typeof x4 !== "string") { throw new TypeError("Expected a string, got " + typeof x4); } if (x4.charCodeAt(0) === 65279) { return x4.slice(1); } return x4; }; }); var require_tsconfig_loader = __commonJS3((exports3) => { "use strict"; var __assign2 = exports3 && exports3.__assign || function() { __assign2 = Object.assign || function(t4) { for (var s4, i4 = 1, n3 = arguments.length; i4 < n3; i4++) { s4 = arguments[i4]; for (var p3 in s4) if (Object.prototype.hasOwnProperty.call(s4, p3)) t4[p3] = s4[p3]; } return t4; }; return __assign2.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_lib32(); var StripBom = require_strip_bom(); function tsConfigLoader(_a2) { var getEnv = _a2.getEnv, cwd = _a2.cwd, _b = _a2.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 (e4) { throw new Error("".concat(configFilePath, " is malformed ").concat(e4.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 _a2; 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 ((_a2 = config.compilerOptions) === null || _a2 === void 0 ? void 0 : _a2.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 __assign2(__assign2(__assign2({}, base), config), { compilerOptions: __assign2(__assign2({}, 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(_a2) { var cwd = _a2.cwd, explicitParams = _a2.explicitParams, _b = _a2.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 o3 = obj; keys.slice(0, -1).forEach(function(key2) { o3 = o3[key2] || {}; }); var key = keys[keys.length - 1]; return key in o3; } function isNumber(x4) { if (typeof x4 === "number") { return true; } if (/^0x[0-9a-f]+$/i.test(x4)) { return true; } return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x4); } 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(x4) { return flags.bools[x4]; }); } Object.keys(opts.alias || {}).forEach(function(key2) { aliases[key2] = [].concat(opts.alias[key2]); aliases[key2].forEach(function(x4) { aliases[x4] = [key2].concat(aliases[key2].filter(function(y2) { return x4 !== y2; })); }); }); [].concat(opts.string).filter(Boolean).forEach(function(key2) { flags.strings[key2] = true; if (aliases[key2]) { [].concat(aliases[key2]).forEach(function(k3) { flags.strings[k3] = 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 o3 = obj; for (var i22 = 0; i22 < keys.length - 1; i22++) { var key2 = keys[i22]; if (isConstructorOrProto(o3, key2)) { return; } if (o3[key2] === void 0) { o3[key2] = {}; } if (o3[key2] === Object.prototype || o3[key2] === Number.prototype || o3[key2] === String.prototype) { o3[key2] = {}; } if (o3[key2] === Array.prototype) { o3[key2] = []; } o3 = o3[key2]; } var lastKey = keys[keys.length - 1]; if (isConstructorOrProto(o3, lastKey)) { return; } if (o3 === Object.prototype || o3 === Number.prototype || o3 === String.prototype) { o3 = {}; } if (o3 === Array.prototype) { o3 = []; } if (o3[lastKey] === void 0 || flags.bools[lastKey] || typeof o3[lastKey] === "boolean") { o3[lastKey] = value2; } else if (Array.isArray(o3[lastKey])) { o3[lastKey].push(value2); } else { o3[lastKey] = [o3[lastKey], value2]; } } function setArg(key2, val2, arg2) { if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) { if (flags.unknownFn(arg2) === false) { return; } } var value2 = !flags.strings[key2] && isNumber(val2) ? Number(val2) : val2; setKey(argv, key2.split("."), value2); (aliases[key2] || []).forEach(function(x4) { setKey(argv, x4.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 i4 = 0; i4 < args.length; i4++) { var arg = args[i4]; var key; var next; if (/^--.+=/.test(arg)) { var m4 = arg.match(/^--([^=]+)=([\s\S]*)$/); key = m4[1]; var value = m4[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[i4 + 1]; if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) { setArg(key, next, arg); i4 += 1; } else if (/^(true|false)$/.test(next)) { setArg(key, next === "true", arg); i4 += 1; } else { setArg(key, flags.strings[key] ? "" : true, arg); } } else if (/^-[^-]+/.test(arg)) { var letters = arg.slice(1, -1).split(""); var broken = false; for (var j3 = 0; j3 < letters.length; j3++) { next = arg.slice(j3 + 2); if (next === "-") { setArg(letters[j3], next, arg); continue; } if (/[A-Za-z]/.test(letters[j3]) && next[0] === "=") { setArg(letters[j3], next.slice(1), arg); broken = true; break; } if (/[A-Za-z]/.test(letters[j3]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { setArg(letters[j3], next, arg); broken = true; break; } if (letters[j3 + 1] && letters[j3 + 1].match(/\W/)) { setArg(letters[j3], arg.slice(j3 + 2), arg); broken = true; break; } else { setArg(letters[j3], flags.strings[letters[j3]] ? "" : true, arg); } } key = arg.slice(-1)[0]; if (!broken && key !== "-") { if (args[i4 + 1] && !/^(-|--)[^-]/.test(args[i4 + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) { setArg(key, args[i4 + 1], arg); i4 += 1; } else if (args[i4 + 1] && /^(true|false)$/.test(args[i4 + 1])) { setArg(key, args[i4 + 1] === "true", arg); i4 += 1; } else { setArg(key, flags.strings[key] ? "" : true, arg); } } } else { if (!flags.unknownFn || flags.unknownFn(arg) !== false) { argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); } if (opts.stopEarly) { argv._.push.apply(argv._, args.slice(i4 + 1)); break; } } } Object.keys(defaults2).forEach(function(k3) { if (!hasKey(argv, k3.split("."))) { setKey(argv, k3.split("."), defaults2[k3]); (aliases[k3] || []).forEach(function(x4) { setKey(argv, x4.split("."), defaults2[k3]); }); } }); if (opts["--"]) { argv["--"] = notFlags.slice(); } else { notFlags.forEach(function(k3) { argv._.push(k3); }); } return argv; }; }); var require_register = __commonJS3((exports3) => { "use strict"; var __spreadArray2 = exports3 && exports3.__spreadArray || function(to, from, pack) { if (pack || arguments.length === 2) for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) { if (ar || !(i4 in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i4); ar[i4] = from[i4]; } } 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 = __spreadArray2([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_lib3()); 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 index6 = quotePosition - 1; let backslashCount = 0; while (jsonString[index6] === "\\") { index6 -= 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 index6 = 0; index6 < jsonString.length; index6++) { const currentCharacter = jsonString[index6]; const nextCharacter = jsonString[index6 + 1]; if (!isInsideComment && currentCharacter === '"') { const escaped = isEscaped(jsonString, index6); if (!escaped) { isInsideString = !isInsideString; } } if (isInsideString) { continue; } if (!isInsideComment && currentCharacter + nextCharacter === "//") { result += jsonString.slice(offset, index6); offset = index6; isInsideComment = singleComment; index6++; } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") { index6++; isInsideComment = false; result += strip(jsonString, offset, index6); offset = index6; continue; } else if (isInsideComment === singleComment && currentCharacter === "\n") { isInsideComment = false; result += strip(jsonString, offset, index6); offset = index6; } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") { result += jsonString.slice(offset, index6); offset = index6; isInsideComment = multiComment; index6++; continue; } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") { index6++; isInsideComment = false; result += strip(jsonString, offset, index6 + 1); offset = index6 + 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 (_3) { 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) => { const { data, path: path4 } = joycon.loadSync(["tsconfig.json", "jsconfig.json"], cwd); if (path4 && data) { return data; } 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 map2 = {}; function installSourceMapSupport() { if (_process2.default.setSourceMapsEnabled) { ; _process2.default.setSourceMapsEnabled(true); } else { import_source_map_support.default.install({ handleUncaughtExceptions: false, environment: "node", retrieveSourceMap(file) { if (map2[file]) { return { url: file, map: map2[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 tsconfigRaw = getOptions(dir); format = format != null ? format : inferPackageFormat(dir, filename); const result = _esbuild.transformSync.call(void 0, code, { sourcefile: filename, loader: getLoader(filename), sourcemap: "both", tsconfigRaw, 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_esm(); init_getTablesFilterByExtensions(); init_global(); init_schemaValidator(); init_serializer(); init_cli(); init_common(); init_gel(); init_libsql(); init_mysql(); init_outputs(); init_postgres(); init_singlestore(); init_sqlite(); init_studio(); init_views(); assertES5 = async (unregister) => { try { init_es5(); } catch (e4) { if ("errors" in e4 && Array.isArray(e4.errors) && e4.errors.length > 0) { const es5Error = e4.errors.filter((it) => { var _a2; return (_a2 = it.text) == null ? void 0 : _a2.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(e4); 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; if (config.dialect === "gel") { console.log( error( `You can't use 'drop' command with Gel dialect` ) ); process.exit(1); } return { out: config.out || "drizzle", bundle: config.driver === "expo" }; }; prepareGenerateConfig = async (options, from) => { var _a2; 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 ? (_a2 = config.migrations) == null ? void 0 : _a2.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) { printConfigConnectionIssues4(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) { printConfigConnectionIssues3(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) { printConfigConnectionIssues5(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) { printConfigConnectionIssues6(config, "push"); 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) { printConfigConnectionIssues6(config, "push"); 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 }; } if (config.dialect === "gel") { console.log( error( `You can't use 'push' command with Gel dialect` ) ); process.exit(1); } assertUnreachable(config.dialect); }; preparePullConfig = async (options, from) => { var _a2, _b, _c, _d, _e, _f; 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) { printConfigConnectionIssues4(config); process.exit(1); } return { dialect: "postgresql", out: config.out, breakpoints: config.breakpoints, casing: config.casing, credentials: parsed2.data, tablesFilter, schemasFilter, prefix: ((_a2 = config.migrations) == null ? void 0 : _a2.prefix) || "index", entities: config.entities }; } if (dialect6 === "mysql") { const parsed2 = mysqlCredentials.safeParse(config); if (!parsed2.success) { printConfigConnectionIssues3(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) { printConfigConnectionIssues5(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) { printConfigConnectionIssues6(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) { printConfigConnectionIssues2(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 }; } if (dialect6 === "gel") { const parsed2 = gelCredentials.safeParse(config); if (!parsed2.success) { printConfigConnectionIssues(config); process.exit(1); } return { dialect: dialect6, out: config.out, breakpoints: config.breakpoints, casing: config.casing, credentials: parsed2.data, tablesFilter, schemasFilter, prefix: ((_f = config.migrations) == null ? void 0 : _f.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, casing: casing2 } = result.data; const flattened = flattenDatabaseCredentials(config); if (dialect6 === "postgresql") { const parsed = postgresCredentials.safeParse(flattened); if (!parsed.success) { printConfigConnectionIssues4(flattened); process.exit(1); } const credentials2 = parsed.data; return { dialect: dialect6, schema: schema6, host, port, credentials: credentials2, casing: casing2 }; } if (dialect6 === "mysql") { const parsed = mysqlCredentials.safeParse(flattened); if (!parsed.success) { printConfigConnectionIssues3(flattened); process.exit(1); } const credentials2 = parsed.data; return { dialect: dialect6, schema: schema6, host, port, credentials: credentials2, casing: casing2 }; } if (dialect6 === "singlestore") { const parsed = singlestoreCredentials.safeParse(flattened); if (!parsed.success) { printConfigConnectionIssues5(flattened); process.exit(1); } const credentials2 = parsed.data; return { dialect: dialect6, schema: schema6, host, port, credentials: credentials2, casing: casing2 }; } if (dialect6 === "sqlite") { const parsed = sqliteCredentials.safeParse(flattened); if (!parsed.success) { printConfigConnectionIssues6(flattened, "studio"); process.exit(1); } const credentials2 = parsed.data; return { dialect: dialect6, schema: schema6, host, port, credentials: credentials2, casing: casing2 }; } if (dialect6 === "turso") { const parsed = libSQLCredentials.safeParse(flattened); if (!parsed.success) { printConfigConnectionIssues2(flattened, "studio"); process.exit(1); } const credentials2 = parsed.data; return { dialect: dialect6, schema: schema6, host, port, credentials: credentials2, casing: casing2 }; } if (dialect6 === "gel") { console.log( error( `You can't use 'studio' command with Gel dialect` ) ); process.exit(1); } 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: table6 } = parsed.data.migrations || {}; const flattened = flattenDatabaseCredentials(config); if (dialect6 === "postgresql") { const parsed2 = postgresCredentials.safeParse(flattened); if (!parsed2.success) { printConfigConnectionIssues4(flattened); process.exit(1); } const credentials2 = parsed2.data; return { dialect: dialect6, out, credentials: credentials2, schema: schema6, table: table6 }; } if (dialect6 === "mysql") { const parsed2 = mysqlCredentials.safeParse(flattened); if (!parsed2.success) { printConfigConnectionIssues3(flattened); process.exit(1); } const credentials2 = parsed2.data; return { dialect: dialect6, out, credentials: credentials2, schema: schema6, table: table6 }; } if (dialect6 === "singlestore") { const parsed2 = singlestoreCredentials.safeParse(flattened); if (!parsed2.success) { printConfigConnectionIssues5(flattened); process.exit(1); } const credentials2 = parsed2.data; return { dialect: dialect6, out, credentials: credentials2, schema: schema6, table: table6 }; } if (dialect6 === "sqlite") { const parsed2 = sqliteCredentials.safeParse(flattened); if (!parsed2.success) { printConfigConnectionIssues6(flattened, "migrate"); process.exit(1); } const credentials2 = parsed2.data; return { dialect: dialect6, out, credentials: credentials2, schema: schema6, table: table6 }; } if (dialect6 === "turso") { const parsed2 = libSQLCredentials.safeParse(flattened); if (!parsed2.success) { printConfigConnectionIssues2(flattened, "migrate"); process.exit(1); } const credentials2 = parsed2.data; return { dialect: dialect6, out, credentials: credentials2, schema: schema6, table: table6 }; } if (dialect6 === "gel") { console.log( error( `You can't use 'migrate' command with Gel dialect` ) ); process.exit(1); } 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((t4) => { if ((0, import_drizzle_orm.is)(t4, import_mysql_core.MySqlTable)) { tables.push(t4); } if ((0, import_drizzle_orm.is)(t4, import_mysql_core.MySqlView)) { views.push(t4); } }); return { tables, views }; }; prepareFromMySqlImports = async (imports) => { const tables = []; const views = []; const { unregister } = await safeRegister(); for (let i4 = 0; i4 < imports.length; i4++) { const it = imports[i4]; 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(column11, casing2) { if (!column11.name) return ""; return !column11.keyAsName || casing2 === void 0 ? column11.name : casing2 === "camelCase" ? (0, import_casing.toCamelCase)(column11.name) : (0, import_casing.toSnakeCase)(column11.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((v6) => `'${escapeSingleQuotes(v6.substring(1, v6.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 table6 of tables) { const { name: tableName, columns, indexes, foreignKeys, schema: schema6, checks, primaryKeys, uniqueConstraints } = (0, import_mysql_core2.getTableConfig)(table6); const columnsObject = {}; const indexesObject = {}; const foreignKeysObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; const checkConstraintObject = {}; let checksInTable = {}; columns.forEach((column11) => { const name = getColumnCasing(column11, casing2); const notNull = column11.notNull; const sqlType = column11.getSQLType(); const sqlTypeLowered = sqlType.toLowerCase(); const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement; const generated = column11.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: column11.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 (column11.primary) { primaryKeysObject[`${tableName}_${name}`] = { name: `${tableName}_${name}`, columns: [name] }; } if (column11.isUnique) { const existingUnique = uniqueConstraintObject[column11.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( column11.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[column11.uniqueName] = { name: column11.uniqueName, columns: [columnToSet.name] }; } if (column11.default !== void 0) { if ((0, import_drizzle_orm2.is)(column11.default, import_drizzle_orm2.SQL)) { columnToSet.default = sqlToStr(column11.default, casing2); } else { if (typeof column11.default === "string") { columnToSet.default = `'${escapeSingleQuotes(column11.default)}'`; } else { if (sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column11.default)}'`; } else if (column11.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) { columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`; } } else { columnToSet.default = column11.default; } } if (["blob", "text", "json"].includes(column11.getSQLType())) { columnToSet.default = `(${columnToSet.default})`; } } } columnsObject[name] = columnToSet; }); primaryKeys.map((pk) => { const originalColumnNames = pk.columns.map((c3) => c3.name); const columnNames = pk.columns.map((c3) => getColumnCasing(c3, casing2)); let name = pk.getName(); if (casing2 !== void 0) { for (let i4 = 0; i4 < originalColumnNames.length; i4++) { name = name.replace(originalColumnNames[i4], columnNames[i4]); } } primaryKeysObject[name] = { name, columns: columnNames }; for (const column11 of pk.columns) { columnsObject[getColumnCasing(column11, casing2)].notNull = true; } }); uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => { const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2)); const name = unq.name ?? (0, import_mysql_core2.uniqueKeyName)(table6, columnNames); const existingUnique = uniqueConstraintObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique constraint ${source_default.underline.blue( name )} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns ` )}` ); process.exit(1); } uniqueConstraintObject[name] = { name: unq.name, columns: columnNames }; }); const fks = foreignKeys.map((fk5) => { const tableFrom = tableName; const onDelete = fk5.onDelete ?? "no action"; const onUpdate = fk5.onUpdate ?? "no action"; const reference = fk5.reference(); const referenceFT = reference.foreignTable; const tableTo = (0, import_drizzle_orm2.getTableName)(referenceFT); const originalColumnsFrom = reference.columns.map((it) => it.name); const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2)); const originalColumnsTo = reference.foreignColumns.map((it) => it.name); const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2)); let name = fk5.getName(); if (casing2 !== void 0) { for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) { name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]); } for (let i4 = 0; i4 < originalColumnsTo.length; i4++) { name = name.replace(originalColumnsTo[i4], columnsTo[i4]); } } 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 _a2; 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 ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") { internal.indexes[name].columns[sql] = { isExpression: true }; } else { internal.indexes[name].columns[sql].isExpression = true; } } return sql; } else { return `${getColumnCasing(it, casing2)}`; } }); if (value.config.unique) { if (typeof uniqueConstraintObject[name] !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique index ${source_default.underline.blue( name )} on the ${source_default.underline.blue( indexColumns.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( uniqueConstraintObject[name].columns.join(",") )} columns ` )}` ); process.exit(1); } } else { if (typeof foreignKeysObject[name] !== "undefined") { console.log( ` ${withStyle.errorWarning( `In MySQL, when creating a foreign key, an index is automatically generated with the same name as the foreign key constraint. We have encountered a collision between the index name on columns ${source_default.underline.blue( indexColumns.join(",") )} and the foreign key on columns ${source_default.underline.blue( foreignKeysObject[name].columnsFrom.join(",") )}. Please change either the index name or the foreign key name. For more information, please refer to https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html ` )}` ); process.exit(1); } } indexesObject[name] = { name, columns: indexColumns, isUnique: value.config.unique ?? false, using: value.config.using, algorithm: value.config.algorithm, lock: value.config.lock }; }); checks.forEach((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 view5 of views) { const { isExisting, name, query, schema: schema6, selectedFields, algorithm, sqlSecurity, withCheckOption } = (0, import_mysql_core2.getViewConfig)(view5); const columnsObject = {}; const existingView = resultViews[name]; if (typeof existingView !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated view name across ${source_default.underline.blue( schema6 ?? "public" )} schema. Please rename your view` )}` ); process.exit(1); } for (const key in selectedFields) { if ((0, import_drizzle_orm2.is)(selectedFields[key], import_mysql_core2.MySqlColumn)) { const column11 = selectedFields[key]; const notNull = column11.notNull; const sqlTypeLowered = column11.getSQLType().toLowerCase(); const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement; const generated = column11.generated; const columnToSet = { name: column11.name, type: column11.getSQLType(), primaryKey: false, // If field is autoincrement it's notNull by default // notNull: autoIncrement ? true : notNull, notNull, autoincrement: autoIncrement, onUpdate: column11.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 (column11.default !== void 0) { if ((0, import_drizzle_orm2.is)(column11.default, import_drizzle_orm2.SQL)) { columnToSet.default = sqlToStr(column11.default, casing2); } else { if (typeof column11.default === "string") { columnToSet.default = `'${column11.default}'`; } else { if (sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column11.default)}'`; } else if (column11.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) { columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`; } } else { columnToSet.default = column11.default; } } if (["blob", "text", "json"].includes(column11.getSQLType())) { columnToSet.default = `(${columnToSet.default})`; } } } columnsObject[column11.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 = (table6) => true, progressCallback) => { const result = {}; const internals = { tables: {}, indexes: {} }; const columns = await db.query(`select * from information_schema.columns where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations' order by table_name, ordinal_position;`); const response = columns; const schemas = []; let columnsCount = 0; let tablesCount = /* @__PURE__ */ new Set(); let indexesCount = 0; let foreignKeysCount = 0; let checksCount = 0; let viewsCount = 0; const idxs = await db.query( `select * from INFORMATION_SCHEMA.STATISTICS WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';` ); const idxRows = idxs; for (const column11 of response) { if (!tablesFilter(column11["TABLE_NAME"])) continue; columnsCount += 1; if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const schema6 = column11["TABLE_SCHEMA"]; const tableName = column11["TABLE_NAME"]; tablesCount.add(`${schema6}.${tableName}`); if (progressCallback) { progressCallback("columns", tablesCount.size, "fetching"); } const columnName = column11["COLUMN_NAME"]; const isNullable = column11["IS_NULLABLE"] === "YES"; const dataType = column11["DATA_TYPE"]; const columnType = column11["COLUMN_TYPE"]; const isPrimary = column11["COLUMN_KEY"] === "PRI"; const columnDefault = column11["COLUMN_DEFAULT"]; const collation = column11["CHARACTER_SET_NAME"]; const geenratedExpression = column11["GENERATION_EXPRESSION"]; let columnExtra = column11["EXTRA"]; let isAutoincrement = false; let isDefaultAnExpression = false; if (typeof column11["EXTRA"] !== "undefined") { columnExtra = column11["EXTRA"]; isAutoincrement = column11["EXTRA"] === "auto_increment"; isDefaultAnExpression = column11["EXTRA"].includes("DEFAULT_GENERATED"); } if (schema6 !== inputSchema) { schemas.push(schema6); } const table6 = result[tableName]; let changedType = columnType; if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) { const uniqueIdx = idxRows.filter( (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0 ); if (uniqueIdx && uniqueIdx.length === 1) { changedType = columnType.replace("bigint unsigned", "serial"); } } if (columnType.includes("decimal(10,0)")) { changedType = columnType.replace("decimal(10,0)", "decimal"); } let onUpdate = void 0; if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) { onUpdate = true; } const newColumn = { default: columnDefault === null || columnDefault === void 0 ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${escapeSingleQuotes(columnDefault)}'`, autoincrement: isAutoincrement, name: columnName, type: changedType, primaryKey: false, notNull: !isNullable, onUpdate, generated: geenratedExpression ? { as: geenratedExpression, type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored" } : void 0 }; if (isDefaultAnExpression) { if (typeof internals.tables[tableName] === "undefined") { internals.tables[tableName] = { columns: { [columnName]: { isDefaultAnExpression: true } } }; } else { if (typeof internals.tables[tableName].columns[columnName] === "undefined") { internals.tables[tableName].columns[columnName] = { isDefaultAnExpression: true }; } else { internals.tables[tableName].columns[columnName].isDefaultAnExpression = true; } } } if (!table6) { result[tableName] = { name: tableName, columns: { [columnName]: newColumn }, compositePrimaryKeys: {}, indexes: {}, foreignKeys: {}, uniqueConstraints: {}, checkConstraint: {} }; } else { result[tableName].columns[columnName] = newColumn; } } const tablePks = await db.query( `SELECT table_name, column_name, ordinal_position FROM information_schema.table_constraints t LEFT JOIN information_schema.key_column_usage k USING(constraint_name,table_schema,table_name) WHERE t.constraint_type='PRIMARY KEY' and table_name != '__drizzle_migrations' AND t.table_schema = '${inputSchema}' ORDER BY ordinal_position` ); const tableToPk = {}; const tableToPkRows = tablePks; for (const tableToPkRow of tableToPkRows) { const tableName = tableToPkRow["TABLE_NAME"]; const columnName = tableToPkRow["COLUMN_NAME"]; const position = tableToPkRow["ordinal_position"]; if (typeof result[tableName] === "undefined") { continue; } if (typeof tableToPk[tableName] === "undefined") { tableToPk[tableName] = [columnName]; } else { tableToPk[tableName].push(columnName); } } for (const [key, value] of Object.entries(tableToPk)) { result[key].compositePrimaryKeys = { [`${key}_${value.join("_")}`]: { name: `${key}_${value.join("_")}`, columns: value } }; } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("tables", tablesCount.size, "done"); } try { const fks = await db.query( `SELECT kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME, rc.UPDATE_RULE, rc.DELETE_RULE FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu LEFT JOIN information_schema.referential_constraints rc ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME WHERE kcu.TABLE_SCHEMA = '${inputSchema}' AND kcu.CONSTRAINT_NAME != 'PRIMARY' AND kcu.REFERENCED_TABLE_NAME IS NOT NULL;` ); const fkRows = fks; for (const fkRow of fkRows) { foreignKeysCount += 1; if (progressCallback) { progressCallback("fks", foreignKeysCount, "fetching"); } const tableSchema = fkRow["TABLE_SCHEMA"]; const tableName = fkRow["TABLE_NAME"]; const constraintName = fkRow["CONSTRAINT_NAME"]; const columnName = fkRow["COLUMN_NAME"]; const refTableSchema = fkRow["REFERENCED_TABLE_SCHEMA"]; const refTableName = fkRow["REFERENCED_TABLE_NAME"]; const refColumnName = fkRow["REFERENCED_COLUMN_NAME"]; const updateRule = fkRow["UPDATE_RULE"]; const deleteRule = fkRow["DELETE_RULE"]; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; if (typeof tableInResult.foreignKeys[constraintName] !== "undefined") { tableInResult.foreignKeys[constraintName].columnsFrom.push(columnName); tableInResult.foreignKeys[constraintName].columnsTo.push( refColumnName ); } else { tableInResult.foreignKeys[constraintName] = { name: constraintName, tableFrom: tableName, tableTo: refTableName, columnsFrom: [columnName], columnsTo: [refColumnName], onDelete: deleteRule == 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 (e4) { } if (progressCallback) { progressCallback("fks", foreignKeysCount, "done"); } for (const idxRow of idxRows) { const tableSchema = idxRow["TABLE_SCHEMA"]; const tableName = idxRow["TABLE_NAME"]; const constraintName = idxRow["INDEX_NAME"]; const columnName = idxRow["COLUMN_NAME"]; const isUnique = idxRow["NON_UNIQUE"] === 0; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; indexesCount += 1; if (progressCallback) { progressCallback("indexes", indexesCount, "fetching"); } if (isUnique) { if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") { tableInResult.uniqueConstraints[constraintName].columns.push( columnName ); } else { tableInResult.uniqueConstraints[constraintName] = { name: constraintName, columns: [columnName] }; } } else { if (typeof tableInResult.foreignKeys[constraintName] === "undefined") { if (typeof tableInResult.indexes[constraintName] !== "undefined") { tableInResult.indexes[constraintName].columns.push(columnName); } else { tableInResult.indexes[constraintName] = { name: constraintName, columns: [columnName], isUnique }; } } } } const views = await db.query( `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';` ); const resultViews = {}; viewsCount = views.length; if (progressCallback) { progressCallback("views", viewsCount, "fetching"); } for await (const view5 of views) { const viewName = view5["TABLE_NAME"]; const definition = view5["VIEW_DEFINITION"]; const withCheckOption = view5["CHECK_OPTION"] === "NONE" ? void 0 : view5["CHECK_OPTION"].toLowerCase(); const sqlSecurity = view5["SECURITY_TYPE"].toLowerCase(); const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`); const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/); const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0; const columns2 = result[viewName].columns; delete result[viewName]; resultViews[viewName] = { columns: columns2, isExisting: false, name: viewName, algorithm, definition, sqlSecurity, withCheckOption }; } if (progressCallback) { progressCallback("indexes", indexesCount, "done"); progressCallback("enums", 0, "done"); progressCallback("views", viewsCount, "done"); } const checkConstraints = await db.query( `SELECT tc.table_name, tc.constraint_name, cc.check_clause FROM information_schema.table_constraints tc JOIN information_schema.check_constraints cc ON tc.constraint_name = cc.constraint_name WHERE tc.constraint_schema = '${inputSchema}' AND tc.constraint_type = 'CHECK';` ); checksCount += checkConstraints.length; if (progressCallback) { progressCallback("checks", checksCount, "fetching"); } for (const checkConstraintRow of checkConstraints) { const constraintName = checkConstraintRow["CONSTRAINT_NAME"]; const constraintValue = checkConstraintRow["CHECK_CLAUSE"]; const tableName = checkConstraintRow["TABLE_NAME"]; const tableInResult = result[tableName]; tableInResult.checkConstraint[constraintName] = { name: constraintName, value: constraintValue }; } if (progressCallback) { progressCallback("checks", checksCount, "done"); } return { version: "5", dialect: "mysql", tables: result, views: resultViews, _meta: { tables: {}, columns: {} }, internal: internals }; }; } }); // src/serializer/pgImports.ts var pgImports_exports = {}; __export(pgImports_exports, { prepareFromExports: () => prepareFromExports2, prepareFromPgImports: () => prepareFromPgImports }); var import_drizzle_orm3, import_pg_core, import_relations, 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"); import_relations = require("drizzle-orm/relations"); init_utils3(); prepareFromExports2 = (exports2) => { const tables = []; const enums = []; const schemas = []; const sequences = []; const roles = []; const policies = []; const views = []; const matViews = []; const relations5 = []; const i0values = Object.values(exports2); i0values.forEach((t4) => { if ((0, import_pg_core.isPgEnum)(t4)) { enums.push(t4); return; } if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgTable)) { tables.push(t4); } if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgSchema)) { schemas.push(t4); } if ((0, import_pg_core.isPgView)(t4)) { views.push(t4); } if ((0, import_pg_core.isPgMaterializedView)(t4)) { matViews.push(t4); } if ((0, import_pg_core.isPgSequence)(t4)) { sequences.push(t4); } if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgRole)) { roles.push(t4); } if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgPolicy)) { policies.push(t4); } if ((0, import_drizzle_orm3.is)(t4, import_relations.Relations)) { relations5.push(t4); } }); return { tables, enums, schemas, sequences, views, matViews, roles, policies, relations: relations5 }; }; prepareFromPgImports = async (imports) => { const tables = []; const enums = []; const schemas = []; const sequences = []; const views = []; const roles = []; const policies = []; const matViews = []; const relations5 = []; const { unregister } = await safeRegister(); for (let i4 = 0; i4 < imports.length; i4++) { const it = imports[i4]; 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); relations5.push(...prepared.relations); } unregister(); return { tables: Array.from(new Set(tables)), enums, schemas, sequences, views, matViews, roles, policies, relations: relations5 }; }; } }); // 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 _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _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 table6 of tables) { const checksInTable = {}; const { name: tableName, columns, indexes, foreignKeys, checks, schema: schema6, primaryKeys, uniqueConstraints, policies: policies2, enableRLS } = (0, import_pg_core2.getTableConfig)(table6); if (schemaFilter && !schemaFilter.includes(schema6 ?? "public")) { continue; } const columnsObject = {}; const indexesObject = {}; const checksObject = {}; const foreignKeysObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; const policiesObject = {}; columns.forEach((column11) => { var _a3, _b2, _c2, _d2, _e2, _f2; const name = getColumnCasing(column11, casing2); const notNull = column11.notNull; const primaryKey = column11.primary; const sqlTypeLowered = column11.getSQLType().toLowerCase(); const getEnumSchema = (column12) => { while ((0, import_drizzle_orm4.is)(column12, import_pg_core2.PgArray)) { column12 = column12.baseColumn; } return (0, import_drizzle_orm4.is)(column12, import_pg_core2.PgEnumColumn) ? column12.enum.schema || "public" : void 0; }; const typeSchema = getEnumSchema(column11); const generated = column11.generated; const identity = column11.generatedIdentity; const increment = stringFromIdentityProperty((_a3 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _a3.increment) ?? "1"; const minValue = stringFromIdentityProperty((_b2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _b2.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column11.columnType) : "1"); const maxValue = stringFromIdentityProperty((_c2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _c2.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column11.getSQLType())); const startWith = stringFromIdentityProperty((_d2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _d2.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue); const cache3 = stringFromIdentityProperty((_e2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _e2.cache) ?? "1"; const columnToSet = { name, type: column11.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: cache3, cycle: ((_f2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _f2.cycle) ?? false } : void 0 }; if (column11.isUnique) { const existingUnique = uniqueConstraintObject[column11.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( column11.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[column11.uniqueName] = { name: column11.uniqueName, nullsNotDistinct: column11.uniqueType === "not distinct", columns: [columnToSet.name] }; } if (column11.default !== void 0) { if ((0, import_drizzle_orm4.is)(column11.default, import_drizzle_orm4.SQL)) { columnToSet.default = sqlToStr(column11.default, casing2); } else { if (typeof column11.default === "string") { columnToSet.default = `'${escapeSingleQuotes(column11.default)}'`; } else { if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column11.default)}'::${sqlTypeLowered}`; } else if (column11.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered === "timestamp") { columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`; } else { columnToSet.default = `'${column11.default.toISOString()}'`; } } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column11.default)) { columnToSet.default = `'${buildArrayString(column11.default, sqlTypeLowered)}'`; } else { columnToSet.default = column11.default; } } } } columnsObject[name] = columnToSet; }); primaryKeys.map((pk) => { const originalColumnNames = pk.columns.map((c3) => c3.name); const columnNames = pk.columns.map((c3) => getColumnCasing(c3, casing2)); let name = pk.getName(); if (casing2 !== void 0) { for (let i4 = 0; i4 < originalColumnNames.length; i4++) { name = name.replace(originalColumnNames[i4], columnNames[i4]); } } primaryKeysObject[name] = { name, columns: columnNames }; }); uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => { const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2)); const name = unq.name ?? (0, import_pg_core2.uniqueKeyName)(table6, columnNames); const existingUnique = uniqueConstraintObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table. The unique constraint ${source_default.underline.blue(name)} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns ` )}` ); process.exit(1); } uniqueConstraintObject[name] = { name: unq.name, nullsNotDistinct: unq.nullsNotDistinct, columns: columnNames }; }); const fks = foreignKeys.map((fk5) => { const tableFrom = tableName; const onDelete = fk5.onDelete; const onUpdate = fk5.onUpdate; const reference = fk5.reference(); const tableTo = (0, import_drizzle_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 = fk5.getName(); if (casing2 !== void 0) { for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) { name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]); } for (let i4 = 0; i4 < originalColumnsTo.length; i4++) { name = name.replace(originalColumnsTo[i4], columnsTo[i4]); } } 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 _a3, _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: ((_a3 = it.indexConfig) == null ? void 0 : _a3.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((policy5) => { var _a3, _b2; const mappedTo = []; if (!policy5.to) { mappedTo.push("public"); } else { if (policy5.to && typeof policy5.to === "string") { mappedTo.push(policy5.to); } else if (policy5.to && (0, import_drizzle_orm4.is)(policy5.to, import_pg_core2.PgRole)) { mappedTo.push(policy5.to.name); } else if (policy5.to && Array.isArray(policy5.to)) { policy5.to.forEach((it) => { if (typeof it === "string") { mappedTo.push(it); } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) { mappedTo.push(it.name); } }); } } if (policiesObject[policy5.name] !== void 0) { console.log( ` ${withStyle.errorWarning( `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue( policy5.name )} name` )}` ); process.exit(1); } policiesObject[policy5.name] = { name: policy5.name, as: ((_a3 = policy5.as) == null ? void 0 : _a3.toUpperCase()) ?? "PERMISSIVE", for: ((_b2 = policy5.for) == null ? void 0 : _b2.toUpperCase()) ?? "ALL", to: mappedTo.sort(), using: (0, import_drizzle_orm4.is)(policy5.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0, withCheck: (0, import_drizzle_orm4.is)(policy5.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.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 policy5 of policies) { if (!policy5._linkedTable) { console.log( ` ${withStyle.errorWarning( `"Policy ${policy5.name} was skipped because it was not linked to any table. You should either include the policy in a table or use .link() on the policy to link it to any table you have. For more information, please check:` )}` ); continue; } const tableConfig = (0, import_pg_core2.getTableConfig)(policy5._linkedTable); const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`; const mappedTo = []; if (!policy5.to) { mappedTo.push("public"); } else { if (policy5.to && typeof policy5.to === "string") { mappedTo.push(policy5.to); } else if (policy5.to && (0, import_drizzle_orm4.is)(policy5.to, import_pg_core2.PgRole)) { mappedTo.push(policy5.to.name); } else if (policy5.to && Array.isArray(policy5.to)) { policy5.to.forEach((it) => { if (typeof it === "string") { mappedTo.push(it); } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) { mappedTo.push(it.name); } }); } } if (((_a2 = result[tableKey2]) == null ? void 0 : _a2.policies[policy5.name]) !== void 0 || policiesToReturn[policy5.name] !== void 0) { console.log( ` ${withStyle.errorWarning( `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue( policy5.name )} name` )}` ); process.exit(1); } const mappedPolicy = { name: policy5.name, as: ((_b = policy5.as) == null ? void 0 : _b.toUpperCase()) ?? "PERMISSIVE", for: ((_c = policy5.for) == null ? void 0 : _c.toUpperCase()) ?? "ALL", to: mappedTo.sort(), using: (0, import_drizzle_orm4.is)(policy5.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0, withCheck: (0, import_drizzle_orm4.is)(policy5.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0 }; if (result[tableKey2]) { result[tableKey2].policies[policy5.name] = mappedPolicy; } else { policiesToReturn[policy5.name] = { ...mappedPolicy, schema: tableConfig.schema ?? "public", on: `"${tableConfig.schema ?? "public"}"."${tableConfig.name}"` }; } } for (const sequence of sequences) { const name = sequence.seqName; if (typeof sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] === "undefined") { const increment = stringFromIdentityProperty((_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 cache3 = 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: cache3, 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 view5 of combinedViews) { let viewName; let schema6; let query; let selectedFields; let isExisting; let withOption; let tablespace; let using; let withNoData; let materialized = false; if ((0, import_drizzle_orm4.is)(view5, import_pg_core2.PgView)) { ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core2.getViewConfig)(view5)); } else { ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core2.getMaterializedViewConfig)(view5)); materialized = true; } const viewSchema = schema6 ?? "public"; const viewKey = `${viewSchema}.${viewName}`; const columnsObject = {}; const uniqueConstraintObject = {}; const existingView = resultViews[viewKey]; if (typeof existingView !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated view name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your view` )}` ); process.exit(1); } for (const key in selectedFields) { if ((0, import_drizzle_orm4.is)(selectedFields[key], import_pg_core2.PgColumn)) { const column11 = selectedFields[key]; const notNull = column11.notNull; const primaryKey = column11.primary; const sqlTypeLowered = column11.getSQLType().toLowerCase(); const typeSchema = (0, import_drizzle_orm4.is)(column11, import_pg_core2.PgEnumColumn) ? column11.enum.schema || "public" : void 0; const generated = column11.generated; const identity = column11.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(column11.columnType) : "1"); const maxValue = stringFromIdentityProperty((_l = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _l.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column11.getSQLType())); const startWith = stringFromIdentityProperty((_m2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _m2.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue); const cache3 = stringFromIdentityProperty((_n = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _n.cache) ?? "1"; const columnToSet = { name: column11.name, type: column11.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}_${column11.name}_seq`, schema: schema6 ?? "public", increment, startWith, minValue, maxValue, cache: cache3, cycle: ((_o = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _o.cycle) ?? false } : void 0 }; if (column11.isUnique) { const existingUnique = uniqueConstraintObject[column11.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(column11.uniqueName)} on the ${source_default.underline.blue( column11.name )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns ` )}` ); process.exit(1); } uniqueConstraintObject[column11.uniqueName] = { name: column11.uniqueName, nullsNotDistinct: column11.uniqueType === "not distinct", columns: [columnToSet.name] }; } if (column11.default !== void 0) { if ((0, import_drizzle_orm4.is)(column11.default, import_drizzle_orm4.SQL)) { columnToSet.default = sqlToStr(column11.default, casing2); } else { if (typeof column11.default === "string") { columnToSet.default = `'${column11.default}'`; } else { if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") { columnToSet.default = `'${JSON.stringify(column11.default)}'::${sqlTypeLowered}`; } else if (column11.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered === "timestamp") { columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`; } else { columnToSet.default = `'${column11.default.toISOString()}'`; } } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column11.default)) { columnToSet.default = `'${buildArrayString(column11.default, sqlTypeLowered)}'`; } else { columnToSet.default = column11.default; } } } } columnsObject[column11.name] = columnToSet; } } resultViews[viewKey] = { columns: columnsObject, definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql, name: viewName, schema: viewSchema, isExisting, with: withOption, withNoData, materialized, tablespace, using }; } const enumsToReturn = enums.reduce((map2, obj) => { const enumSchema4 = obj.schema || "public"; const key = `${enumSchema4}.${obj.enumName}`; map2[key] = { name: obj.enumName, schema: enumSchema4, values: obj.enumValues }; return map2; }, {}); const schemasObject = Object.fromEntries( schemas.filter((it) => { if (schemaFilter) { return schemaFilter.includes(it.schemaName) && it.schemaName !== "public"; } else { return it.schemaName !== "public"; } }).map((it) => [it.schemaName, it.schemaName]) ); return { version: "7", dialect: "postgresql", tables: result, enums: enumsToReturn, schemas: schemasObject, sequences: sequencesToReturn, roles: rolesToReturn, policies: policiesToReturn, views: resultViews, _meta: { schemas: {}, tables: {}, columns: {} } }; }; trimChar = (str, char) => { let start = 0; let end = str.length; while (start < end && str[start] === char) ++start; while (end > start && str[end - 1] === char) --end; return start > 0 || end < str.length ? str.substring(start, end) : str.toString(); }; fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => { const result = {}; const views = {}; const policies = {}; const internals = { tables: {} }; const where = schemaFilters.map((t4) => `n.nspname = '${t4}'`).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((t4) => `schemaname = '${t4}'`).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((t4) => `n.nspname = '${t4}'`).join(" or "); const allEnums = await db.query( `select n.nspname as enum_schema, t.typname as enum_name, e.enumlabel as enum_value, e.enumsortorder as sort_order from pg_type t join pg_enum e on t.oid = e.enumtypid join pg_catalog.pg_namespace n ON n.oid = t.typnamespace ${whereEnums === "" ? "" : ` WHERE ${whereEnums}`} order by enum_schema, enum_name, sort_order;` ); const enumsToReturn = {}; for (const dbEnum of allEnums) { const enumName = dbEnum.enum_name; const enumValue = dbEnum.enum_value; const enumSchema4 = dbEnum.enum_schema || "public"; const key = `${enumSchema4}.${enumName}`; if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) { enumsToReturn[key].values.push(enumValue); } else { enumsToReturn[key] = { name: enumName, values: [enumValue], schema: enumSchema4 }; } } if (progressCallback) { progressCallback("enums", Object.keys(enumsToReturn).length, "done"); } const allRoles = await db.query( `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;` ); const rolesToReturn = {}; const preparedRoles = prepareRoles(entities); if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) { for (const dbRole of allRoles) { if (preparedRoles.useRoles) { rolesToReturn[dbRole.rolname] = { createDb: dbRole.rolcreatedb, createRole: dbRole.rolcreatedb, inherit: dbRole.rolinherit, name: dbRole.rolname }; } else { if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0) continue; if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname)) continue; if (preparedRoles.excludeRoles.includes(dbRole.rolname)) continue; if (!preparedRoles.includeRoles.includes(dbRole.rolname)) continue; rolesToReturn[dbRole.rolname] = { createDb: dbRole.rolcreatedb, createRole: dbRole.rolcreaterole, inherit: dbRole.rolinherit, name: dbRole.rolname }; } } } const schemasForLinkedPoliciesInSchema = Object.values((tsSchema == null ? void 0 : tsSchema.policies) ?? {}).map((it) => it.schema); const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t4) => `schemaname = '${t4}'`).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 _a2, _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' AND con.contype = 'c';`); columnsCount += tableResponse.length; if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const tableForeignKeys = await db.query( `SELECT con.contype AS constraint_type, nsp.nspname AS constraint_schema, con.conname AS constraint_name, rel.relname AS table_name, att.attname AS column_name, fnsp.nspname AS foreign_table_schema, frel.relname AS foreign_table_name, fatt.attname AS foreign_column_name, CASE con.confupdtype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'n' THEN 'SET NULL' WHEN 'c' THEN 'CASCADE' WHEN 'd' THEN 'SET DEFAULT' END AS update_rule, CASE con.confdeltype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'n' THEN 'SET NULL' WHEN 'c' THEN 'CASCADE' WHEN 'd' THEN 'SET DEFAULT' END AS delete_rule FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey) AND att.attrelid = con.conrelid LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey) AND fatt.attrelid = con.confrelid WHERE nsp.nspname = '${tableSchema}' AND rel.relname = '${tableName}' AND con.contype IN ('f');` ); foreignKeysCount += tableForeignKeys.length; if (progressCallback) { progressCallback("fks", foreignKeysCount, "fetching"); } for (const fk5 of tableForeignKeys) { const columnFrom = fk5.column_name; const tableTo = fk5.foreign_table_name; const columnTo = fk5.foreign_column_name; const schemaTo = fk5.foreign_table_schema; const foreignKeyName = fk5.constraint_name; const onUpdate = (_a2 = fk5.update_rule) == null ? void 0 : _a2.toLowerCase(); const onDelete = (_b = fk5.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((c3) => c3.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 i4 = 1; i4 < Number(columnDimensions); i4++) { columnTypeMapped += "[]"; } } columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char"); columnTypeMapped = trimChar(columnTypeMapped, '"'); columnToReturn[columnName] = { name: columnName, type: ( // filter vectors, but in future we should filter any extension that was installed by user columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped ), typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0, primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2, // default: isSerial ? undefined : defaultValue, notNull: columnResponse.is_nullable === "NO", generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0, identity: isIdentity ? { type: identityGeneration, name: identityName, increment: stringFromDatabaseIdentityProperty(identityIncrement), minValue: stringFromDatabaseIdentityProperty(identityMinimum), maxValue: stringFromDatabaseIdentityProperty(identityMaximum), startWith: stringFromDatabaseIdentityProperty(identityStart), cache: ((_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_indexdef(i.indexrelid, k.i, false)) AS column_name, CASE WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1 ELSE 0 END AS is_expression, i.indoption[k.i-1] & 1 = 1 AS descending, i.indoption[k.i-1] & 2 = 2 AS nulls_first, pg_get_expr( i.indpred, i.indrelid ) as where, opc.opcname FROM pg_class t LEFT JOIN pg_index i ON t.oid = i.indrelid LEFT JOIN pg_class ic ON ic.oid = i.indexrelid CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i) LEFT JOIN pg_attribute AS a ON i.indrelid = a.attrelid AND k.attnum = a.attnum JOIN pg_namespace c on c.oid = t.relnamespace LEFT JOIN pg_am AS am ON ic.relam = am.oid JOIN pg_opclass opc ON opc.oid = ANY(i.indclass) WHERE c.nspname = '${tableSchema}' AND t.relname = '${tableName}';` ); const dbIndexFromConstraint = await db.query( `SELECT idx.indexrelname AS index_name, idx.relname AS table_name, schemaname, CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint FROM pg_stat_user_indexes idx LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}' group by index_name, table_name,schemaname, generated_by_constraint;` ); const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map( (it) => it.index_name ); for (const dbIndex of dbIndexes) { const indexName6 = 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(indexName6)) continue; if (typeof indexToReturn[indexName6] !== "undefined") { indexToReturn[indexName6].columns.push({ expression: indexColumnName, asc: !desc, nulls: nullsFirst ? "first" : "last", opclass, isExpression }); } else { indexToReturn[indexName6] = { name: indexName6, 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 (e4) { rej(e4); return; } res(""); }); }); if (progressCallback) { progressCallback("tables", tableCount, "done"); } for await (const _3 of all) { } const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => { return new Promise(async (res, rej) => { var _a2, _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 i4 = 1; i4 < Number(columnDimensions); i4++) { columnTypeMapped += "[]"; } } columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char"); columnTypeMapped = trimChar(columnTypeMapped, '"'); columnToReturn[columnName] = { name: columnName, type: ( // filter vectors, but in future we should filter any extension that was installed by user columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped ), typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0, primaryKey, notNull: viewResponse.is_nullable === "NO", generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0, identity: isIdentity ? { type: identityGeneration, name: identityName, increment: stringFromDatabaseIdentityProperty(identityIncrement), minValue: stringFromDatabaseIdentityProperty(identityMinimum), maxValue: stringFromDatabaseIdentityProperty(identityMaximum), startWith: stringFromDatabaseIdentityProperty(identityStart), cache: ((_a2 = sequencesToReturn[identityName]) == null ? void 0 : _a2.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 (e4) { rej(e4); return; } res(""); }); }); viewsCount = allViews.length; for await (const _3 of allViews) { } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("indexes", indexesCount, "done"); progressCallback("fks", foreignKeysCount, "done"); progressCallback("checks", checksCount, "done"); progressCallback("views", viewsCount, "done"); } const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it])); return { version: "7", dialect: "postgresql", tables: result, enums: enumsToReturn, schemas: schemasObject, sequences: sequencesToReturn, roles: rolesToReturn, policies, views, _meta: { schemas: {}, tables: {}, columns: {} }, internal: internals }; }; defaultForColumn = (column11, internals, tableName) => { var _a2, _b; const columnName = column11.column_name; const isArray = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[columnName]) == null ? void 0 : _b.isArray) ?? false; if (column11.column_default === null || column11.column_default === void 0 || column11.data_type === "serial" || column11.data_type === "smallserial" || column11.data_type === "bigserial") { return void 0; } if (column11.column_default.endsWith("[]")) { column11.column_default = column11.column_default.slice(0, -2); } column11.column_default = column11.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, ""); const columnDefaultAsString = column11.column_default.toString(); if (isArray) { return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => { if (["integer", "smallint", "bigint", "double precision", "real"].includes(column11.data_type.slice(0, -2))) { return value; } else if (column11.data_type.startsWith("timestamp")) { return `${value}`; } else if (column11.data_type.slice(0, -2) === "interval") { return value.replaceAll('"', `"`); } else if (column11.data_type.slice(0, -2) === "boolean") { return value === "t" ? "true" : "false"; } else if (["json", "jsonb"].includes(column11.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(column11.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 (column11.data_type.includes("numeric")) { return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`; } else if (column11.data_type === "json" || column11.data_type === "jsonb") { const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1))); return `'${jsonWithoutSpaces}'::${column11.data_type}`; } else if (column11.data_type === "boolean") { return column11.column_default === "true"; } else if (columnDefaultAsString === "NULL") { return `NULL`; } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) { return columnDefaultAsString; } else { return `${columnDefaultAsString.replace(/\\/g, "`\\")}`; } }; getColumnsInfoQuery = ({ schema: schema6, table: table6, db }) => { return db.query( `SELECT a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name a.attname AS column_name, -- Column name CASE WHEN NOT a.attisdropped THEN CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END ELSE NULL END AS is_nullable, -- NULL or NOT NULL constraint a.attndims AS array_dimensions, -- Array dimensions CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) AND EXISTS ( SELECT FROM pg_attrdef ad WHERE ad.adrelid = a.attrelid AND ad.adnum = a.attnum AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)' ) THEN CASE a.atttypid WHEN 'int'::regtype THEN 'serial' WHEN 'int8'::regtype THEN 'bigserial' WHEN 'int2'::regtype THEN 'smallserial' END ELSE format_type(a.atttypid, a.atttypmod) END AS data_type, -- Column data type -- ns.nspname AS type_schema, -- Schema name pg_get_serial_sequence('"${schema6}"."${table6}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any) c.column_default, -- Column default value c.data_type AS additional_dt, -- Data type from information_schema c.udt_name AS enum_name, -- Enum type (if applicable) c.is_generated, -- Is it a generated column? c.generation_expression, -- Generation expression (if generated) c.is_identity, -- Is it an identity column? c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT) c.identity_start, -- Start value of identity column c.identity_increment, -- Increment for identity column c.identity_maximum, -- Maximum value for identity column c.identity_minimum, -- Minimum value for identity column c.identity_cycle, -- Does the identity column cycle? enum_ns.nspname AS type_schema -- Schema of the enum type FROM pg_attribute a JOIN pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info JOIN pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info LEFT JOIN information_schema.columns c ON c.column_name = a.attname AND c.table_schema = ns.nspname AND c.table_name = cls.relname -- Match schema and table/view name LEFT JOIN pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info LEFT JOIN pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema WHERE a.attnum > 0 -- Valid column numbers only AND NOT a.attisdropped -- Skip dropped columns AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m') AND ns.nspname = '${schema6}' -- Filter by schema AND cls.relname = '${table6}' -- Filter by table name ORDER BY a.attnum; -- Order by column number` ); }; } }); // src/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((t4) => { if ((0, import_drizzle_orm5.is)(t4, import_sqlite_core.SQLiteTable)) { tables.push(t4); } if ((0, import_drizzle_orm5.is)(t4, import_sqlite_core.SQLiteView)) { views.push(t4); } }); return { tables, views }; }; prepareFromSqliteImports = async (imports) => { const tables = []; const views = []; const { unregister } = await safeRegister(); for (let i4 = 0; i4 < imports.length; i4++) { const it = imports[i4]; 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; } function filterIgnoredTablesByField(fieldName) { return `${fieldName} != '__drizzle_migrations' AND ${fieldName} NOT LIKE '\\_cf\\_%' ESCAPE '\\' AND ${fieldName} NOT LIKE '\\_litestream\\_%' ESCAPE '\\' AND ${fieldName} NOT LIKE 'libsql\\_%' ESCAPE '\\' AND ${fieldName} NOT LIKE 'sqlite\\_%' ESCAPE '\\'`; } var import_drizzle_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 table6 of tables) { const columnsObject = {}; const indexesObject = {}; const foreignKeysObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; const checkConstraintObject = {}; const checksInTable = {}; const { name: tableName, columns, indexes, checks, foreignKeys: tableForeignKeys, primaryKeys, uniqueConstraints } = (0, import_sqlite_core2.getTableConfig)(table6); columns.forEach((column11) => { const name = getColumnCasing(column11, casing2); const notNull = column11.notNull; const primaryKey = column11.primary; const generated = column11.generated; const columnToSet = { name, type: column11.getSQLType(), primaryKey, notNull, autoincrement: (0, import_drizzle_orm6.is)(column11, import_sqlite_core2.SQLiteBaseInteger) ? column11.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 (column11.default !== void 0) { if ((0, import_drizzle_orm6.is)(column11.default, import_drizzle_orm6.SQL)) { columnToSet.default = sqlToStr(column11.default, casing2); } else { columnToSet.default = typeof column11.default === "string" ? `'${escapeSingleQuotes(column11.default)}'` : typeof column11.default === "object" || Array.isArray(column11.default) ? `'${JSON.stringify(column11.default)}'` : column11.default; } } columnsObject[name] = columnToSet; if (column11.isUnique) { const existingUnique = indexesObject[column11.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( column11.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[column11.uniqueName] = { name: column11.uniqueName, columns: [columnToSet.name], isUnique: true }; } }); const foreignKeys = tableForeignKeys.map((fk5) => { const tableFrom = tableName; const onDelete = fk5.onDelete ?? "no action"; const onUpdate = fk5.onUpdate ?? "no action"; const reference = fk5.reference(); const referenceFT = reference.foreignTable; const tableTo = (0, import_drizzle_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 = fk5.getName(); if (casing2 !== void 0) { for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) { name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]); } for (let i4 = 0; i4 < originalColumnsTo.length; i4++) { name = name.replace(originalColumnsTo[i4], columnsTo[i4]); } } 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 _a2; 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 ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.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((c3) => getColumnCasing(c3, casing2)); const name = unq.name ?? (0, import_sqlite_core2.uniqueKeyName)(table6, columnNames); const existingUnique = indexesObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique constraint ${source_default.underline.blue( name )} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns ` )}` ); process.exit(1); } indexesObject[name] = { name: unq.name, columns: columnNames, isUnique: true }; }); primaryKeys.forEach((it) => { if (it.columns.length > 1) { const originalColumnNames = it.columns.map((c3) => c3.name); const columnNames = it.columns.map((c3) => getColumnCasing(c3, casing2)); let name = it.getName(); if (casing2 !== void 0) { for (let i4 = 0; i4 < originalColumnNames.length; i4++) { name = name.replace(originalColumnNames[i4], columnNames[i4]); } } 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 view5 of views) { const { name, isExisting, selectedFields, query, schema: schema6 } = (0, import_sqlite_core2.getViewConfig)(view5); const columnsObject = {}; const existingView = resultViews[name]; if (typeof existingView !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated view name across ${source_default.underline.blue( schema6 ?? "public" )} schema. Please rename your view` )}` ); process.exit(1); } for (const key in selectedFields) { if ((0, import_drizzle_orm6.is)(selectedFields[key], import_sqlite_core2.SQLiteColumn)) { const column11 = selectedFields[key]; const notNull = column11.notNull; const primaryKey = column11.primary; const generated = column11.generated; const columnToSet = { name: column11.name, type: column11.getSQLType(), primaryKey, notNull, autoincrement: (0, import_drizzle_orm6.is)(column11, import_sqlite_core2.SQLiteBaseInteger) ? column11.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 (column11.default !== void 0) { if ((0, import_drizzle_orm6.is)(column11.default, import_drizzle_orm6.SQL)) { columnToSet.default = sqlToStr(column11.default, casing2); } else { columnToSet.default = typeof column11.default === "string" ? `'${column11.default}'` : typeof column11.default === "object" || Array.isArray(column11.default) ? `'${JSON.stringify(column11.default)}'` : column11.default; } } columnsObject[column11.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 = (table6) => true, progressCallback) => { const result = {}; const resultViews = {}; const columns = await db.query(`SELECT m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk, p.hidden as hidden, m.sql, m.type as type FROM sqlite_master AS m JOIN pragma_table_xinfo(m.name) AS p WHERE (m.type = 'table' OR m.type = 'view') AND ${filterIgnoredTablesByField("m.tbl_name")};`); const tablesWithSeq = []; const seq = await db.query(`SELECT * FROM sqlite_master WHERE sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*' AND ${filterIgnoredTablesByField("tbl_name")};`); for (const s4 of seq) { tablesWithSeq.push(s4.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 column11 of columns) { if (!tablesFilter(column11.tableName)) continue; if (column11.type !== "view") { columnsCount += 1; } if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const tableName = column11.tableName; tablesCount.add(tableName); if (progressCallback) { progressCallback("tables", tablesCount.size, "fetching"); } const columnName = column11.columnName; const isNotNull = column11.notNull === 1; const columnType = column11.columnType; const isPrimary = column11.pk !== 0; const columnDefault = column11.defaultValue; const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName); if (isPrimary) { if (typeof tableToPk[tableName] === "undefined") { tableToPk[tableName] = [columnName]; } else { tableToPk[tableName].push(columnName); } } const table6 = result[tableName]; if (column11.hidden === 2 || column11.hidden === 3) { if (typeof tableToGeneratedColumnsInfo[column11.tableName] === "undefined") { tableToGeneratedColumnsInfo[column11.tableName] = extractGeneratedColumns( column11.sql ); } } const newColumn = { default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes( columnDefault ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : `(${columnDefault})`, autoincrement: isAutoincrement, name: columnName, type: mapSqlToSqliteType(columnType), primaryKey: false, notNull: isNotNull, generated: tableToGeneratedColumnsInfo[tableName] && tableToGeneratedColumnsInfo[tableName][columnName] ? { type: tableToGeneratedColumnsInfo[tableName][columnName].type, as: tableToGeneratedColumnsInfo[tableName][columnName].expression } : void 0 }; if (!table6) { result[tableName] = { name: tableName, columns: { [columnName]: newColumn }, compositePrimaryKeys: {}, indexes: {}, foreignKeys: {}, uniqueConstraints: {}, checkConstraints: {} }; } else { result[tableName].columns[columnName] = newColumn; } } for (const [key, value] of Object.entries(tableToPk)) { if (value.length > 1) { result[key].compositePrimaryKeys = { [`${key}_${value.join("_")}_pk`]: { columns: value, name: `${key}_${value.join("_")}_pk` } }; } else if (value.length === 1) { result[key].columns[value[0]].primaryKey = true; } else { } } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("tables", tablesCount.size, "done"); } try { const fks = await db.query(`SELECT m.name as "tableFrom", f.id as "id", f."table" as "tableTo", f."from", f."to", f."on_update" as "onUpdate", f."on_delete" as "onDelete", f.seq as "seq" FROM sqlite_master m, pragma_foreign_key_list(m.name) as f WHERE ${filterIgnoredTablesByField("m.tbl_name")};`); const fkByTableName = {}; for (const fkRow of fks) { foreignKeysCount += 1; if (progressCallback) { progressCallback("fks", foreignKeysCount, "fetching"); } const tableName = fkRow.tableFrom; const columnName = fkRow.from; const refTableName = fkRow.tableTo; const refColumnName = fkRow.to; const updateRule = fkRow.onUpdate; const deleteRule = fkRow.onDelete; const sequence = fkRow.seq; const id = fkRow.id; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") { fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName); fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName); } else { fkByTableName[`${tableName}_${id}`] = { name: "", tableFrom: tableName, tableTo: refTableName, columnsFrom: [columnName], columnsTo: [refColumnName], onDelete: deleteRule == 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 (e4) { } if (progressCallback) { progressCallback("fks", foreignKeysCount, "done"); } const idxs = await db.query(`SELECT m.tbl_name as tableName, il.name as indexName, ii.name as columnName, il.[unique] as isUnique, il.seq as seq FROM sqlite_master AS m, pragma_index_list(m.name) AS il, pragma_index_info(il.name) AS ii WHERE m.type = 'table' AND il.name NOT LIKE 'sqlite\\_autoindex\\_%' ESCAPE '\\' AND ${filterIgnoredTablesByField("m.tbl_name")};`); for (const idxRow of idxs) { const tableName = idxRow.tableName; const constraintName = idxRow.indexName; const columnName = idxRow.columnName; const isUnique = idxRow.isUnique === 1; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; indexesCount += 1; if (progressCallback) { progressCallback("indexes", indexesCount, "fetching"); } if (typeof tableInResult.indexes[constraintName] !== "undefined" && columnName) { tableInResult.indexes[constraintName].columns.push(columnName); } else { tableInResult.indexes[constraintName] = { name: constraintName, columns: columnName ? [columnName] : [], isUnique }; } } if (progressCallback) { progressCallback("indexes", indexesCount, "done"); progressCallback("enums", 0, "done"); } const views = await db.query( `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';` ); viewsCount = views.length; if (progressCallback) { progressCallback("views", viewsCount, "fetching"); } for (const view5 of views) { const viewName = view5["view_name"]; const sql = view5["sql"]; const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i"); const match2 = sql.match(regex); if (!match2) { console.log("Could not process view"); process.exit(1); } const viewDefinition = match2[1]; const columns2 = result[viewName].columns; delete result[viewName]; resultViews[viewName] = { columns: columns2, isExisting: false, name: viewName, definition: viewDefinition }; } if (progressCallback) { progressCallback("views", viewsCount, "done"); } const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi; const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi; let checkCounter = 0; const checkConstraints = {}; const checks = await db.query(`SELECT name as "tableName", sql as "sql" FROM sqlite_master WHERE type = 'table' AND ${filterIgnoredTablesByField("tbl_name")};`); for (const check2 of checks) { if (!tablesFilter(check2.tableName)) continue; const { tableName, sql } = check2; let namedChecks = [...sql.matchAll(namedCheckPattern)]; if (namedChecks.length > 0) { namedChecks.forEach(([_3, checkName, checkValue]) => { checkConstraints[checkName] = { name: checkName, value: checkValue.trim() }; }); } else { let unnamedChecks = [...sql.matchAll(unnamedCheckPattern)]; unnamedChecks.forEach(([_3, checkValue]) => { let checkName = `${tableName}_check_${++checkCounter}`; checkConstraints[checkName] = { name: checkName, value: checkValue.trim() }; }); } checksCount += Object.values(checkConstraints).length; if (progressCallback) { progressCallback("checks", checksCount, "fetching"); } const table6 = result[tableName]; if (!table6) { result[tableName] = { name: tableName, columns: {}, compositePrimaryKeys: {}, indexes: {}, foreignKeys: {}, uniqueConstraints: {}, checkConstraints }; } else { result[tableName].checkConstraints = checkConstraints; } } if (progressCallback) { progressCallback("checks", checksCount, "done"); } return { version: "6", dialect: "sqlite", tables: result, views: resultViews, enums: {}, _meta: { tables: {}, columns: {} } }; }; } }); // src/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((t4) => { if ((0, import_drizzle_orm7.is)(t4, import_singlestore_core.SingleStoreTable)) { tables.push(t4); } }); return { tables /* views */ }; }; prepareFromSingleStoreImports = async (imports) => { const tables = []; const { unregister } = await safeRegister(); for (let i4 = 0; i4 < imports.length; i4++) { const it = imports[i4]; 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 table6 of tables) { const { name: tableName, columns, indexes, schema: schema6, primaryKeys, uniqueConstraints } = (0, import_singlestore_core2.getTableConfig)(table6); const columnsObject = {}; const indexesObject = {}; const primaryKeysObject = {}; const uniqueConstraintObject = {}; columns.forEach((column11) => { const notNull = column11.notNull; const sqlTypeLowered = column11.getSQLType().toLowerCase(); const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement; const generated = column11.generated; const columnToSet = { name: column11.name, type: column11.getSQLType(), primaryKey: false, // If field is autoincrement it's notNull by default // notNull: autoIncrement ? true : notNull, notNull, autoincrement: autoIncrement, onUpdate: column11.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 (column11.primary) { primaryKeysObject[`${tableName}_${column11.name}`] = { name: `${tableName}_${column11.name}`, columns: [column11.name] }; } if (column11.isUnique) { const existingUnique = uniqueConstraintObject[column11.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( column11.uniqueName )} on the ${source_default.underline.blue( column11.name )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns `)}` ); process.exit(1); } uniqueConstraintObject[column11.uniqueName] = { name: column11.uniqueName, columns: [columnToSet.name] }; } if (column11.default !== void 0) { if ((0, import_drizzle_orm8.is)(column11.default, import_drizzle_orm8.SQL)) { columnToSet.default = sqlToStr(column11.default, casing2); } else { if (typeof column11.default === "string") { columnToSet.default = `'${column11.default}'`; } else { if (sqlTypeLowered === "json" || Array.isArray(column11.default)) { columnToSet.default = `'${JSON.stringify(column11.default)}'`; } else if (column11.default instanceof Date) { if (sqlTypeLowered === "date") { columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`; } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) { columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`; } } else { columnToSet.default = column11.default; } } } } columnsObject[column11.name] = columnToSet; }); primaryKeys.map((pk) => { const columnNames = pk.columns.map((c3) => c3.name); primaryKeysObject[pk.getName()] = { name: pk.getName(), columns: columnNames }; for (const column11 of pk.columns) { columnsObject[column11.name].notNull = true; } }); uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => { const columnNames = unq.columns.map((c3) => c3.name); const name = unq.name ?? (0, import_singlestore_core2.uniqueKeyName)(table6, columnNames); const existingUnique = uniqueConstraintObject[name]; if (typeof existingUnique !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique constraint ${source_default.underline.blue( name )} on the ${source_default.underline.blue( columnNames.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( existingUnique.columns.join(",") )} columns ` )}` ); process.exit(1); } uniqueConstraintObject[name] = { name: unq.name, columns: columnNames }; }); indexes.forEach((value) => { const columns2 = value.config.columns; const name = value.config.name; let indexColumns = columns2.map((it) => { var _a2; 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 ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") { internal.indexes[name].columns[sql] = { isExpression: true }; } else { internal.indexes[name].columns[sql].isExpression = true; } } return sql; } else { return `${it.name}`; } }); if (value.config.unique) { if (typeof uniqueConstraintObject[name] !== "undefined") { console.log( ` ${withStyle.errorWarning( `We've found duplicated unique constraint names in ${source_default.underline.blue( tableName )} table. The unique index ${source_default.underline.blue( name )} on the ${source_default.underline.blue( indexColumns.join(",") )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue( uniqueConstraintObject[name].columns.join(",") )} columns ` )}` ); process.exit(1); } } indexesObject[name] = { name, columns: indexColumns, isUnique: value.config.unique ?? false, using: value.config.using, algorithm: value.config.algorithm, lock: value.config.lock }; }); if (!schema6) { result[tableName] = { name: tableName, columns: columnsObject, indexes: indexesObject, compositePrimaryKeys: primaryKeysObject, uniqueConstraints: uniqueConstraintObject }; } } return { version: "1", dialect: "singlestore", tables: result, /* views: resultViews, */ _meta: { tables: {}, columns: {} }, internal }; }; fromDatabase4 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => { const result = {}; const internals = { tables: {}, indexes: {} }; const columns = await db.query(`select * from information_schema.columns where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations' order by table_name, ordinal_position;`); const response = columns; const schemas = []; let columnsCount = 0; let tablesCount = /* @__PURE__ */ new Set(); let indexesCount = 0; const idxs = await db.query( `select * from INFORMATION_SCHEMA.STATISTICS WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';` ); const idxRows = idxs; for (const column11 of response) { if (!tablesFilter(column11["TABLE_NAME"])) continue; columnsCount += 1; if (progressCallback) { progressCallback("columns", columnsCount, "fetching"); } const schema6 = column11["TABLE_SCHEMA"]; const tableName = column11["TABLE_NAME"]; tablesCount.add(`${schema6}.${tableName}`); if (progressCallback) { progressCallback("columns", tablesCount.size, "fetching"); } const columnName = column11["COLUMN_NAME"]; const isNullable = column11["IS_NULLABLE"] === "YES"; const dataType = column11["DATA_TYPE"]; const columnType = column11["COLUMN_TYPE"]; const isPrimary = column11["COLUMN_KEY"] === "PRI"; let columnDefault = column11["COLUMN_DEFAULT"]; const collation = column11["CHARACTER_SET_NAME"]; const geenratedExpression = column11["GENERATION_EXPRESSION"]; let columnExtra = column11["EXTRA"]; let isAutoincrement = false; let isDefaultAnExpression = false; if (typeof column11["EXTRA"] !== "undefined") { columnExtra = column11["EXTRA"]; isAutoincrement = column11["EXTRA"] === "auto_increment"; isDefaultAnExpression = column11["EXTRA"].includes("DEFAULT_GENERATED"); } if (schema6 !== inputSchema) { schemas.push(schema6); } const table6 = result[tableName]; let changedType = columnType; if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) { const uniqueIdx = idxRows.filter( (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0 ); if (uniqueIdx && uniqueIdx.length === 1) { changedType = columnType.replace("bigint unsigned", "serial"); } } if (columnType.startsWith("bigint(") || columnType.startsWith("tinyint(") || columnType.startsWith("date(") || columnType.startsWith("int(") || columnType.startsWith("mediumint(") || columnType.startsWith("smallint(") || columnType.startsWith("text(") || columnType.startsWith("time(") || columnType.startsWith("year(")) { changedType = columnType.replace(/\(\s*[^)]*\)$/, ""); } if (columnType.includes("decimal(10,0)")) { changedType = columnType.replace("decimal(10,0)", "decimal"); } if (columnDefault == 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 (!table6) { result[tableName] = { name: tableName, columns: { [columnName]: newColumn }, compositePrimaryKeys: {}, indexes: {}, uniqueConstraints: {} }; } else { result[tableName].columns[columnName] = newColumn; } } const tablePks = await db.query( `SELECT table_name, column_name, ordinal_position FROM information_schema.table_constraints t LEFT JOIN information_schema.key_column_usage k USING(constraint_name,table_schema,table_name) WHERE t.constraint_type='UNIQUE' and table_name != '__drizzle_migrations' AND t.table_schema = '${inputSchema}' ORDER BY ordinal_position` ); const tableToPk = {}; const tableToPkRows = tablePks; for (const tableToPkRow of tableToPkRows) { const tableName = tableToPkRow["table_name"]; const columnName = tableToPkRow["column_name"]; const position = tableToPkRow["ordinal_position"]; if (typeof result[tableName] === "undefined") { continue; } if (typeof tableToPk[tableName] === "undefined") { tableToPk[tableName] = [columnName]; } else { tableToPk[tableName].push(columnName); } } for (const [key, value] of Object.entries(tableToPk)) { result[key].compositePrimaryKeys = { [`${key}_${value.join("_")}`]: { name: `${key}_${value.join("_")}`, columns: value } }; } if (progressCallback) { progressCallback("columns", columnsCount, "done"); progressCallback("tables", tablesCount.size, "done"); } for (const idxRow of idxRows) { const tableSchema = idxRow["TABLE_SCHEMA"]; const tableName = idxRow["TABLE_NAME"]; const constraintName = idxRow["INDEX_NAME"]; const columnName = idxRow["COLUMN_NAME"]; const isUnique = idxRow["NON_UNIQUE"] === 0; const tableInResult = result[tableName]; if (typeof tableInResult === "undefined") continue; indexesCount += 1; if (progressCallback) { progressCallback("indexes", indexesCount, "fetching"); } if (isUnique) { if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") { tableInResult.uniqueConstraints[constraintName].columns.push( columnName ); } else { tableInResult.uniqueConstraints[constraintName] = { name: constraintName, columns: [columnName] }; } } } if (progressCallback) { progressCallback("indexes", indexesCount, "done"); progressCallback("enums", 0, "done"); } return { version: "1", dialect: "singlestore", tables: result, /* views: resultViews, */ _meta: { tables: {}, columns: {} }, internal: internals }; }; } }); // 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, 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 }; }; 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 = { id, prevId: idPrev, ...prevRest }; 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(x4, y2) { if (x4 < y2) { return -1; } if (x4 > y2) { return 1; } return 0; }; insort = function(a3, x4, 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 = a3.length; } while (lo < hi) { mid = floor((lo + hi) / 2); if (cmp(x4, a3[mid]) < 0) { hi = mid; } else { lo = mid + 1; } } return [].splice.apply(a3, [lo, lo - lo].concat(x4)), x4; }; 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 i4, _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++) { i4 = _ref1[_i]; _results.push(_siftup(array2, i4, 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, n3, cmp) { var elem, result, _i, _len, _ref; if (cmp == null) { cmp = defaultCmp; } result = array2.slice(0, n3); if (!result.length) { return result; } heapify(result, cmp); _ref = array2.slice(n3); for (_i = 0, _len = _ref.length; _i < _len; _i++) { elem = _ref[_i]; heappushpop(result, elem, cmp); } return result.sort(cmp).reverse(); }; nsmallest = function(array2, n3, cmp) { var elem, i4, los, result, _i, _j, _len, _ref, _ref1, _results; if (cmp == null) { cmp = defaultCmp; } if (n3 * 10 <= array2.length) { result = array2.slice(0, n3).sort(cmp); if (!result.length) { return result; } los = result[result.length - 1]; _ref = array2.slice(n3); 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 (i4 = _j = 0, _ref1 = min(n3, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i4 = 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(x4) { return heappush(this.nodes, x4, this.cmp); }; Heap2.prototype.pop = function() { return heappop(this.nodes, this.cmp); }; Heap2.prototype.peek = function() { return this.nodes[0]; }; Heap2.prototype.contains = function(x4) { return this.nodes.indexOf(x4) !== -1; }; Heap2.prototype.replace = function(x4) { return heapreplace(this.nodes, x4, this.cmp); }; Heap2.prototype.pushpop = function(x4) { return heappushpop(this.nodes, x4, this.cmp); }; Heap2.prototype.heapify = function() { return heapify(this.nodes, this.cmp); }; Heap2.prototype.updateItem = function(x4) { return updateItem(this.nodes, x4, 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(a3, b3) { var i4, l3, la, lb, ref; [la, lb] = [a3.length, b3.length]; for (i4 = l3 = 0, ref = min(la, lb); 0 <= ref ? l3 < ref : l3 > ref; i4 = 0 <= ref ? ++l3 : --l3) { if (a3[i4] < b3[i4]) { return -1; } if (a3[i4] > b3[i4]) { return 1; } } return la - lb; }; _has = function(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }; _any = function(items) { var item, l3, len; for (l3 = 0, len = items.length; l3 < len; l3++) { item = items[l3]; 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, a3 = "", b3 = "", autojunk = true) { this.isjunk = isjunk1; this.autojunk = autojunk; this.a = this.b = null; this.setSeqs(a3, b3); } setSeqs(a3, b3) { this.setSeq1(a3); return this.setSeq2(b3); } setSeq1(a3) { if (a3 === this.a) { return; } this.a = a3; return this.matchingBlocks = this.opcodes = null; } setSeq2(b3) { if (b3 === this.b) { return; } this.b = b3; 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 b3, b2j, elt, i4, indices, isjunk, junk, l3, len, n3, ntest, popular; b3 = this.b; this.b2j = b2j = /* @__PURE__ */ new Map(); for (i4 = l3 = 0, len = b3.length; l3 < len; i4 = ++l3) { elt = b3[i4]; if (!b2j.has(elt)) { b2j.set(elt, []); } indices = b2j.get(elt); indices.push(i4); } 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(); n3 = b3.length; if (this.autojunk && n3 >= 200) { ntest = floor(n3 / 100) + 1; b2j.forEach(function(idxs, elt2) { if (idxs.length > ntest) { popular.set(elt2, true); return b2j.delete(elt2); } }); } this.isbjunk = function(b4) { return junk.has(b4); }; return this.isbpopular = function(b4) { return popular.has(b4); }; } findLongestMatch(alo, ahi, blo, bhi) { var a3, b3, b2j, besti, bestj, bestsize, i4, isbjunk, j3, j2len, jlist, k3, l3, len, m4, newj2len, ref, ref1; [a3, b3, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk]; [besti, bestj, bestsize] = [alo, blo, 0]; j2len = {}; for (i4 = l3 = ref = alo, ref1 = ahi; ref <= ref1 ? l3 < ref1 : l3 > ref1; i4 = ref <= ref1 ? ++l3 : --l3) { newj2len = {}; jlist = []; if (b2j.has(a3[i4])) { jlist = b2j.get(a3[i4]); } for (m4 = 0, len = jlist.length; m4 < len; m4++) { j3 = jlist[m4]; if (j3 < blo) { continue; } if (j3 >= bhi) { break; } k3 = newj2len[j3] = (j2len[j3 - 1] || 0) + 1; if (k3 > bestsize) { [besti, bestj, bestsize] = [i4 - k3 + 1, j3 - k3 + 1, k3]; } } j2len = newj2len; } while (besti > alo && bestj > blo && !isbjunk(b3[bestj - 1]) && a3[besti - 1] === b3[bestj - 1]) { [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1]; } while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b3[bestj + bestsize]) && a3[besti + bestsize] === b3[bestj + bestsize]) { bestsize++; } while (besti > alo && bestj > blo && isbjunk(b3[bestj - 1]) && a3[besti - 1] === b3[bestj - 1]) { [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1]; } while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b3[bestj + bestsize]) && a3[besti + bestsize] === b3[bestj + bestsize]) { bestsize++; } return [besti, bestj, bestsize]; } getMatchingBlocks() { var ahi, alo, bhi, blo, i4, i1, i22, j3, j1, j22, k3, k1, k22, l3, la, lb, len, matchingBlocks, nonAdjacent, queue, x4; 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(); [i4, j3, k3] = x4 = this.findLongestMatch(alo, ahi, blo, bhi); if (k3) { matchingBlocks.push(x4); if (alo < i4 && blo < j3) { queue.push([alo, i4, blo, j3]); } if (i4 + k3 < ahi && j3 + k3 < bhi) { queue.push([i4 + k3, ahi, j3 + k3, bhi]); } } } matchingBlocks.sort(_arrayCmp); i1 = j1 = k1 = 0; nonAdjacent = []; for (l3 = 0, len = matchingBlocks.length; l3 < len; l3++) { [i22, j22, k22] = matchingBlocks[l3]; if (i1 + k1 === i22 && j1 + k1 === j22) { k1 += k22; } else { if (k1) { nonAdjacent.push([i1, j1, k1]); } [i1, j1, k1] = [i22, j22, k22]; } } if (k1) { nonAdjacent.push([i1, j1, k1]); } nonAdjacent.push([la, lb, 0]); return this.matchingBlocks = nonAdjacent; } getOpcodes() { var ai, answer, bj, i4, j3, l3, len, ref, size, tag; if (this.opcodes) { return this.opcodes; } i4 = j3 = 0; this.opcodes = answer = []; ref = this.getMatchingBlocks(); for (l3 = 0, len = ref.length; l3 < len; l3++) { [ai, bj, size] = ref[l3]; tag = ""; if (i4 < ai && j3 < bj) { tag = "replace"; } else if (i4 < ai) { tag = "delete"; } else if (j3 < bj) { tag = "insert"; } if (tag) { answer.push([tag, i4, ai, j3, bj]); } [i4, j3] = [ai + size, bj + size]; if (size) { answer.push(["equal", ai, i4, bj, j3]); } } return answer; } getGroupedOpcodes(n3 = 3) { var codes, group, groups, i1, i22, j1, j22, l3, len, nn, tag; codes = this.getOpcodes(); if (!codes.length) { codes = [["equal", 0, 1, 0, 1]]; } if (codes[0][0] === "equal") { [tag, i1, i22, j1, j22] = codes[0]; codes[0] = [tag, max(i1, i22 - n3), i22, max(j1, j22 - n3), j22]; } if (codes[codes.length - 1][0] === "equal") { [tag, i1, i22, j1, j22] = codes[codes.length - 1]; codes[codes.length - 1] = [tag, i1, min(i22, i1 + n3), j1, min(j22, j1 + n3)]; } nn = n3 + n3; groups = []; group = []; for (l3 = 0, len = codes.length; l3 < len; l3++) { [tag, i1, i22, j1, j22] = codes[l3]; if (tag === "equal" && i22 - i1 > nn) { group.push([tag, i1, min(i22, i1 + n3), j1, min(j22, j1 + n3)]); groups.push(group); group = []; [i1, j1] = [max(i1, i22 - n3), max(j1, j22 - n3)]; } group.push([tag, i1, i22, j1, j22]); } if (group.length && !(group.length === 1 && group[0][0] === "equal")) { groups.push(group); } return groups; } ratio() { var l3, len, match2, matches, ref; matches = 0; ref = this.getMatchingBlocks(); for (l3 = 0, len = ref.length; l3 < len; l3++) { match2 = ref[l3]; matches += match2[2]; } return _calculateRatio(matches, this.a.length + this.b.length); } quickRatio() { var avail, elt, fullbcount, l3, len, len1, m4, matches, numb, ref, ref1; if (!this.fullbcount) { this.fullbcount = fullbcount = {}; ref = this.b; for (l3 = 0, len = ref.length; l3 < len; l3++) { elt = ref[l3]; fullbcount[elt] = (fullbcount[elt] || 0) + 1; } } fullbcount = this.fullbcount; avail = {}; matches = 0; ref1 = this.a; for (m4 = 0, len1 = ref1.length; m4 < len1; m4++) { elt = ref1[m4]; 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, n3 = 3, cutoff = 0.6) { var l3, len, len1, m4, result, results, s4, score, x4; if (!(n3 > 0)) { throw new Error(`n must be > 0: (${n3})`); } if (!(0 <= cutoff && cutoff <= 1)) { throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`); } result = []; s4 = new SequenceMatcher(); s4.setSeq2(word); for (l3 = 0, len = possibilities.length; l3 < len; l3++) { x4 = possibilities[l3]; s4.setSeq1(x4); if (s4.realQuickRatio() >= cutoff && s4.quickRatio() >= cutoff && s4.ratio() >= cutoff) { result.push([s4.ratio(), x4]); } } result = Heap.nlargest(result, n3, _arrayCmp); results = []; for (m4 = 0, len1 = result.length; m4 < len1; m4++) { [score, x4] = result[m4]; results.push(x4); } return results; }; _countLeading = function(line, ch) { var i4, n3; [i4, n3] = [0, line.length]; while (i4 < n3 && line[i4] === ch) { i4++; } return i4; }; 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(a3, b3) { var ahi, alo, bhi, blo, cruncher, g3, l3, len, len1, line, lines, m4, ref, tag; cruncher = new SequenceMatcher(this.linejunk, a3, b3); lines = []; ref = cruncher.getOpcodes(); for (l3 = 0, len = ref.length; l3 < len; l3++) { [tag, alo, ahi, blo, bhi] = ref[l3]; switch (tag) { case "replace": g3 = this._fancyReplace(a3, alo, ahi, b3, blo, bhi); break; case "delete": g3 = this._dump("-", a3, alo, ahi); break; case "insert": g3 = this._dump("+", b3, blo, bhi); break; case "equal": g3 = this._dump(" ", a3, alo, ahi); break; default: throw new Error(`unknow tag (${tag})`); } for (m4 = 0, len1 = g3.length; m4 < len1; m4++) { line = g3[m4]; lines.push(line); } } return lines; } _dump(tag, x4, lo, hi) { var i4, l3, ref, ref1, results; results = []; for (i4 = l3 = ref = lo, ref1 = hi; ref <= ref1 ? l3 < ref1 : l3 > ref1; i4 = ref <= ref1 ? ++l3 : --l3) { results.push(`${tag} ${x4[i4]}`); } return results; } _plainReplace(a3, alo, ahi, b3, blo, bhi) { var first, g3, l3, len, len1, line, lines, m4, ref, second; assert(alo < ahi && blo < bhi); if (bhi - blo < ahi - alo) { first = this._dump("+", b3, blo, bhi); second = this._dump("-", a3, alo, ahi); } else { first = this._dump("-", a3, alo, ahi); second = this._dump("+", b3, blo, bhi); } lines = []; ref = [first, second]; for (l3 = 0, len = ref.length; l3 < len; l3++) { g3 = ref[l3]; for (m4 = 0, len1 = g3.length; m4 < len1; m4++) { line = g3[m4]; lines.push(line); } } return lines; } _fancyReplace(a3, alo, ahi, b3, blo, bhi) { var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i4, j3, l3, la, lb, len, len1, len2, len3, len4, line, lines, m4, o3, p3, q3, r4, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t4, 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 (j3 = l3 = ref = blo, ref1 = bhi; ref <= ref1 ? l3 < ref1 : l3 > ref1; j3 = ref <= ref1 ? ++l3 : --l3) { bj = b3[j3]; cruncher.setSeq2(bj); for (i4 = m4 = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m4 < ref3 : m4 > ref3; i4 = ref2 <= ref3 ? ++m4 : --m4) { ai = a3[i4]; if (ai === bj) { if (eqi === null) { [eqi, eqj] = [i4, j3]; } continue; } cruncher.setSeq1(ai); if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) { [bestRatio, besti, bestj] = [cruncher.ratio(), i4, j3]; } } } if (bestRatio < cutoff) { if (eqi === null) { ref4 = this._plainReplace(a3, alo, ahi, b3, blo, bhi); for (o3 = 0, len = ref4.length; o3 < len; o3++) { line = ref4[o3]; lines.push(line); } return lines; } [besti, bestj, bestRatio] = [eqi, eqj, 1]; } else { eqi = null; } ref5 = this._fancyHelper(a3, alo, besti, b3, blo, bestj); for (p3 = 0, len1 = ref5.length; p3 < len1; p3++) { line = ref5[p3]; lines.push(line); } [aelt, belt] = [a3[besti], b3[bestj]]; if (eqi === null) { atags = btags = ""; cruncher.setSeqs(aelt, belt); ref6 = cruncher.getOpcodes(); for (q3 = 0, len2 = ref6.length; q3 < len2; q3++) { [tag, ai1, ai2, bj1, bj2] = ref6[q3]; [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 (r4 = 0, len3 = ref7.length; r4 < len3; r4++) { line = ref7[r4]; lines.push(line); } } else { lines.push(" " + aelt); } ref8 = this._fancyHelper(a3, besti + 1, ahi, b3, bestj + 1, bhi); for (t4 = 0, len4 = ref8.length; t4 < len4; t4++) { line = ref8[t4]; lines.push(line); } return lines; } _fancyHelper(a3, alo, ahi, b3, blo, bhi) { var g3; g3 = []; if (alo < ahi) { if (blo < bhi) { g3 = this._fancyReplace(a3, alo, ahi, b3, blo, bhi); } else { g3 = this._dump("-", a3, alo, ahi); } } else if (blo < bhi) { g3 = this._dump("+", b3, blo, bhi); } return g3; } _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(a3, b3, { fromfile, tofile, fromfiledate, tofiledate, n: n3, lineterm } = {}) { var file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l3, last, len, len1, len2, len3, len4, line, lines, m4, o3, p3, q3, ref, ref1, ref2, ref3, started, tag, todate; if (fromfile == null) { fromfile = ""; } if (tofile == null) { tofile = ""; } if (fromfiledate == null) { fromfiledate = ""; } if (tofiledate == null) { tofiledate = ""; } if (n3 == null) { n3 = 3; } if (lineterm == null) { lineterm = "\n"; } lines = []; started = false; ref = new SequenceMatcher(null, a3, b3).getGroupedOpcodes(); for (l3 = 0, len = ref.length; l3 < len; l3++) { group = ref[l3]; 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 (m4 = 0, len1 = group.length; m4 < len1; m4++) { [tag, i1, i22, j1, j22] = group[m4]; if (tag === "equal") { ref1 = a3.slice(i1, i22); for (o3 = 0, len2 = ref1.length; o3 < len2; o3++) { line = ref1[o3]; lines.push(" " + line); } continue; } if (tag === "replace" || tag === "delete") { ref2 = a3.slice(i1, i22); for (p3 = 0, len3 = ref2.length; p3 < len3; p3++) { line = ref2[p3]; lines.push("-" + line); } } if (tag === "replace" || tag === "insert") { ref3 = b3.slice(j1, j22); for (q3 = 0, len4 = ref3.length; q3 < len4; q3++) { line = ref3[q3]; 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(a3, b3, { fromfile, tofile, fromfiledate, tofiledate, n: n3, lineterm } = {}) { var _3, file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l3, last, len, len1, len2, len3, len4, line, lines, m4, o3, p3, prefix2, q3, ref, ref1, ref2, started, tag, todate; if (fromfile == null) { fromfile = ""; } if (tofile == null) { tofile = ""; } if (fromfiledate == null) { fromfiledate = ""; } if (tofiledate == null) { tofiledate = ""; } if (n3 == null) { n3 = 3; } if (lineterm == null) { lineterm = "\n"; } prefix2 = { insert: "+ ", delete: "- ", replace: "! ", equal: " " }; started = false; lines = []; ref = new SequenceMatcher(null, a3, b3).getGroupedOpcodes(); for (l3 = 0, len = ref.length; l3 < len; l3++) { group = ref[l3]; 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, m5, results; results = []; for (m5 = 0, len12 = group.length; m5 < len12; m5++) { [tag, _3, _3, _3, _3] = group[m5]; results.push(tag === "replace" || tag === "delete"); } return results; }())) { for (m4 = 0, len1 = group.length; m4 < len1; m4++) { [tag, i1, i22, _3, _3] = group[m4]; if (tag !== "insert") { ref1 = a3.slice(i1, i22); for (o3 = 0, len2 = ref1.length; o3 < len2; o3++) { line = ref1[o3]; lines.push(prefix2[tag] + line); } } } } file2Range = _formatRangeContext(first[3], last[4]); lines.push(`--- ${file2Range} ----${lineterm}`); if (_any(function() { var len32, p4, results; results = []; for (p4 = 0, len32 = group.length; p4 < len32; p4++) { [tag, _3, _3, _3, _3] = group[p4]; results.push(tag === "replace" || tag === "insert"); } return results; }())) { for (p3 = 0, len3 = group.length; p3 < len3; p3++) { [tag, _3, _3, j1, j22] = group[p3]; if (tag !== "delete") { ref2 = b3.slice(j1, j22); for (q3 = 0, len4 = ref2.length; q3 < len4; q3++) { line = ref2[q3]; lines.push(prefix2[tag] + line); } } } } } } return lines; }; ndiff = function(a3, b3, linejunk, charjunk = IS_CHARACTER_JUNK) { return new Differ(linejunk, charjunk).compare(a3, b3); }; restore = function(delta, which) { var l3, 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 (l3 = 0, len = delta.length; l3 < len; l3++) { line = delta[l3]; 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((x4) => roundObj(x4, 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(c3) { c3 = c3.toLowerCase(); var chars = trap[c3] || [" "]; var rand = Math.floor(Math.random() * chars.length); if (typeof trap[c3] !== "undefined") { result += trap[c3][rand]; } else { result += c3; } }); 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 r4 = Math.floor(Math.random() * range); return r4; } function isChar(character) { var bool = false; all.filter(function(i4) { bool = i4 === character; }); return bool; } function heComes(text2, options2) { var result = ""; var counts; var l3; 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 (l3 in text2) { if (isChar(l3)) { continue; } result = result + text2[l3]; 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 d3 in arr) { var index6 = arr[d3]; for (var i4 = 0; i4 <= counts[index6]; i4++) { if (options2[index6]) { result = result + soul[index6][randomNumber(soul[index6].length)]; } } } } return result; } return heComes(text, options); }; } }); // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js var require_america = __commonJS({ "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports2, module2) { module2["exports"] = function(colors) { return function(letter, i4, exploded) { if (letter === " ") return letter; switch (i4 % 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, i4, exploded) { return i4 % 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, i4, exploded) { if (letter === " ") { return letter; } else { return colors[rainbowColors[i4++ % 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, i4, 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 i4 = nestedStyles.length; while (i4--) { var code = ansiStyles2[nestedStyles[i4]]; 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 i4 in theme[style2]) { out = colors[theme[style2][i4]](out); } return out; } return colors[theme[style2]](str); }; })(style); } }; function init2() { var ret = {}; Object.keys(styles3).forEach(function(name) { ret[name] = { get: function() { return build([name]); } }; }); return ret; } var sequencer = function sequencer2(map3, str) { var exploded = str.split(""); exploded = exploded.map(map3); return exploded.join(""); }; colors.trap = require_trap(); colors.zalgo = require_zalgo(); colors.maps = {}; colors.maps.america = require_america()(colors); colors.maps.zebra = require_zebra()(colors); colors.maps.rainbow = require_rainbow()(colors); colors.maps.random = require_random()(colors); for (map2 in colors.maps) { (function(map3) { colors[map3] = function(str) { return sequencer(colors.maps[map3], str); }; })(map2); } var map2; defineProps(colors, init2()); } }); // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js var require_safe = __commonJS({ "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js"(exports2, module2) { 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 = { " "(s4) { return s4; }, "+": color.green, "-": color.red }; var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) { let subvalue; const prefix2 = key ? `${key}: ` : ""; const subindent = indent + " "; const outputElisions = (n3) => { const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions; if (n3 < maxElisions) { for (let i4 = 0; i4 < n3; i4++) { output(" ", subindent + "..."); } } else { output(" ", subindent + `... (${n3} 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 m4; subvalue = diff2[subkey]; if (m4 = subkey.match(/^(.*)__deleted$/)) { subcolorizeToCallback(options, m4[1], subvalue, output, "-", subindent); } else if (m4 = subkey.match(/^(.*)__added$/)) { subcolorizeToCallback(options, m4[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, index6, fuzzyOriginals) { let bestMatch = null; for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) { if (key !== "__next") { const indexDistance = Math.abs(matchIndex - index6); if (extendedTypeOf(item) === extendedTypeOf(candidate)) { const { score } = this.diff(item, candidate); if (!bestMatch || score > bestMatch.score || score === bestMatch.score && indexDistance < bestMatch.indexDistance) { bestMatch = { score, key, indexDistance }; } } } } return bestMatch; } scalarize(array2, originals, fuzzyOriginals) { const fuzzyMatches = []; if (fuzzyOriginals) { const keyScores = {}; for (let index6 = 0; index6 < array2.length; index6++) { const item = array2[index6]; if (this.isScalar(item)) { continue; } const bestMatch = this.findMatchingObject(item, index6, fuzzyOriginals); if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) { keyScores[bestMatch.key] = { score: bestMatch.score, index: index6 }; } } for (const [key, match2] of Object.entries(keyScores)) { fuzzyMatches[match2.index] = key; } } const result = []; for (let index6 = 0; index6 < array2.length; index6++) { const item = array2[index6]; if (this.isScalar(item)) { result.push(item); } else { const key = fuzzyMatches[index6] || "__$!SCALAR" + originals.__next++; originals[key] = { item, index: index6 }; result.push(key); } } return result; } isScalarized(item, originals) { return typeof item === "string" && item in originals; } descalarize(item, originals) { if (this.isScalarized(item, originals)) { return originals[item].item; } else { return item; } } arrayDiff(obj1, obj2) { const originals1 = { __next: 1 }; const seq1 = this.scalarize(obj1, originals1); const originals2 = { __next: originals1.__next }; const seq2 = this.scalarize(obj2, originals2, originals1); if (this.options.sort) { seq1.sort(); seq2.sort(); } const opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes(); let result = []; let score = 0; let equal = true; for (const [op, i1, i22, j1, j22] of opcodes) { let i4, j3; let asc, end; let asc1, end1; let asc2, end2; if (!(op === "equal" || this.options.keysOnly && op === "replace")) { equal = false; } switch (op) { case "equal": for (i4 = i1, end = i22, asc = i1 <= end; asc ? i4 < end : i4 > end; asc ? i4++ : i4--) { const item = seq1[i4]; 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 (i4 = i1, end1 = i22, asc1 = i1 <= end1; asc1 ? i4 < end1 : i4 > end1; asc1 ? i4++ : i4--) { result.push(["-", this.descalarize(seq1[i4], originals1)]); score -= 5; } break; case "insert": for (j3 = j1, end2 = j22, asc2 = j1 <= end2; asc2 ? j3 < end2 : j3 > end2; asc2 ? j3++ : j3--) { result.push(["+", this.descalarize(seq2[j3], originals2)]); score -= 5; } break; case "replace": if (!this.options.keysOnly) { let asc3, end3; let asc4, end4; for (i4 = i1, end3 = i22, asc3 = i1 <= end3; asc3 ? i4 < end3 : i4 > end3; asc3 ? i4++ : i4--) { result.push(["-", this.descalarize(seq1[i4], originals1)]); score -= 5; } for (j3 = j1, end4 = j22, asc4 = j1 <= end4; asc4 ? j3 < end4 : j3 > end4; asc4 ? j3++ : j3--) { result.push(["+", this.descalarize(seq2[j3], originals2)]); score -= 5; } } else { let asc5, end5; for (i4 = i1, end5 = i22, asc5 = i1 <= end5; asc5 ? i4 < end5 : i4 > end5; asc5 ? i4++ : i4--) { const change = this.diff( this.descalarize(seq1[i4], originals1), this.descalarize(seq2[i4 - i1 + j1], originals2) ); if (!change.equal) { result.push(["~", change.result]); equal = false; } else { result.push([" "]); } } } break; } } if (equal || opcodes.length === 0) { if (!this.options.full) { result = void 0; } else { result = obj1; } score = 100; } else { score = Math.max(0, score); } return { score, result, equal }; } diff(obj1, obj2) { const type1 = extendedTypeOf(obj1); const type2 = extendedTypeOf(obj2); if (type1 === type2) { switch (type1) { case "object": return this.objectDiff(obj1, obj2); case "array": return this.arrayDiff(obj1, obj2); } } let score = 100; let result = obj1; let equal; if (!this.options.keysOnly) { if (type1 === "date" && type2 === "date") { equal = obj1.getTime() === obj2.getTime(); } else { equal = obj1 === obj2; } if (!equal) { score = 0; if (this.options.outputNewOnly) { result = obj2; } else { result = { __old: obj1, __new: obj2 }; } } else if (!this.options.full) { result = void 0; } } else { equal = true; result = void 0; } return { score, result, equal }; } }; function diff2(obj1, obj2, options = {}) { if (options.precision !== void 0) { obj1 = roundObj(obj1, options.precision); obj2 = roundObj(obj2, options.precision); } return new JsonDiff(options).diff(obj1, obj2).result; } function diffString(obj1, obj2, options = {}) { return colorize(diff2(obj1, obj2, options), options); } module2.exports = { diff: diff2, diffString, colorize, colorizeToCallback }; } }); // src/jsonDiffer.js function diffSchemasOrTables(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {}); const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]); const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]); return { added, deleted }; } function diffIndPolicies(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {}); const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]); const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]); return { added, deleted }; } function diffColumns(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = (0, import_json_diff.diff)(left, right) ?? {}; const alteredTables = Object.fromEntries( Object.entries(result).filter((it) => { return !(it[0].includes("__added") || it[0].includes("__deleted")); }).map((tableEntry) => { const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => { return it[0].endsWith("__deleted"); }).map((it) => { return it[1]; }); const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => { return it[0].endsWith("__added"); }).map((it) => { return it[1]; }); tableEntry[1].columns = { added: addedColumns, deleted: deletedColumns }; const table6 = left[tableEntry[0]]; return [ tableEntry[0], { name: table6.name, schema: table6.schema, ...tableEntry[1] } ]; }) ); return alteredTables; } function diffPolicies(left, right) { left = JSON.parse(JSON.stringify(left)); right = JSON.parse(JSON.stringify(right)); const result = (0, import_json_diff.diff)(left, right) ?? {}; const alteredTables = Object.fromEntries( Object.entries(result).filter((it) => { return !(it[0].includes("__added") || it[0].includes("__deleted")); }).map((tableEntry) => { const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => { return it[0].endsWith("__deleted"); }).map((it) => { return it[1]; }); const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => { return it[0].endsWith("__added"); }).map((it) => { return it[1]; }); tableEntry[1].policies = { added: addedPolicies, deleted: deletedPolicies }; const table6 = left[tableEntry[0]]; return [ tableEntry[0], { name: table6.name, schema: table6.schema, ...tableEntry[1] } ]; }) ); return alteredTables; } function applyJsonDiff(json1, json2) { json1 = JSON.parse(JSON.stringify(json1)); json2 = JSON.parse(JSON.stringify(json2)); const rawDiff = (0, import_json_diff.diff)(json1, json2); const difference = JSON.parse(JSON.stringify(rawDiff || {})); difference.schemas = difference.schemas || {}; difference.tables = difference.tables || {}; difference.enums = difference.enums || {}; difference.sequences = difference.sequences || {}; difference.roles = difference.roles || {}; difference.policies = difference.policies || {}; difference.views = difference.views || {}; const schemaKeys = Object.keys(difference.schemas); for (let key of schemaKeys) { if (key.endsWith("__added") || key.endsWith("__deleted")) { delete difference.schemas[key]; continue; } } const tableKeys = Object.keys(difference.tables); for (let key of tableKeys) { if (key.endsWith("__added") || key.endsWith("__deleted")) { delete difference.tables[key]; continue; } const table6 = json1.tables[key]; difference.tables[key] = { name: table6.name, schema: table6.schema, ...difference.tables[key] }; } for (let [tableKey2, tableValue] of Object.entries(difference.tables)) { const table6 = difference.tables[tableKey2]; const columns = tableValue.columns || {}; const columnKeys = Object.keys(columns); for (let key of columnKeys) { if (key.endsWith("__added") || key.endsWith("__deleted")) { delete table6.columns[key]; continue; } } if (Object.keys(columns).length === 0) { delete table6["columns"]; } if ("name" in table6 && "schema" in table6 && Object.keys(table6).length === 2) { delete difference.tables[tableKey2]; } } const enumsEntries = Object.entries(difference.enums); const alteredEnums = enumsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => { const enumEntry = json1.enums[it[0]]; const { name, schema: schema6, values } = enumEntry; const sequence = mapArraysDiff(values, it[1].values); const addedValues = sequence.filter((it2) => it2.type === "added").map((it2) => { return { before: it2.before, value: it2.value }; }); const deletedValues = sequence.filter((it2) => it2.type === "removed").map((it2) => it2.value); return { name, schema: schema6, addedValues, deletedValues }; }); const sequencesEntries = Object.entries(difference.sequences); const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => { return json2.sequences[it[0]]; }); const rolesEntries = Object.entries(difference.roles); const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => { return json2.roles[it[0]]; }); const policiesEntries = Object.entries(difference.policies); const alteredPolicies = policiesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => { return json2.policies[it[0]]; }); const viewsEntries = Object.entries(difference.views); const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map( ([nameWithSchema, view5]) => { const deletedWithOption = view5.with__deleted; const addedWithOption = view5.with__added; const deletedWith = Object.fromEntries( Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => { return [key.replace("__deleted", ""), value]; }) ); const addedWith = Object.fromEntries( Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => { return [key.replace("__added", ""), value]; }) ); const alterWith = Object.fromEntries( Object.entries(view5.with || {}).filter( (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined" ).map( (it) => { return [it[0], it[1].__new]; } ) ); const alteredSchema = view5.schema; const alteredDefinition = view5.definition; const alteredExisting = view5.isExisting; const addedTablespace = view5.tablespace__added; const droppedTablespace = view5.tablespace__deleted; const alterTablespaceTo = view5.tablespace; let alteredTablespace; if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" }; if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace }; if (alterTablespaceTo) alteredTablespace = alterTablespaceTo; const addedUsing = view5.using__added; const droppedUsing = view5.using__deleted; const alterUsingTo = view5.using; let alteredUsing; if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" }; if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing }; if (alterUsingTo) alteredUsing = alterUsingTo; const alteredMeta = view5.meta; return Object.fromEntries( Object.entries({ name: json2.views[nameWithSchema].name, schema: json2.views[nameWithSchema].schema, // pg deletedWithOption, addedWithOption, deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0, addedWith: Object.keys(addedWith).length ? addedWith : void 0, alteredWith: Object.keys(alterWith).length ? alterWith : void 0, alteredSchema, alteredTablespace, alteredUsing, // mysql alteredMeta, // common alteredDefinition, alteredExisting }).filter(([_3, value]) => value !== void 0) ); } ); const alteredTablesWithColumns = Object.values(difference.tables).map( (table6) => { return findAlternationsInTable(table6); } ); return { alteredTablesWithColumns, alteredEnums, alteredSequences, alteredRoles, alteredViews, alteredPolicies }; } var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn; var init_jsonDiffer = __esm({ "src/jsonDiffer.js"() { "use strict"; "use-strict"; import_json_diff = __toESM(require_lib()); mapArraysDiff = (source, diff2) => { const sequence = []; let sourceIndex = 0; for (let i4 = 0; i4 < diff2.length; i4++) { const it = diff2[i4]; if (it.length === 1) { sequence.push({ type: "same", value: source[sourceIndex] }); sourceIndex += 1; } else { if (it[0] === "-") { sequence.push({ type: "removed", value: it[1] }); } else { sequence.push({ type: "added", value: it[1], before: "" }); } } } const result = sequence.reverse().reduce( (acc, it) => { if (it.type === "same") { acc.prev = it.value; } if (it.type === "added" && acc.prev) { it.before = acc.prev; } acc.result.push(it); return acc; }, { result: [] } ); return result.result.reverse(); }; findAlternationsInTable = (table6) => { const columns = table6.columns ?? {}; const altered = Object.keys(columns).filter((it) => !(it.includes("__deleted") || it.includes("__added"))).map((it) => { return { name: it, ...columns[it] }; }); const deletedIndexes = Object.fromEntries( Object.entries(table6.indexes__deleted || {}).concat( Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__deleted")) ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]]) ); const addedIndexes = Object.fromEntries( Object.entries(table6.indexes__added || {}).concat( Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__added")) ).map((entry) => [entry[0].replace("__added", ""), entry[1]]) ); const alteredIndexes = Object.fromEntries( Object.entries(table6.indexes || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const deletedPolicies = Object.fromEntries( Object.entries(table6.policies__deleted || {}).concat( Object.entries(table6.policies || {}).filter((it) => it[0].includes("__deleted")) ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]]) ); const addedPolicies = Object.fromEntries( Object.entries(table6.policies__added || {}).concat( Object.entries(table6.policies || {}).filter((it) => it[0].includes("__added")) ).map((entry) => [entry[0].replace("__added", ""), entry[1]]) ); const alteredPolicies = Object.fromEntries( Object.entries(table6.policies || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const deletedForeignKeys = Object.fromEntries( Object.entries(table6.foreignKeys__deleted || {}).concat( Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__deleted")) ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]]) ); const addedForeignKeys = Object.fromEntries( Object.entries(table6.foreignKeys__added || {}).concat( Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__added")) ).map((entry) => [entry[0].replace("__added", ""), entry[1]]) ); const alteredForeignKeys = Object.fromEntries( Object.entries(table6.foreignKeys || {}).filter( (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted") ).map((entry) => [entry[0], entry[1]]) ); const addedCompositePKs = Object.fromEntries( Object.entries(table6.compositePrimaryKeys || {}).filter((it) => { return it[0].endsWith("__added"); }) ); const deletedCompositePKs = Object.fromEntries( Object.entries(table6.compositePrimaryKeys || {}).filter((it) => { return it[0].endsWith("__deleted"); }) ); const alteredCompositePKs = Object.fromEntries( Object.entries(table6.compositePrimaryKeys || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const addedUniqueConstraints = Object.fromEntries( Object.entries(table6.uniqueConstraints || {}).filter((it) => { return it[0].endsWith("__added"); }) ); const deletedUniqueConstraints = Object.fromEntries( Object.entries(table6.uniqueConstraints || {}).filter((it) => { return it[0].endsWith("__deleted"); }) ); const alteredUniqueConstraints = Object.fromEntries( Object.entries(table6.uniqueConstraints || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const addedCheckConstraints = Object.fromEntries( Object.entries(table6.checkConstraints || {}).filter((it) => { return it[0].endsWith("__added"); }) ); const deletedCheckConstraints = Object.fromEntries( Object.entries(table6.checkConstraints || {}).filter((it) => { return it[0].endsWith("__deleted"); }) ); const alteredCheckConstraints = Object.fromEntries( Object.entries(table6.checkConstraints || {}).filter((it) => { return !it[0].endsWith("__deleted") && !it[0].endsWith("__added"); }) ); const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean); return { name: table6.name, schema: table6.schema || "", altered: mappedAltered, addedIndexes, deletedIndexes, alteredIndexes, addedForeignKeys, deletedForeignKeys, alteredForeignKeys, addedCompositePKs, deletedCompositePKs, alteredCompositePKs, addedUniqueConstraints, deletedUniqueConstraints, alteredUniqueConstraints, deletedPolicies, addedPolicies, alteredPolicies, addedCheckConstraints, deletedCheckConstraints, alteredCheckConstraints }; }; alternationsInColumn = (column11) => { const altered = [column11]; 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", "halfvec", "sparsevec", "bit" ]; const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g; const arrayDefinition = (type.match(arrayDefinitionRegex) ?? []).join(""); const withoutArrayDefinition = type.replace(arrayDefinitionRegex, ""); return pgNativeTypes.some((it) => type.startsWith(it)) ? `${withoutArrayDefinition}${arrayDefinition}` : `${schemaPrefix}"${withoutArrayDefinition}"${arrayDefinition}`; }; Convertor = class { }; PgCreateRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_role" && dialect6 === "postgresql"; } convert(statement) { return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`; } }; PgDropRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_role" && dialect6 === "postgresql"; } convert(statement) { return `DROP ROLE "${statement.name}";`; } }; PgRenameRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_role" && dialect6 === "postgresql"; } convert(statement) { return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`; } }; PgAlterRoleConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_role" && dialect6 === "postgresql"; } convert(statement) { return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`; } }; PgCreatePolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_policy" && dialect6 === "postgresql"; } convert(statement) { var _a2, _b, _c; const policy5 = statement.data; const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; const usingPart = policy5.using ? ` USING (${policy5.using})` : ""; const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : ""; const policyToPart = (_a2 = policy5.to) == null ? void 0 : _a2.map( (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"` ).join(", "); return `CREATE POLICY "${policy5.name}" ON ${tableNameWithSchema} AS ${(_b = policy5.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy5.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 policy5 = statement.data; const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `DROP POLICY "${policy5.name}" ON ${tableNameWithSchema} CASCADE;`; } }; PgRenamePolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_policy" && dialect6 === "postgresql"; } convert(statement) { const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`; } }; PgAlterPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_policy" && dialect6 === "postgresql"; } convert(statement, _dialect, action) { const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.newData) : PgSquasher.unsquashPolicy(statement.newData); const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.oldData) : PgSquasher.unsquashPolicy(statement.oldData); const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : ""; const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : ""; return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`; } }; PgCreateIndPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_ind_policy" && dialect6 === "postgresql"; } convert(statement) { var _a2, _b, _c; const policy5 = statement.data; const usingPart = policy5.using ? ` USING (${policy5.using})` : ""; const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : ""; const policyToPart = (_a2 = policy5.to) == null ? void 0 : _a2.map( (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"` ).join(", "); return `CREATE POLICY "${policy5.name}" ON ${policy5.on} AS ${(_b = policy5.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy5.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 policy5 = statement.data; return `DROP POLICY "${policy5.name}" ON ${policy5.on} CASCADE;`; } }; PgRenameIndPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "rename_ind_policy" && dialect6 === "postgresql"; } convert(statement) { return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`; } }; PgAlterIndPolicyConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_ind_policy" && dialect6 === "postgresql"; } convert(statement) { const newPolicy = statement.newData; const oldPolicy = statement.oldData; const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : ""; const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : ""; return `ALTER POLICY "${oldPolicy.name}" ON ${oldPolicy.on} TO ${newPolicy.to}${usingPart}${withCheckPart};`; } }; PgEnableRlsConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "enable_rls" && dialect6 === "postgresql"; } convert(statement) { const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`; } }; PgDisableRlsConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "disable_rls" && dialect6 === "postgresql"; } convert(statement) { const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`; return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`; } }; PgCreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_table" && dialect6 === "postgresql"; } convert(st) { const { tableName, schema: schema6, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st; let statement = ""; const name = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; statement += `CREATE TABLE ${name} ( `; for (let i4 = 0; i4 < columns.length; i4++) { const column11 = columns[i4]; const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column11.notNull && !column11.identity ? " NOT NULL" : ""; const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""; const uniqueConstraint6 = column11.isUnique ? ` CONSTRAINT "${column11.uniqueName}" UNIQUE${column11.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : ""; const schemaPrefix = column11.typeSchema && column11.typeSchema !== "public" ? `"${column11.typeSchema}".` : ""; const type = parseType(schemaPrefix, column11.type); const generated = column11.generated; const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) STORED` : ""; const unsquashedIdentity = column11.identity ? PgSquasher.unsquashIdentity(column11.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 += ` "${column11.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint6}${identity}`; statement += i4 === columns.length - 1 ? "" : ",\n"; } if (typeof compositePKs !== "undefined" && compositePKs.length > 0) { statement += ",\n"; const compositePK6 = PgSquasher.unsquashPK(compositePKs[0]); statement += ` CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK6.columns.join(`","`)}")`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint6); statement += ` CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`; } } if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) { for (const checkConstraint5 of checkConstraints) { statement += ",\n"; const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint5); statement += ` CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`; } } statement += ` );`; statement += ` `; const enableRls = new PgEnableRlsConvertor().convert({ type: "enable_rls", tableName, schema: schema6 }); return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []]; } }; MySqlCreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_table" && dialect6 === "mysql"; } convert(st) { var _a2, _b; const { tableName, columns, schema: schema6, checkConstraints, compositePKs, uniqueConstraints, internals } = st; let statement = ""; statement += `CREATE TABLE \`${tableName}\` ( `; for (let i4 = 0; i4 < columns.length; i4++) { const column11 = columns[i4]; const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column11.notNull ? " NOT NULL" : ""; const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""; const onUpdateStatement = column11.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; const autoincrementStatement = column11.autoincrement ? " AUTO_INCREMENT" : ""; const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS (${(_a2 = column11.generated) == null ? void 0 : _a2.as}) ${(_b = column11.generated) == null ? void 0 : _b.type.toUpperCase()}` : ""; statement += ` \`${column11.name}\` ${column11.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`; statement += i4 === columns.length - 1 ? "" : ",\n"; } if (typeof compositePKs !== "undefined" && compositePKs.length > 0) { statement += ",\n"; const compositePK6 = MySqlSquasher.unsquashPK(compositePKs[0]); statement += ` CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint6); const uniqueString = unsquashedUnique.columns.map((it) => { var _a3, _b2; return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a3 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a3.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 checkConstraint5 of checkConstraints) { statement += ",\n"; const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint5); statement += ` CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`; } } statement += ` );`; statement += ` `; return statement; } }; SingleStoreCreateTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "create_table" && dialect6 === "singlestore"; } convert(st) { var _a2, _b; const { tableName, columns, schema: schema6, compositePKs, uniqueConstraints, internals } = st; let statement = ""; statement += `CREATE TABLE \`${tableName}\` ( `; for (let i4 = 0; i4 < columns.length; i4++) { const column11 = columns[i4]; const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column11.notNull ? " NOT NULL" : ""; const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""; const onUpdateStatement = column11.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : ""; const autoincrementStatement = column11.autoincrement ? " AUTO_INCREMENT" : ""; const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS (${(_a2 = column11.generated) == null ? void 0 : _a2.as}) ${(_b = column11.generated) == null ? void 0 : _b.type.toUpperCase()}` : ""; statement += ` \`${column11.name}\` ${column11.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`; statement += i4 === columns.length - 1 ? "" : ",\n"; } if (typeof compositePKs !== "undefined" && compositePKs.length > 0) { statement += ",\n"; const compositePK6 = SingleStoreSquasher.unsquashPK(compositePKs[0]); statement += ` CONSTRAINT \`${compositePK6.name}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint6); const uniqueString = unsquashedUnique.columns.map((it) => { var _a3, _b2; return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a3 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a3.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 i4 = 0; i4 < columns.length; i4++) { const column11 = columns[i4]; const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : ""; const notNullStatement = column11.notNull ? " NOT NULL" : ""; const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""; const autoincrementStatement = column11.autoincrement ? " AUTOINCREMENT" : ""; const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS ${column11.generated.as} ${column11.generated.type.toUpperCase()}` : ""; statement += " "; statement += `\`${column11.name}\` ${column11.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`; statement += i4 === columns.length - 1 ? "" : ",\n"; } compositePKs.forEach((it) => { statement += ",\n "; statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`; }); for (let i4 = 0; i4 < referenceData.length; i4++) { const { name, tableFrom, tableTo, columnsFrom, columnsTo, onDelete, onUpdate } = referenceData[i4]; const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : ""; const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : ""; const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(","); const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(","); statement += ","; statement += "\n "; statement += `FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onUpdateStatement}${onDeleteStatement}`; } if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) { for (const uniqueConstraint6 of uniqueConstraints) { statement += ",\n"; const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint6); statement += ` CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`; } } if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) { for (const 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: cache3, 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}` : ""}${cache3 ? ` CACHE ${cache3}` : ""}${cycle ? ` CYCLE` : ""};`; } }; CreateTypeEnumConvertor = class extends Convertor { can(statement) { return statement.type === "create_type_enum"; } convert(st) { const { name, values, schema: schema6 } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; let valuesStatement = "("; valuesStatement += values.map((it) => `'${escapeSingleQuotes(it)}'`).join(", "); valuesStatement += ")"; let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`; return statement; } }; DropTypeEnumConvertor = class extends Convertor { can(statement) { return statement.type === "drop_type_enum"; } convert(st) { const { name, schema: schema6 } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; let statement = `DROP TYPE ${enumNameWithSchema};`; return statement; } }; AlterTypeAddValueConvertor = class extends Convertor { can(statement) { return statement.type === "alter_type_add_value"; } convert(st) { const { name, schema: schema6, value, before } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`; return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`; } }; AlterTypeSetSchemaConvertor = class extends Convertor { can(statement) { return statement.type === "move_type_enum"; } convert(st) { const { name, schemaFrom, schemaTo } = st; const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`; return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`; } }; AlterRenameTypeConvertor = class extends Convertor { can(statement) { return statement.type === "rename_type_enum"; } convert(st) { const { nameTo, nameFrom, schema: schema6 } = st; const enumNameWithSchema = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`; return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`; } }; AlterTypeDropValueConvertor = class extends Convertor { can(statement) { return statement.type === "alter_type_drop_value"; } convert(st) { const { columnsWithEnum, name, newValues, enumSchema: enumSchema4 } = st; const statements = []; for (const withEnum of columnsWithEnum) { const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`; statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;` ); if (withEnum.default) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::text;` ); } } statements.push(new DropTypeEnumConvertor().convert({ name, schema: enumSchema4, type: "drop_type_enum" })); statements.push(new CreateTypeEnumConvertor().convert({ name, schema: enumSchema4, values: newValues, type: "create_type_enum" })); for (const withEnum of columnsWithEnum) { const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`; const parsedType = parseType(`"${enumSchema4}".`, withEnum.columnType); if (withEnum.default) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::${parsedType};` ); } statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE ${parsedType} USING "${withEnum.column}"::${parsedType};` ); } return statements; } }; PgDropTableConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "drop_table" && dialect6 === "postgresql"; } convert(statement, _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((p3) => { return dropPolicyConvertor.convert({ type: "drop_policy", tableName, data: action === "push" ? PgSquasher.unsquashPolicyPush(p3) : PgSquasher.unsquashPolicy(p3), 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: column11, schema: schema6 } = statement; const { name, type, notNull, generated, primaryKey, identity } = column11; const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : ""; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`; const schemaPrefix = column11.typeSchema && column11.typeSchema !== "public" ? `"${column11.typeSchema}".` : ""; const fixedType = parseType(schemaPrefix, column11.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: column11 } = statement; const { name, type, notNull, primaryKey, autoincrement, onUpdate, generated } = column11; const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.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: column11 } = statement; const { name, type, notNull, primaryKey, autoincrement, onUpdate, generated } = column11; const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.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: column11, referenceData } = statement; const { name, type, notNull, primaryKey, generated } = column11; const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`; const notNullStatement = `${notNull ? " NOT NULL" : ""}`; const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`; const referenceAsObject = referenceData ? SQLiteSquasher.unsquashFK(referenceData) : void 0; const referenceStatement = `${referenceAsObject ? ` REFERENCES ${referenceAsObject.tableTo}(${referenceAsObject.columnsTo})` : ""}`; const generatedStatement = generated ? ` GENERATED ALWAYS AS ${generated.as} ${generated.type.toUpperCase()}` : ""; return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`; } }; PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "pg_alter_table_alter_column_set_type" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, newDataType, schema: schema6, oldDataType, columnDefault, typeSchema } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const statements = []; const type = parseType(`"${typeSchema}".`, newDataType.name); if (!oldDataType.isEnum && !newDataType.isEnum) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};` ); if (columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};` ); } } if (oldDataType.isEnum && !newDataType.isEnum) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};` ); if (columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};` ); } } if (!oldDataType.isEnum && newDataType.isEnum) { if (columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault}::${type};` ); } statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::${type};` ); } if (oldDataType.isEnum && newDataType.isEnum) { const alterType = `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::text::${type};`; if (newDataType.name !== oldDataType.name && columnDefault) { statements.push( `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`, alterType, `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};` ); } else { statements.push(alterType); } } return statements; } }; PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`; } }; PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_default" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`; } }; PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_generated" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6 } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`; } }; PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_generated" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({ schema: schema6, tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "alter_table_add_column" }); return [ `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`, addColumnStatement ]; } }; PgAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "postgresql"; } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`; const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({ schema: schema6, tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "alter_table_add_column" }); return [ `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`, addColumnStatement ]; } }; SqliteAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_generated" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, columnName, schema: schema6, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated, columnNotNull } = statement; const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert( { tableName, column: { name: columnName, type: statement.newDataType, notNull: columnNotNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "sqlite_alter_table_add_column" } ); const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({ tableName, columnName, schema: schema6, type: "alter_table_drop_column" }); return [dropColumnStatement, addColumnStatement]; } }; SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_generated" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert( { tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "sqlite_alter_table_add_column" } ); const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({ tableName, columnName, schema: schema6, type: "alter_table_drop_column" }); return [dropColumnStatement, addColumnStatement]; } }; SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_alter_generated" && (dialect6 === "sqlite" || dialect6 === "turso"); } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert( { tableName, column: { name: columnName, type: statement.newDataType, notNull: columnNotNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "sqlite_alter_table_add_column" } ); const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({ tableName, columnName, schema: schema6, type: "alter_table_drop_column" }); return [dropColumnStatement, addColumnStatement]; } }; MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "mysql"; } convert(statement) { const { tableName, columnName, schema: schema6, columnNotNull: notNull, columnDefault, columnOnUpdate, columnAutoIncrement, columnPk, columnGenerated } = statement; const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``; const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({ schema: schema6, tableName, column: { name: columnName, type: statement.newDataType, notNull, default: columnDefault, onUpdate: columnOnUpdate, autoincrement: columnAutoIncrement, primaryKey: columnPk, generated: columnGenerated }, type: "alter_table_add_column" }); return [ `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`, addColumnStatement ]; } }; MySqlAlterTableAddPk = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "mysql"; } convert(statement) { return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`; } }; MySqlAlterTableDropPk = class extends Convertor { can(statement, dialect6) { return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "mysql"; } convert(statement) { return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`; } }; LibSQLModifyColumn = class extends Convertor { can(statement, dialect6) { return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect6 === "turso"; } convert(statement, json2) { const { tableName, columnName } = statement; let columnType = ``; let columnDefault = ""; let columnNotNull = ""; const sqlStatements = []; const indexes = []; for (const table6 of Object.values(json2.tables)) { for (const index6 of Object.values(table6.indexes)) { const unsquashed = SQLiteSquasher.unsquashIdx(index6); sqlStatements.push(`DROP INDEX "${unsquashed.name}";`); indexes.push({ ...unsquashed, tableName: table6.name }); } } switch (statement.type) { case "alter_table_alter_column_set_type": columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; break; case "alter_table_alter_column_drop_notnull": columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = ""; break; case "alter_table_alter_column_set_notnull": columnType = ` ${statement.newDataType}`; columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : ""; columnNotNull = ` NOT NULL`; break; case "alter_table_alter_column_set_default": columnType = ` ${statement.newDataType}`; columnDefault = ` DEFAULT ${statement.newDefaultValue}`; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; break; case "alter_table_alter_column_drop_default": columnType = ` ${statement.newDataType}`; columnDefault = ""; columnNotNull = statement.columnNotNull ? ` NOT NULL` : ""; break; } columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault; sqlStatements.push( `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};` ); for (const index6 of indexes) { const indexPart = index6.isUnique ? "UNIQUE INDEX" : "INDEX"; const whereStatement = index6.where ? ` WHERE ${index6.where}` : ""; const uniqueString = index6.columns.map((it) => `\`${it}\``).join(","); const tableName2 = index6.tableName; sqlStatements.push( `CREATE ${indexPart} \`${index6.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};` ); } return sqlStatements; } }; MySqlModifyColumn = class extends Convertor { can(statement, dialect6) { return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "mysql"; } convert(statement) { var _a2, _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 (((_a2 = statement.columnGenerated) == null ? void 0 : _a2.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 _a2, _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 (((_a2 = statement.columnGenerated) == null ? void 0 : _a2.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 _a2, _b, _c, _d; return ((_a2 = statement.internal) == null ? void 0 : _a2.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 _a2, _b, _c, _d; return ((_a2 = statement.internal) == null ? void 0 : _a2.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 _a2, _b, _c, _d; return ((_a2 = statement.internal) == null ? void 0 : _a2.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( (c3) => `"${c3}"` ); statements.push( `INSERT INTO \`${newTableName}\`(${columns.join( ", " )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;` ); } statements.push( new SQLiteDropTableConvertor().convert({ type: "drop_table", tableName, schema: "" }) ); statements.push( new SqliteRenameTableConvertor().convert({ fromSchema: "", tableNameFrom: newTableName, tableNameTo: tableName, toSchema: "", type: "rename_table" }) ); for (const idx of Object.values(json.tables[tableName].indexes)) { statements.push( new CreateSqliteIndexConvertor().convert({ type: "create_index", tableName, schema: "", data: idx }) ); } return statements; }; getOldTableName = (tableName, meta) => { for (const key of Object.keys(meta.tables)) { const value = meta.tables[key]; if (`"${tableName}"` === value) { return key.substring(1, key.length - 1); } } return tableName; }; getNewTableName = (tableName, meta) => { if (typeof meta.tables[`"${tableName}"`] !== "undefined") { return meta.tables[`"${tableName}"`].substring( 1, meta.tables[`"${tableName}"`].length - 1 ); } return tableName; }; logSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => { let shouldAskForApprove = false; const statementsToExecute = []; const infoToPrint = []; const tablesToRemove = []; const columnsToRemove = []; const schemasToRemove = []; const tablesToTruncate = []; for (const statement of statements) { if (statement.type === "drop_table") { const res = await connection.query( `select count(*) as count from \`${statement.tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to delete ${source_default.underline( statement.tableName )} table with ${count} items` ); tablesToRemove.push(statement.tableName); shouldAskForApprove = true; } const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } else if (statement.type === "alter_table_drop_column") { const tableName = statement.tableName; const columnName = statement.columnName; const res = await connection.query( `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to delete ${source_default.underline( columnName )} column in ${tableName} table with ${count} items` ); columnsToRemove.push(`${tableName}_${statement.columnName}`); shouldAskForApprove = true; } const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) { const tableName = statement.tableName; const columnName = statement.column.name; const res = await connection.query( `select count(*) as count from \`${tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to add not-null ${source_default.underline( columnName )} column without default value, which contains ${count} items` ); tablesToTruncate.push(tableName); statementsToExecute.push(`delete from ${tableName};`); shouldAskForApprove = true; } const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } else if (statement.type === "recreate_table") { const tableName = statement.tableName; const oldTableName = getOldTableName(tableName, meta); let dataLoss = false; const prevColumnNames = Object.keys(json1.tables[oldTableName].columns); const currentColumnNames = Object.keys(json2.tables[tableName].columns); const { removedColumns, addedColumns } = findAddedAndRemoved( prevColumnNames, currentColumnNames ); if (removedColumns.length) { for (const removedColumn of removedColumns) { const res = await connection.query( `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\`` ); const count = Number(res[0].count); if (count > 0) { infoToPrint.push( `\xB7 You're about to delete ${source_default.underline( removedColumn )} column in ${tableName} table with ${count} items` ); columnsToRemove.push(removedColumn); shouldAskForApprove = true; } } } if (addedColumns.length) { for (const addedColumn of addedColumns) { const [res] = await connection.query( `select count(*) as count from \`${tableName}\`` ); const columnConf = json2.tables[tableName].columns[addedColumn]; const count = Number(res.count); if (count > 0 && columnConf.notNull && !columnConf.default) { dataLoss = true; infoToPrint.push( `\xB7 You're about to add not-null ${source_default.underline( addedColumn )} column without default value to table, which contains ${count} items` ); shouldAskForApprove = true; tablesToTruncate.push(tableName); statementsToExecute.push(`DELETE FROM \`${tableName}\`;`); } } } const tablesReferencingCurrent = []; for (const table6 of Object.values(json2.tables)) { const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t4) => SQLiteSquasher.unsquashPushFK(t4).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom); tablesReferencingCurrent.push(...tablesRefs); } if (!tablesReferencingCurrent.length) { statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss)); continue; } const [{ foreign_keys: pragmaState }] = await connection.query(`PRAGMA foreign_keys;`); if (pragmaState) { statementsToExecute.push(`PRAGMA foreign_keys=OFF;`); } statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss)); if (pragmaState) { statementsToExecute.push(`PRAGMA foreign_keys=ON;`); } } else { const fromJsonStatement = fromJson([statement], "sqlite", "push"); statementsToExecute.push( ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement] ); } } return { statementsToExecute, shouldAskForApprove, infoToPrint, columnsToRemove: [...new Set(columnsToRemove)], schemasToRemove: [...new Set(schemasToRemove)], tablesToTruncate: [...new Set(tablesToTruncate)], tablesToRemove: [...new Set(tablesToRemove)] }; }; } }); // src/jsonStatements.ts var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSingleStoreCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareRenameIndPolicyJsons, prepareCreatePolicyJsons, prepareCreateIndPolicyJsons, prepareDropPolicyJsons, prepareDropIndPolicyJsons, prepareAlterPolicyJson, prepareAlterIndPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView; var init_jsonStatements = __esm({ "src/jsonStatements.ts"() { "use strict"; init_source(); init_sqlitePushUtils(); init_views(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); preparePgCreateTableJson = (table6, json2) => { const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table6; const tableKey2 = `${schema6 || "public"}.${name}`; const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : ""; return { type: "create_table", tableName: name, schema: schema6, columns: Object.values(columns), compositePKs: Object.values(compositePrimaryKeys), compositePkName, uniqueConstraints: Object.values(uniqueConstraints), policies: Object.values(policies), checkConstraints: Object.values(checkConstraints), isRLSEnabled: isRLSEnabled ?? false }; }; prepareMySqlCreateTableJson = (table6, json2, internals) => { const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table6; return { type: "create_table", tableName: name, schema: schema6, columns: Object.values(columns), compositePKs: Object.values(compositePrimaryKeys), compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "", uniqueConstraints: Object.values(uniqueConstraints), internals, checkConstraints: Object.values(checkConstraints) }; }; prepareSingleStoreCreateTableJson = (table6, json2, internals) => { const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints } = table6; return { type: "create_table", tableName: name, schema: schema6, columns: Object.values(columns), compositePKs: Object.values(compositePrimaryKeys), compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[SingleStoreSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "", uniqueConstraints: Object.values(uniqueConstraints), internals }; }; prepareSQLiteCreateTable = (table6, action) => { const { name, columns, uniqueConstraints, checkConstraints } = table6; const references2 = Object.values(table6.foreignKeys); const composites = Object.values(table6.compositePrimaryKeys).map( (it) => SQLiteSquasher.unsquashPK(it) ); const fks = references2.map( (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it) ); return { type: "sqlite_create_table", tableName: name, columns: Object.values(columns), referenceData: fks, compositePKs: composites, uniqueConstraints: Object.values(uniqueConstraints), checkConstraints: Object.values(checkConstraints) }; }; prepareDropTableJson = (table6) => { return { type: "drop_table", tableName: table6.name, schema: table6.schema, policies: table6.policies ? Object.values(table6.policies) : [] }; }; prepareRenameTableJson = (tableFrom, tableTo) => { return { type: "rename_table", fromSchema: tableTo.schema, toSchema: tableTo.schema, tableNameFrom: tableFrom.name, tableNameTo: tableTo.name }; }; prepareCreateEnumJson = (name, schema6, values) => { return { type: "create_type_enum", name, schema: schema6, values }; }; prepareAddValuesToEnumJson = (name, schema6, values) => { return values.map((it) => { return { type: "alter_type_add_value", name, schema: schema6, value: it.value, before: it.before }; }); }; prepareDropEnumValues = (name, schema6, removedValues, json2) => { if (!removedValues.length) return []; const affectedColumns = []; for (const tableKey2 in json2.tables) { const table6 = json2.tables[tableKey2]; for (const columnKey in table6.columns) { const column11 = table6.columns[columnKey]; const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g; const parsedColumnType = column11.type.replace(arrayDefinitionRegex, ""); if (parsedColumnType === name && column11.typeSchema === schema6) { affectedColumns.push({ tableSchema: table6.schema, table: table6.name, column: column11.name, columnType: column11.type, default: column11.default }); } } } return [{ type: "alter_type_drop_value", name, enumSchema: schema6, deletedValues: removedValues, newValues: json2.enums[`${schema6}.${name}`].values, columnsWithEnum: affectedColumns }]; }; prepareDropEnumJson = (name, schema6) => { return { type: "drop_type_enum", name, schema: schema6 }; }; prepareMoveEnumJson = (name, schemaFrom, schemaTo) => { return { type: "move_type_enum", name, schemaFrom, schemaTo }; }; prepareRenameEnumJson = (nameFrom, nameTo, schema6) => { return { type: "rename_type_enum", nameFrom, nameTo, schema: schema6 }; }; prepareCreateSequenceJson = (seq) => { const values = PgSquasher.unsquashSequence(seq.values); return { type: "create_sequence", name: seq.name, schema: seq.schema, values }; }; prepareAlterSequenceJson = (seq) => { const values = PgSquasher.unsquashSequence(seq.values); return [ { type: "alter_sequence", schema: seq.schema, name: seq.name, values } ]; }; prepareDropSequenceJson = (name, schema6) => { return { type: "drop_sequence", name, schema: schema6 }; }; prepareMoveSequenceJson = (name, schemaFrom, schemaTo) => { return { type: "move_sequence", name, schemaFrom, schemaTo }; }; prepareRenameSequenceJson = (nameFrom, nameTo, schema6) => { return { type: "rename_sequence", nameFrom, nameTo, schema: schema6 }; }; prepareCreateRoleJson = (role) => { return { type: "create_role", name: role.name, values: { createDb: role.createDb, createRole: role.createRole, inherit: role.inherit } }; }; prepareAlterRoleJson = (role) => { return { type: "alter_role", name: role.name, values: { createDb: role.createDb, createRole: role.createRole, inherit: role.inherit } }; }; prepareDropRoleJson = (name) => { return { type: "drop_role", name }; }; prepareRenameRoleJson = (nameFrom, nameTo) => { return { type: "rename_role", nameFrom, nameTo }; }; prepareCreateSchemasJson = (values) => { return values.map((it) => { return { type: "create_schema", name: it }; }); }; prepareRenameSchemasJson = (values) => { return values.map((it) => { return { type: "rename_schema", from: it.from, to: it.to }; }); }; prepareDeleteSchemasJson = (values) => { return values.map((it) => { return { type: "drop_schema", name: it }; }); }; prepareRenameColumns = (tableName, schema6, pairs) => { return pairs.map((it) => { return { type: "alter_table_rename_column", tableName, oldColumnName: it.from.name, newColumnName: it.to.name, schema: schema6 }; }); }; _prepareDropColumns = (taleName, schema6, columns) => { return columns.map((it) => { return { type: "alter_table_drop_column", tableName: taleName, columnName: it.name, schema: schema6 }; }); }; _prepareAddColumns = (tableName, schema6, columns) => { return columns.map((it) => { return { type: "alter_table_add_column", tableName, column: it, schema: schema6 }; }); }; _prepareSqliteAddColumns = (tableName, columns, referenceData) => { const unsquashed = referenceData.map((addedFkValue) => SQLiteSquasher.unsquashFK(addedFkValue)); return columns.map((it) => { var _a2; const columnsWithReference = unsquashed.find((t4) => t4.columnsFrom.includes(it.name)); if (((_a2 = it.generated) == null ? void 0 : _a2.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 _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s; let statements = []; let dropPkStatements = []; let setPkStatements = []; for (const column11 of columns) { const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name; const table6 = json2.tables[tableName]; const snapshotColumn = table6.columns[columnName]; const columnType = snapshotColumn.type; const columnDefault = snapshotColumn.default; const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0; const columnNotNull = table6.columns[columnName].notNull; const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false; const columnPk = table6.columns[columnName].primaryKey; if (((_a2 = column11.autoincrement) == null ? void 0 : _a2.type) === "added") { statements.push({ type: "alter_table_alter_column_set_autoincrement", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (((_b = column11.autoincrement) == null ? void 0 : _b.type) === "changed") { const type = column11.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 = column11.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 column11 of columns) { const columnName = typeof column11.name !== "string" ? column11.name.new : column11.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 column11.name !== "string") { statements.push({ type: "alter_table_rename_column", tableName, oldColumnName: column11.name.old, newColumnName: column11.name.new, schema: schema6 }); } if (((_d = column11.type) == null ? void 0 : _d.type) === "changed") { statements.push({ type: "alter_table_alter_column_set_type", tableName, columnName, newDataType: column11.type.new, oldDataType: column11.type.old, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk, columnGenerated }); } if (((_e = column11.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column11.primaryKey) == null ? void 0 : _f.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") { dropPkStatements.push({ //// type: "alter_table_alter_column_drop_pk", tableName, columnName, schema: schema6 }); } if (((_g = column11.default) == null ? void 0 : _g.type) === "added") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column11.default.value, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (((_h = column11.default) == null ? void 0 : _h.type) === "changed") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column11.default.new, oldDefaultValue: column11.default.old, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (((_i = column11.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 = column11.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 = column11.notNull) == null ? void 0 : _k.type) === "changed") { const type = column11.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 = column11.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 (((_m2 = column11.generated) == null ? void 0 : _m2.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 = column11.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 = column11.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 = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.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 = column11.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 = column11.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, json1, action) => { var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s; const tableKey2 = `${schema6 || "public"}.${_tableName}`; let statements = []; let dropPkStatements = []; let setPkStatements = []; for (const column11 of columns) { const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name; const tableName = json2.tables[tableKey2].name; const columnType = json2.tables[tableKey2].columns[columnName].type; const columnDefault = json2.tables[tableKey2].columns[columnName].default; const columnGenerated = json2.tables[tableKey2].columns[columnName].generated; const columnOnUpdate = json2.tables[tableKey2].columns[columnName].onUpdate; const columnNotNull = json2.tables[tableKey2].columns[columnName].notNull; const columnAutoIncrement = json2.tables[tableKey2].columns[columnName].autoincrement; const columnPk = json2.tables[tableKey2].columns[columnName].primaryKey; const typeSchema = json2.tables[tableKey2].columns[columnName].typeSchema; const json1ColumnTypeSchema = json1.tables[tableKey2].columns[columnName].typeSchema; const compositePk = json2.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`]; if (typeof column11.name !== "string") { statements.push({ type: "alter_table_rename_column", tableName, oldColumnName: column11.name.old, newColumnName: column11.name.new, schema: schema6 }); } if (((_a2 = column11.type) == null ? void 0 : _a2.type) === "changed") { const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g; const parsedNewColumnType = column11.type.new.replace(arrayDefinitionRegex, ""); const parsedOldColumnType = column11.type.old.replace(arrayDefinitionRegex, ""); const isNewTypeIsEnum = json2.enums[`${typeSchema}.${parsedNewColumnType}`]; const isOldTypeIsEnum = json1.enums[`${json1ColumnTypeSchema}.${parsedOldColumnType}`]; statements.push({ type: "pg_alter_table_alter_column_set_type", tableName, columnName, typeSchema, newDataType: { name: column11.type.new, isEnum: isNewTypeIsEnum ? true : false }, oldDataType: { name: column11.type.old, isEnum: isOldTypeIsEnum ? true : false }, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (((_b = column11.primaryKey) == null ? void 0 : _b.type) === "deleted" || ((_c = column11.primaryKey) == null ? void 0 : _c.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") { dropPkStatements.push({ //// type: "alter_table_alter_column_drop_pk", tableName, columnName, schema: schema6 }); } if (((_d = column11.default) == null ? void 0 : _d.type) === "added") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column11.default.value, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (((_e = column11.default) == null ? void 0 : _e.type) === "changed") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column11.default.new, oldDefaultValue: column11.default.old, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (((_f = column11.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 = column11.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 = column11.notNull) == null ? void 0 : _h.type) === "changed") { const type = column11.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 = column11.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 = column11.identity) == null ? void 0 : _j.type) === "added") { statements.push({ type: "alter_table_alter_column_set_identity", tableName, columnName, schema: schema6, identity: column11.identity.value }); } if (((_k = column11.identity) == null ? void 0 : _k.type) === "changed") { statements.push({ type: "alter_table_alter_column_change_identity", tableName, columnName, schema: schema6, identity: column11.identity.new, oldIdentity: column11.identity.old }); } if (((_l = column11.identity) == null ? void 0 : _l.type) === "deleted") { statements.push({ type: "alter_table_alter_column_drop_identity", tableName, columnName, schema: schema6 }); } if (((_m2 = column11.generated) == null ? void 0 : _m2.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 = column11.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 = column11.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 = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.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 = column11.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 = column11.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 _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s; let statements = []; let dropPkStatements = []; let setPkStatements = []; for (const column11 of columns) { const columnName = typeof column11.name !== "string" ? column11.name.new : column11.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 (((_a2 = column11.autoincrement) == null ? void 0 : _a2.type) === "added") { statements.push({ type: "alter_table_alter_column_set_autoincrement", tableName, columnName, schema: schema6, newDataType: columnType, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (((_b = column11.autoincrement) == null ? void 0 : _b.type) === "changed") { const type = column11.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 = column11.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 column11.name !== "string") { statements.push({ type: "alter_table_rename_column", tableName, oldColumnName: column11.name.old, newColumnName: column11.name.new, schema: schema6 }); } if (((_d = column11.type) == null ? void 0 : _d.type) === "changed") { statements.push({ type: "alter_table_alter_column_set_type", tableName, columnName, newDataType: column11.type.new, oldDataType: column11.type.old, schema: schema6, columnDefault, columnOnUpdate, columnNotNull, columnAutoIncrement, columnPk }); } if (((_e = column11.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column11.primaryKey) == null ? void 0 : _f.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") { dropPkStatements.push({ //// type: "alter_table_alter_column_drop_pk", tableName, columnName, schema: schema6 }); } if (((_g = column11.default) == null ? void 0 : _g.type) === "added") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column11.default.value, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (((_h = column11.default) == null ? void 0 : _h.type) === "changed") { statements.push({ type: "alter_table_alter_column_set_default", tableName, columnName, newDefaultValue: column11.default.new, oldDefaultValue: column11.default.old, schema: schema6, columnOnUpdate, columnNotNull, columnAutoIncrement, newDataType: columnType, columnPk }); } if (((_i = column11.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 = column11.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 = column11.notNull) == null ? void 0 : _k.type) === "changed") { const type = column11.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 = column11.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 (((_m2 = column11.generated) == null ? void 0 : _m2.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 = column11.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 = column11.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 = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.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 = column11.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 = column11.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 _a2, _b; const res = []; for (const it of Object.values(pks)) { const unsquashed = MySqlSquasher.unsquashPK(it); if (unsquashed.columns.length === 1 && ((_b = (_a2 = json1.tables[tableName]) == null ? void 0 : _a2.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 = (view5) => { return { type: "alter_mysql_view", ...view5 }; }; } }); // src/statementCombiner.ts var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements; var init_statementCombiner = __esm({ "src/statementCombiner.ts"() { "use strict"; init_jsonStatements(); init_sqliteSchema(); prepareLibSQLRecreateTable = (table6, action) => { const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6; const composites = Object.values(table6.compositePrimaryKeys).map( (it) => SQLiteSquasher.unsquashPK(it) ); const references2 = Object.values(table6.foreignKeys); const fks = references2.map( (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it) ); const statements = [ { type: "recreate_table", tableName: name, columns: Object.values(columns), compositePKs: composites, referenceData: fks, uniqueConstraints: Object.values(uniqueConstraints), checkConstraints: Object.values(checkConstraints) } ]; if (Object.keys(indexes).length) { statements.push(...prepareCreateIndexesJson(name, "", indexes)); } return statements; }; prepareSQLiteRecreateTable = (table6, action) => { const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6; const composites = Object.values(table6.compositePrimaryKeys).map( (it) => SQLiteSquasher.unsquashPK(it) ); const references2 = Object.values(table6.foreignKeys); const fks = references2.map( (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it) ); const statements = [ { type: "recreate_table", tableName: name, columns: Object.values(columns), compositePKs: composites, referenceData: fks, uniqueConstraints: Object.values(uniqueConstraints), checkConstraints: Object.values(checkConstraints) } ]; if (Object.keys(indexes).length) { statements.push(...prepareCreateIndexesJson(name, "", indexes)); } return statements; }; libSQLCombineStatements = (statements, json2, action) => { const newStatements = {}; for (const statement of statements) { if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") { const { tableName: tableName2, columnName, columnPk } = statement; const columnIsPartOfForeignKey = Object.values( json2.tables[tableName2].foreignKeys ).some((it) => { const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it); return unsquashFk.columnsFrom.includes(columnName); }); const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) { if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } } continue; } if (statementsForTable2 && !(columnIsPartOfForeignKey || columnPk)) { if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { newStatements[tableName2].push(statement); } continue; } newStatements[tableName2] = [statement]; continue; } if (statement.type === "create_reference") { const tableName2 = statement.tableName; const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data); const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json2.tables[tableName2], action) : [statement]; continue; } if (!statement.isMulticolumn && statementsForTable2.some( (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0] )) { continue; } if (statement.isMulticolumn) { if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { newStatements[tableName2].push(statement); } continue; } if (statement.type === "delete_reference") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName; const statementsForTable = newStatements[tableName]; if (!statementsForTable) { newStatements[tableName] = [statement]; continue; } if (!statementsForTable.some(({ type }) => type === "recreate_table")) { newStatements[tableName].push(statement); } } const combinedStatements = Object.values(newStatements).flat(); const renamedTables = combinedStatements.filter((it) => it.type === "rename_table"); const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column"); const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column"); return [...renamedTables, ...renamedColumns, ...rest]; }; sqliteCombineStatements = (statements, json2, action) => { const newStatements = {}; for (const statement of statements) { if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "create_reference") { const tableName2 = statement.tableName; const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data); const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action); continue; } if (data.columnsFrom.length === 1 && statementsForTable2.some( (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0] )) { continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName; const statementsForTable = newStatements[tableName]; if (!statementsForTable) { newStatements[tableName] = [statement]; continue; } if (!statementsForTable.some(({ type }) => type === "recreate_table")) { newStatements[tableName].push(statement); } } const combinedStatements = Object.values(newStatements).flat(); const renamedTables = combinedStatements.filter((it) => it.type === "rename_table"); const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column"); const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column"); return [...renamedTables, ...renamedColumns, ...rest]; }; prepareSingleStoreRecreateTable = (table6) => { const { name, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table6; const composites = Object.values(compositePrimaryKeys); const statements = [ { type: "singlestore_recreate_table", tableName: name, columns: Object.values(columns), compositePKs: composites, uniqueConstraints: Object.values(uniqueConstraints) } ]; if (Object.keys(indexes).length) { statements.push(...prepareCreateIndexesJson(name, "", indexes)); } return statements; }; singleStoreCombineStatements = (statements, json2) => { const newStatements = {}; for (const statement of statements) { if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some( ({ type }) => type === "rename_table" || type === "alter_table_rename_column" ); const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if ((statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_default") && statement.columnNotNull) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } if (statement.type === "alter_table_add_column" && statement.column.primaryKey) { const tableName2 = statement.tableName; const statementsForTable2 = newStatements[tableName2]; if (!statementsForTable2) { newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]); continue; } if (!statementsForTable2.some(({ type }) => type === "recreate_table")) { const wasRename = statementsForTable2.some(({ type }) => type === "rename_table"); const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]); if (wasRename) { newStatements[tableName2].push(...preparedStatements); } else { newStatements[tableName2] = preparedStatements; } continue; } continue; } const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName; const statementsForTable = newStatements[tableName]; if (!statementsForTable) { newStatements[tableName] = [statement]; continue; } if (!statementsForTable.some(({ type }) => type === "singlestore_recreate_table")) { newStatements[tableName].push(statement); } } const combinedStatements = Object.values(newStatements).flat(); const renamedTables = combinedStatements.filter((it) => it.type === "rename_table"); const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column"); const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column"); return [...renamedTables, ...renamedColumns, ...rest]; }; } }); // src/snapshotsDiffer.ts var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema3, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSingleStore, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff; var init_snapshotsDiffer = __esm({ "src/snapshotsDiffer.ts"() { "use strict"; init_esm(); init_jsonDiffer(); init_sqlgenerator(); init_jsonStatements(); init_global(); init_mysqlSchema(); init_pgSchema(); init_singlestoreSchema(); init_sqliteSchema(); init_statementCombiner(); init_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(); enumSchema3 = objectType({ name: stringType(), schema: stringType(), values: arrayType(stringType()) }).strict(); changedEnumSchema = objectType({ name: stringType(), schema: stringType(), addedValues: objectType({ before: stringType(), value: stringType() }).array(), deletedValues: arrayType(stringType()) }).strict(); tableScheme = objectType({ name: stringType(), schema: stringType().default(""), columns: recordType(stringType(), columnSchema), indexes: recordType(stringType(), stringType()), foreignKeys: recordType(stringType(), stringType()), compositePrimaryKeys: recordType(stringType(), stringType()).default({}), uniqueConstraints: recordType(stringType(), stringType()).default({}), policies: recordType(stringType(), stringType()).default({}), checkConstraints: recordType(stringType(), stringType()).default({}), isRLSEnabled: booleanType().default(false) }).strict(); alteredTableScheme = objectType({ name: stringType(), schema: stringType(), altered: alteredColumnSchema.array(), addedIndexes: recordType(stringType(), stringType()), deletedIndexes: recordType(stringType(), stringType()), alteredIndexes: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }).strict() ), addedForeignKeys: recordType(stringType(), stringType()), deletedForeignKeys: recordType(stringType(), stringType()), alteredForeignKeys: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }).strict() ), addedCompositePKs: recordType(stringType(), stringType()), deletedCompositePKs: recordType(stringType(), stringType()), alteredCompositePKs: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ), addedUniqueConstraints: recordType(stringType(), stringType()), deletedUniqueConstraints: recordType(stringType(), stringType()), alteredUniqueConstraints: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ), addedPolicies: recordType(stringType(), stringType()), deletedPolicies: recordType(stringType(), stringType()), alteredPolicies: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ), addedCheckConstraints: recordType( stringType(), stringType() ), deletedCheckConstraints: recordType( stringType(), stringType() ), alteredCheckConstraints: recordType( stringType(), objectType({ __new: stringType(), __old: stringType() }) ) }).strict(); alteredViewCommon = objectType({ name: stringType(), alteredDefinition: objectType({ __old: stringType(), __new: stringType() }).strict().optional(), alteredExisting: objectType({ __old: booleanType(), __new: booleanType() }).strict().optional() }); alteredPgViewSchema = alteredViewCommon.merge( objectType({ schema: stringType(), deletedWithOption: 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 = (table6, renamedSchemas) => { for (let ren of renamedSchemas) { if (table6.schema === ren.from.name) { return { key: `${ren.to.name}.${table6.name}`, schema: ren.to.name }; } } return { key: `${table6.schema || "public"}.${table6.name}`, schema: table6.schema }; }; nameChangeFor = (table6, renamed) => { for (let ren of renamed) { if (table6.name === ren.from.name) { return { name: ren.to.name }; } } return { name: table6.name }; }; nameSchemaChangeFor = (table6, renamedTables) => { for (let ren of renamedTables) { if (table6.name === ren.from.name && table6.schema === ren.from.schema) { return { key: `${ren.to.schema || "public"}.${ren.to.name}`, name: ren.to.name, schema: ren.to.schema }; } } return { key: `${table6.schema || "public"}.${table6.name}`, name: table6.name, schema: table6.schema }; }; columnChangeFor = (column11, renamedColumns) => { for (let ren of renamedColumns) { if (column11 === ren.from.name) { return ren.to.name; } } return column11; }; applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, indPolicyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas); const { created: createdSchemas, deleted: deletedSchemas, renamed: renamedSchemas } = await schemasResolver2({ created: schemasDiff.added.map((it) => ({ name: it })), deleted: schemasDiff.deleted.map((it) => ({ name: it })) }); const schemasPatchedSnap1 = copy(json1); schemasPatchedSnap1.tables = mapEntries( schemasPatchedSnap1.tables, (_3, it) => { const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas); it.schema = schema6; return [key, it]; } ); schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => { const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas); it.schema = schema6; return [key, it]; }); const enumsDiff = diffSchemasOrTables(schemasPatchedSnap1.enums, json2.enums); const { created: createdEnums, deleted: deletedEnums, renamed: renamedEnums, moved: movedEnums } = await enumsResolver2({ created: enumsDiff.added, deleted: enumsDiff.deleted }); schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => { const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedEnums); it.name = name; it.schema = schema6; return [key, it]; }); const columnTypesChangeMap = renamedEnums.reduce( (acc, it) => { acc[`${it.from.schema}.${it.from.name}`] = { nameFrom: it.from.name, nameTo: it.to.name, schemaFrom: it.from.schema, schemaTo: it.to.schema }; return acc; }, {} ); const columnTypesMovesMap = movedEnums.reduce( (acc, it) => { acc[`${it.schemaFrom}.${it.name}`] = { nameFrom: it.name, nameTo: it.name, schemaFrom: it.schemaFrom, schemaTo: it.schemaTo }; return acc; }, {} ); schemasPatchedSnap1.tables = mapEntries( schemasPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapValues(tableValue.columns, (column11) => { const key = `${column11.typeSchema || "public"}.${column11.type}`; const change = columnTypesChangeMap[key] || columnTypesMovesMap[key]; if (change) { column11.type = change.nameTo; column11.typeSchema = change.schemaTo; } return column11; }); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); schemasPatchedSnap1.sequences = mapEntries( schemasPatchedSnap1.sequences, (_3, it) => { const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas); it.schema = schema6; return [key, it]; } ); const sequencesDiff = diffSchemasOrTables( schemasPatchedSnap1.sequences, json2.sequences ); const { created: createdSequences, deleted: deletedSequences, renamed: renamedSequences, moved: movedSequences } = await sequencesResolver2({ created: sequencesDiff.added, deleted: sequencesDiff.deleted }); schemasPatchedSnap1.sequences = mapEntries( schemasPatchedSnap1.sequences, (_3, it) => { const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedSequences); it.name = name; it.schema = schema6; return [key, it]; } ); const sequencesChangeMap = renamedSequences.reduce( (acc, it) => { acc[`${it.from.schema}.${it.from.name}`] = { nameFrom: it.from.name, nameTo: it.to.name, schemaFrom: it.from.schema, schemaTo: it.to.schema }; return acc; }, {} ); const sequencesMovesMap = movedSequences.reduce( (acc, it) => { acc[`${it.schemaFrom}.${it.name}`] = { nameFrom: it.name, nameTo: it.name, schemaFrom: it.schemaFrom, schemaTo: it.schemaTo }; return acc; }, {} ); schemasPatchedSnap1.tables = mapEntries( schemasPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapValues(tableValue.columns, (column11) => { const key = `${column11.typeSchema || "public"}.${column11.type}`; const change = sequencesChangeMap[key] || sequencesMovesMap[key]; if (change) { column11.type = change.nameTo; column11.typeSchema = change.schemaTo; } return column11; }); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const rolesDiff = diffSchemasOrTables( schemasPatchedSnap1.roles, json2.roles ); const { created: createdRoles, deleted: deletedRoles, renamed: renamedRoles } = await roleResolver2({ created: rolesDiff.added, deleted: rolesDiff.deleted }); schemasPatchedSnap1.roles = mapEntries( schemasPatchedSnap1.roles, (_3, it) => { const { name } = nameChangeFor(it, renamedRoles); it.name = name; return [name, it]; } ); const rolesChangeMap = renamedRoles.reduce( (acc, it) => { acc[it.from.name] = { nameFrom: it.from.name, nameTo: it.to.name }; return acc; }, {} ); schemasPatchedSnap1.roles = mapEntries( schemasPatchedSnap1.roles, (roleKey, roleValue) => { const key = roleKey; const change = rolesChangeMap[key]; if (change) { roleValue.name = change.nameTo; } return [roleKey, roleValue]; } ); const tablesDiff = diffSchemasOrTables( schemasPatchedSnap1.tables, json2.tables ); const { created: createdTables, deleted: deletedTables, moved: movedTables, renamed: renamedTables // renamed or moved } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(schemasPatchedSnap1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedTables); it.name = name; it.schema = schema6; return [key, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created: created2, deleted: deleted2 } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created2.length > 0) { columnCreates.push({ table: entry.name, schema: entry.schema, columns: created2 }); } if (deleted2.length > 0) { columnDeletes.push({ table: entry.name, schema: entry.schema, columns: deleted2 }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, schema: entry.schema, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[`${it.schema || "public"}.${it.table}`] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column11) => { const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || []; const newName = columnChangeFor(columnKey, rens); column11.name = newName; return newName; } ); tableValue.columns = patchedColumns; return [tableKey2, tableValue]; } ); const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables); const policyRenames = []; const policyCreates = []; const policyDeletes = []; for (let entry of Object.values(policyRes)) { const { renamed, created: created2, deleted: deleted2 } = await policyResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.policies.deleted.map( action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy ), created: entry.policies.added.map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy) }); if (created2.length > 0) { policyCreates.push({ table: entry.name, schema: entry.schema, columns: created2 }); } if (deleted2.length > 0) { policyDeletes.push({ table: entry.name, schema: entry.schema, columns: deleted2 }); } if (renamed.length > 0) { policyRenames.push({ table: entry.name, schema: entry.schema, renames: renamed }); } } const policyRenamesDict = columnRenames.reduce( (acc, it) => { acc[`${it.schema || "public"}.${it.table}`] = it.renames; return acc; }, {} ); const policyPatchedSnap1 = copy(tablesPatchedSnap1); policyPatchedSnap1.tables = mapEntries( policyPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedPolicies = mapKeys( tableValue.policies, (policyKey, policy5) => { const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || []; const newName = columnChangeFor(policyKey, rens); const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy5) : PgSquasher.unsquashPolicy(policy5); unsquashedPolicy.name = newName; policy5 = PgSquasher.squashPolicy(unsquashedPolicy); return newName; } ); tableValue.policies = patchedPolicies; return [tableKey2, tableValue]; } ); const indPolicyRes = diffIndPolicies(policyPatchedSnap1.policies, json2.policies); const indPolicyCreates = []; const indPolicyDeletes = []; const { renamed: indPolicyRenames, created, deleted } = await indPolicyResolver2({ deleted: indPolicyRes.deleted.map( (t4) => action === "push" ? PgSquasher.unsquashPolicyPush(t4.values) : PgSquasher.unsquashPolicy(t4.values) ), created: indPolicyRes.added.map( (t4) => action === "push" ? PgSquasher.unsquashPolicyPush(t4.values) : PgSquasher.unsquashPolicy(t4.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 k3 of Object.keys(it.alteredUniqueConstraints)) { added[k3] = it.alteredUniqueConstraints[k3].__new; deleted2[k3] = it.alteredUniqueConstraints[k3].__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 k3 of Object.keys(it.alteredCheckConstraints)) { added[k3] = it.alteredCheckConstraints[k3].__new; deleted2[k3] = it.alteredCheckConstraints[k3].__old; } createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added)); deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted2)); } jsonCreatedCheckConstraints.push(...createCheckConstraints); jsonDeletedCheckConstraints.push(...deleteCheckConstraints); jsonAddedCompositePKs.push(...addedCompositePKs); jsonDeletedCompositePKs.push(...deletedCompositePKs); jsonAlteredCompositePKs.push(...alteredCompositePKs); jsonAddedUniqueConstraints.push(...addedUniqueConstraints); jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints); jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints); } const rColumns = jsonRenameColumnsStatements.map((it) => { const tableName = it.tableName; const schema6 = it.schema; return { from: { schema: schema6, table: tableName, column: it.oldColumnName }, to: { schema: schema6, table: tableName, column: it.newColumnName } }; }); const jsonTableAlternations = alteredTables.map((it) => { return preparePgAlterColumns( it.name, it.schema, it.altered, json2, json1, action ); }).flat(); const jsonCreateIndexesFoAlteredTables = alteredTables.map((it) => { return preparePgCreateIndexesJson( it.name, it.schema, it.addedIndexes || {}, curFull, action ); }).flat(); const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareDropIndexesJson( it.name, it.schema, it.deletedIndexes || {} ); }).flat(); const jsonCreatePoliciesStatements = []; const jsonDropPoliciesStatements = []; const jsonAlterPoliciesStatements = []; const jsonRenamePoliciesStatements = []; const jsonRenameIndPoliciesStatements = []; const jsonCreateIndPoliciesStatements = []; const jsonDropIndPoliciesStatements = []; const jsonAlterIndPoliciesStatements = []; const jsonEnableRLSStatements = []; const jsonDisableRLSStatements = []; for (let it of indPolicyRenames) { jsonRenameIndPoliciesStatements.push( ...prepareRenameIndPolicyJsons([it]) ); } for (const it of indPolicyCreates) { jsonCreateIndPoliciesStatements.push( ...prepareCreateIndPolicyJsons( it.policies ) ); } for (const it of indPolicyDeletes) { jsonDropIndPoliciesStatements.push( ...prepareDropIndPolicyJsons( it.policies ) ); } typedResult.alteredPolicies.forEach(({ values }) => { const policy5 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values); const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json2.policies[policy5.name].values); const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy5.name].values); if (newPolicy.as !== oldPolicy.as) { jsonDropIndPoliciesStatements.push( ...prepareDropIndPolicyJsons( [oldPolicy] ) ); jsonCreateIndPoliciesStatements.push( ...prepareCreateIndPolicyJsons( [newPolicy] ) ); return; } if (newPolicy.for !== oldPolicy.for) { jsonDropIndPoliciesStatements.push( ...prepareDropIndPolicyJsons( [oldPolicy] ) ); jsonCreateIndPoliciesStatements.push( ...prepareCreateIndPolicyJsons( [newPolicy] ) ); return; } jsonAlterIndPoliciesStatements.push( prepareAlterIndPolicyJson( oldPolicy, newPolicy ) ); }); for (let it of policyRenames) { jsonRenamePoliciesStatements.push( ...prepareRenamePolicyJsons(it.table, it.schema, it.renames) ); } for (const it of policyCreates) { jsonCreatePoliciesStatements.push( ...prepareCreatePolicyJsons( it.table, it.schema, it.columns ) ); } for (const it of policyDeletes) { jsonDropPoliciesStatements.push( ...prepareDropPolicyJsons( it.table, it.schema, it.columns ) ); } alteredTables.forEach((it) => { Object.keys(it.alteredPolicies).forEach((policyName) => { const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__new) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new); const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__old) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old); if (newPolicy.as !== oldPolicy.as) { jsonDropPoliciesStatements.push( ...prepareDropPolicyJsons( it.name, it.schema, [oldPolicy] ) ); jsonCreatePoliciesStatements.push( ...prepareCreatePolicyJsons( it.name, it.schema, [newPolicy] ) ); return; } if (newPolicy.for !== oldPolicy.for) { jsonDropPoliciesStatements.push( ...prepareDropPolicyJsons( it.name, it.schema, [oldPolicy] ) ); jsonCreatePoliciesStatements.push( ...prepareCreatePolicyJsons( it.name, it.schema, [newPolicy] ) ); return; } jsonAlterPoliciesStatements.push( prepareAlterPolicyJson( it.name, it.schema, it.alteredPolicies[policyName].__old, it.alteredPolicies[policyName].__new ) ); }); for (const table6 of Object.values(json2.tables)) { const policiesInCurrentState = Object.keys(table6.policies); const tableInPreviousState = columnsPatchedSnap1.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`]; const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : []; if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table6.isRLSEnabled) { jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema }); } if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table6.isRLSEnabled) { jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema }); } const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false; if (table6.isRLSEnabled !== wasRlsEnabled) { if (table6.isRLSEnabled) { jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema }); } else if (!table6.isRLSEnabled && policiesInCurrentState.length === 0) { jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema }); } } } for (const table6 of Object.values(columnsPatchedSnap1.tables)) { const tableInCurrentState = json2.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`]; if (tableInCurrentState === void 0 && !table6.isRLSEnabled) { jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema }); } } const droppedIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__old; return current; }, {} ); const createdIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__new; return current; }, {} ); jsonCreateIndexesFoAlteredTables.push( ...preparePgCreateIndexesJson( it.name, it.schema, createdIndexes || {}, curFull, action ) ); jsonDropIndexesForAllAlteredTables.push( ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {}) ); }); const jsonCreateReferencesForCreatedTables = createdTables.map((it) => { return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys); }).flat(); const jsonReferencesForAlteredTables = alteredTables.map((it) => { const forAdded = prepareCreateReferencesJson( it.name, it.schema, it.addedForeignKeys ); const forAltered = prepareDropReferencesJson( it.name, it.schema, it.deletedForeignKeys ); const alteredFKs = prepareAlterReferencesJson( it.name, it.schema, it.alteredForeignKeys ); return [...forAdded, ...forAltered, ...alteredFKs]; }).flat(); const jsonCreatedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter( (t4) => t4.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter( (t4) => t4.type === "delete_reference" ); const createEnums = createdEnums.map((it) => { return prepareCreateEnumJson(it.name, it.schema, it.values); }) ?? []; const dropEnums = deletedEnums.map((it) => { return prepareDropEnumJson(it.name, it.schema); }); const moveEnums = movedEnums.map((it) => { return prepareMoveEnumJson(it.name, it.schemaFrom, it.schemaTo); }); const renameEnums = renamedEnums.map((it) => { return prepareRenameEnumJson(it.from.name, it.to.name, it.to.schema); }); const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => { return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues); }).flat() ?? []; const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => { return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull); }).flat() ?? []; const createSequences = createdSequences.map((it) => { return prepareCreateSequenceJson(it); }) ?? []; const dropSequences = deletedSequences.map((it) => { return prepareDropSequenceJson(it.name, it.schema); }); const moveSequences = movedSequences.map((it) => { return prepareMoveSequenceJson(it.name, it.schemaFrom, it.schemaTo); }); const renameSequences = renamedSequences.map((it) => { return prepareRenameSequenceJson(it.from.name, it.to.name, it.to.schema); }); const jsonAlterSequences = typedResult.alteredSequences.map((it) => { return prepareAlterSequenceJson(it); }).flat() ?? []; const createRoles = createdRoles.map((it) => { return prepareCreateRoleJson(it); }) ?? []; const dropRoles = deletedRoles.map((it) => { return prepareDropRoleJson(it.name); }); const renameRoles = renamedRoles.map((it) => { return prepareRenameRoleJson(it.from.name, it.to.name); }); const jsonAlterRoles = typedResult.alteredRoles.map((it) => { return prepareAlterRoleJson(it); }).flat() ?? []; const createSchemas = prepareCreateSchemasJson( createdSchemas.map((it) => it.name) ); const renameSchemas = prepareRenameSchemasJson( renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name })) ); const dropSchemas = prepareDeleteSchemasJson( deletedSchemas.map((it) => it.name) ); const createTables = createdTables.map((it) => { return preparePgCreateTableJson(it, curFull); }); jsonCreatePoliciesStatements.push(...[].concat( ...createdTables.map( (it) => prepareCreatePolicyJsons( it.name, it.schema, Object.values(it.policies).map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy) ) ) )); const createViews = []; const dropViews = []; const renameViews = []; const alterViews = []; createViews.push( ...createdViews.filter((it) => !it.isExisting).map((it) => { return preparePgCreateViewJson( it.name, it.schema, it.definition, it.materialized, it.withNoData, it.with, it.using, it.tablespace ); }) ); dropViews.push( ...deletedViews.filter((it) => !it.isExisting).map((it) => { return prepareDropViewJson(it.name, it.schema, it.materialized); }) ); renameViews.push( ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => { return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized); }) ); alterViews.push( ...movedViews.filter( (it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting ).map((it) => { return preparePgAlterViewAlterSchemaJson( it.schemaTo, it.schemaFrom, it.name, json2.views[`${it.schemaTo}.${it.name}`].materialized ); }) ); const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting); for (const alteredView of alteredViews) { const viewKey = `${alteredView.schema}.${alteredView.name}`; const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey]; if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") { dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized)); createViews.push( preparePgCreateViewJson( alteredView.name, alteredView.schema, definition, materialized, withNoData, withOption, using, tablespace ) ); continue; } if (alteredView.addedWithOption) { alterViews.push( preparePgAlterViewAddWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.addedWithOption ) ); } if (alteredView.deletedWithOption) { alterViews.push( preparePgAlterViewDropWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.deletedWithOption ) ); } if (alteredView.addedWith) { alterViews.push( preparePgAlterViewAddWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.addedWith ) ); } if (alteredView.deletedWith) { alterViews.push( preparePgAlterViewDropWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.deletedWith ) ); } if (alteredView.alteredWith) { alterViews.push( preparePgAlterViewAddWithOptionJson( alteredView.name, alteredView.schema, materialized, alteredView.alteredWith ) ); } if (alteredView.alteredTablespace) { alterViews.push( preparePgAlterViewAlterTablespaceJson( alteredView.name, alteredView.schema, materialized, alteredView.alteredTablespace.__new ) ); } if (alteredView.alteredUsing) { alterViews.push( preparePgAlterViewAlterUsingJson( alteredView.name, alteredView.schema, materialized, alteredView.alteredUsing.__new ) ); } } jsonStatements.push(...createSchemas); jsonStatements.push(...renameSchemas); jsonStatements.push(...createEnums); jsonStatements.push(...moveEnums); jsonStatements.push(...renameEnums); jsonStatements.push(...jsonAlterEnumsWithAddedValues); jsonStatements.push(...createSequences); jsonStatements.push(...moveSequences); jsonStatements.push(...renameSequences); jsonStatements.push(...jsonAlterSequences); jsonStatements.push(...renameRoles); jsonStatements.push(...dropRoles); jsonStatements.push(...createRoles); jsonStatements.push(...jsonAlterRoles); jsonStatements.push(...createTables); jsonStatements.push(...jsonEnableRLSStatements); jsonStatements.push(...jsonDisableRLSStatements); jsonStatements.push(...dropViews); jsonStatements.push(...renameViews); jsonStatements.push(...alterViews); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonSetTableSchemas); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonDeletedCheckConstraints); jsonStatements.push(...jsonDroppedReferencesForAlteredTables); jsonStatements.push(...jsonAlterEnumsWithDroppedValues); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonDeletedCompositePKs); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonCreateReferencesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreatedReferencesForAlteredTables); jsonStatements.push(...jsonCreateIndexesFoAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAlteredCompositePKs); jsonStatements.push(...jsonAddedUniqueConstraints); jsonStatements.push(...jsonCreatedCheckConstraints); jsonStatements.push(...jsonAlteredUniqueConstraints); jsonStatements.push(...createViews); jsonStatements.push(...jsonRenamePoliciesStatements); jsonStatements.push(...jsonDropPoliciesStatements); jsonStatements.push(...jsonCreatePoliciesStatements); jsonStatements.push(...jsonAlterPoliciesStatements); jsonStatements.push(...jsonRenameIndPoliciesStatements); jsonStatements.push(...jsonDropIndPoliciesStatements); jsonStatements.push(...jsonCreateIndPoliciesStatements); jsonStatements.push(...jsonAlterIndPoliciesStatements); jsonStatements.push(...dropEnums); jsonStatements.push(...dropSequences); jsonStatements.push(...dropSchemas); const filteredJsonStatements = jsonStatements.filter((st) => { if (st.type === "alter_table_alter_column_drop_notnull") { if (jsonStatements.find( (it) => it.type === "alter_table_alter_column_drop_identity" && it.tableName === st.tableName && it.schema === st.schema )) { return false; } } if (st.type === "alter_table_alter_column_set_notnull") { if (jsonStatements.find( (it) => it.type === "alter_table_alter_column_set_identity" && it.tableName === st.tableName && it.schema === st.schema )) { return false; } } return true; }); const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => { if (st.type === "alter_type_add_value") { if (filteredJsonStatements.find( (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.enumSchema === st.schema )) { return false; } } return true; }); const filteredEnums2JsonStatements = filteredEnumsJsonStatements.filter((st) => { if (st.type === "alter_table_alter_column_set_default") { if (filteredEnumsJsonStatements.find( (it) => it.type === "pg_alter_table_alter_column_set_type" && it.columnDefault === st.newDefaultValue && it.columnName === st.columnName && it.tableName === st.tableName && it.schema === st.schema )) { return false; } if (filteredEnumsJsonStatements.find( (it) => it.type === "alter_type_drop_value" && it.columnsWithEnum.find( (column11) => column11.default === st.newDefaultValue && column11.column === st.columnName && column11.table === st.tableName && column11.tableSchema === st.schema ) )) { return false; } } return true; }); const sqlStatements = fromJson(filteredEnums2JsonStatements, "postgresql", action); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rSchemas = renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name })); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns); return { statements: filteredEnums2JsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { for (const tableName in json1.tables) { const table6 = json1.tables[tableName]; for (const indexName6 in table6.indexes) { const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName6]); if (index6.isUnique) { table6.uniqueConstraints[indexName6] = MySqlSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json1.tables[tableName].indexes[index6.name]; } } } for (const tableName in json2.tables) { const table6 = json2.tables[tableName]; for (const indexName6 in table6.indexes) { const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName6]); if (index6.isUnique) { table6.uniqueConstraints[indexName6] = MySqlSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json2.tables[tableName].indexes[index6.name]; } } } const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables // renamed or moved } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column11) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column11.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 k3 of Object.keys(it.alteredUniqueConstraints)) { added[k3] = it.alteredUniqueConstraints[k3].__new; deleted[k3] = it.alteredUniqueConstraints[k3].__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 k3 of Object.keys(it.alteredCheckConstraints)) { added[k3] = it.alteredCheckConstraints[k3].__new; deleted[k3] = it.alteredCheckConstraints[k3].__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( (t4) => t4.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t4) => t4.type === "delete_reference" ); const jsonMySqlCreateTables = createdTables.map((it) => { return prepareMySqlCreateTableJson( it, curFull, curFull.internal ); }); const createViews = []; const dropViews = []; const renameViews = []; const alterViews = []; createViews.push( ...createdViews.filter((it) => !it.isExisting).map((it) => { return prepareMySqlCreateViewJson( it.name, it.definition, it.meta ); }) ); dropViews.push( ...deletedViews.filter((it) => !it.isExisting).map((it) => { return prepareDropViewJson(it.name); }) ); renameViews.push( ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => { return prepareRenameViewJson(it.to.name, it.from.name); }) ); const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting); for (const alteredView of alteredViews) { const { definition, meta } = json2.views[alteredView.name]; if (alteredView.alteredExisting) { dropViews.push(prepareDropViewJson(alteredView.name)); createViews.push( prepareMySqlCreateViewJson( alteredView.name, definition, meta ) ); continue; } if (alteredView.alteredDefinition && action !== "push") { createViews.push( prepareMySqlCreateViewJson( alteredView.name, definition, meta, true ) ); continue; } if (alteredView.alteredMeta) { const view5 = curFull["views"][alteredView.name]; alterViews.push( prepareMySqlAlterView(view5) ); } } jsonStatements.push(...jsonMySqlCreateTables); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...dropViews); jsonStatements.push(...renameViews); jsonStatements.push(...alterViews); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonDeletedCheckConstraints); jsonStatements.push(...jsonDroppedReferencesForAlteredTables); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonDeletedCompositePKs); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonAddedUniqueConstraints); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonCreateReferencesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreatedCheckConstraints); jsonStatements.push(...jsonCreatedReferencesForAlteredTables); jsonStatements.push(...jsonCreateIndexesForAllAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAlteredCompositePKs); jsonStatements.push(...createViews); jsonStatements.push(...jsonAlteredUniqueConstraints); const sqlStatements = fromJson(jsonStatements, "mysql"); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta([], rTables, rColumns); return { statements: jsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applySingleStoreSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => { for (const tableName in json1.tables) { const table6 = json1.tables[tableName]; for (const indexName6 in table6.indexes) { const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName6]); if (index6.isUnique) { table6.uniqueConstraints[indexName6] = SingleStoreSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json1.tables[tableName].indexes[index6.name]; } } } for (const tableName in json2.tables) { const table6 = json2.tables[tableName]; for (const indexName6 in table6.indexes) { const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName6]); if (index6.isUnique) { table6.uniqueConstraints[indexName6] = SingleStoreSquasher.squashUnique({ name: index6.name, columns: index6.columns }); delete json2.tables[tableName].indexes[index6.name]; } } } const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables // renamed or moved } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column11) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column11.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 k3 of Object.keys(it.alteredUniqueConstraints)) { added[k3] = it.alteredUniqueConstraints[k3].__new; deleted[k3] = it.alteredUniqueConstraints[k3].__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 k3 of Object.keys(it.alteredCheckConstraints)) { added[k3] = it.alteredCheckConstraints[k3].__new; deleted[k3] = it.alteredCheckConstraints[k3].__old; } createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added)); deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted)); } jsonAddedUniqueConstraints.push(...addedUniqueConstraints); jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints); jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints); }); const rColumns = jsonRenameColumnsStatements.map((it) => { const tableName = it.tableName; const schema6 = it.schema; return { from: { schema: schema6, table: tableName, column: it.oldColumnName }, to: { schema: schema6, table: tableName, column: it.newColumnName } }; }); const jsonTableAlternations = alteredTables.map((it) => { return prepareAlterColumnsMysql( it.name, it.schema, it.altered, json1, json2, action ); }).flat(); const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareCreateIndexesJson( it.name, it.schema, it.addedIndexes || {}, curFull.internal ); }).flat(); const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => { return prepareDropIndexesJson( it.name, it.schema, it.deletedIndexes || {} ); }).flat(); alteredTables.forEach((it) => { const droppedIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__old; return current; }, {} ); const createdIndexes = Object.keys(it.alteredIndexes).reduce( (current, item) => { current[item] = it.alteredIndexes[item].__new; return current; }, {} ); jsonCreateIndexesForAllAlteredTables.push( ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {}) ); jsonDropIndexesForAllAlteredTables.push( ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {}) ); }); const jsonSingleStoreCreateTables = createdTables.map((it) => { return prepareSingleStoreCreateTableJson( it, curFull, curFull.internal ); }); jsonStatements.push(...jsonSingleStoreCreateTables); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddedUniqueConstraints); jsonStatements.push(...jsonDeletedUniqueConstraints); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForAllAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAlteredUniqueConstraints); const combinedJsonStatements = singleStoreCombineStatements(jsonStatements, json2); const sqlStatements = fromJson(combinedJsonStatements, "singlestore"); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta([], rTables, rColumns); return { statements: combinedJsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column11) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column11.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 k3 of Object.keys(it.alteredUniqueConstraints)) { added[k3] = it.alteredUniqueConstraints[k3].__new; deleted[k3] = it.alteredUniqueConstraints[k3].__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 k3 of Object.keys(it.alteredUniqueConstraints)) { added[k3] = it.alteredUniqueConstraints[k3].__new; deleted[k3] = it.alteredUniqueConstraints[k3].__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 k3 of Object.keys(it.alteredCheckConstraints)) { added[k3] = it.alteredCheckConstraints[k3].__new; deleted[k3] = it.alteredCheckConstraints[k3].__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( (t4) => t4.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t4) => t4.type === "delete_reference" ); const createViews = []; const dropViews = []; createViews.push( ...createdViews.filter((it) => !it.isExisting).map((it) => { return prepareSqliteCreateViewJson( it.name, it.definition ); }) ); dropViews.push( ...deletedViews.filter((it) => !it.isExisting).map((it) => { return prepareDropViewJson(it.name); }) ); dropViews.push( ...renamedViews.filter((it) => !it.to.isExisting).map((it) => { return prepareDropViewJson(it.from.name); }) ); createViews.push( ...renamedViews.filter((it) => !it.to.isExisting).map((it) => { return prepareSqliteCreateViewJson(it.to.name, it.to.definition); }) ); const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting); for (const alteredView of alteredViews) { const { definition } = json2.views[alteredView.name]; if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") { dropViews.push(prepareDropViewJson(alteredView.name)); createViews.push( prepareSqliteCreateViewJson( alteredView.name, definition ) ); } } const jsonStatements = []; jsonStatements.push(...jsonCreateTables); jsonStatements.push(...jsonDropTables); jsonStatements.push(...jsonRenameTables); jsonStatements.push(...jsonRenameColumnsStatements); jsonStatements.push(...jsonDroppedReferencesForAlteredTables); jsonStatements.push(...jsonDeletedCheckConstraints); jsonStatements.push(...jsonDropIndexesForAllAlteredTables); jsonStatements.push(...jsonDeletedCompositePKs); jsonStatements.push(...jsonTableAlternations); jsonStatements.push(...jsonAddedCompositePKs); jsonStatements.push(...jsonAddColumnsStatemets); jsonStatements.push(...jsonCreateIndexesForCreatedTables); jsonStatements.push(...jsonCreateIndexesForAllAlteredTables); jsonStatements.push(...jsonCreatedCheckConstraints); jsonStatements.push(...jsonCreatedReferencesForAlteredTables); jsonStatements.push(...jsonDropColumnsStatemets); jsonStatements.push(...jsonAlteredCompositePKs); jsonStatements.push(...jsonAlteredUniqueConstraints); jsonStatements.push(...dropViews); jsonStatements.push(...createViews); const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action); const sqlStatements = fromJson(combinedJsonStatements, "sqlite"); const uniqueSqlStatements = []; sqlStatements.forEach((ss) => { if (!uniqueSqlStatements.includes(ss)) { uniqueSqlStatements.push(ss); } }); const rTables = renamedTables.map((it) => { return { from: it.from, to: it.to }; }); const _meta = prepareMigrationMeta([], rTables, rColumns); return { statements: combinedJsonStatements, sqlStatements: uniqueSqlStatements, _meta }; }; applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => { const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables); const { created: createdTables, deleted: deletedTables, renamed: renamedTables } = await tablesResolver2({ created: tablesDiff.added, deleted: tablesDiff.deleted }); const tablesPatchedSnap1 = copy(json1); tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => { const { name } = nameChangeFor(it, renamedTables); it.name = name; return [name, it]; }); const res = diffColumns(tablesPatchedSnap1.tables, json2.tables); const columnRenames = []; const columnCreates = []; const columnDeletes = []; for (let entry of Object.values(res)) { const { renamed, created, deleted } = await columnsResolver2({ tableName: entry.name, schema: entry.schema, deleted: entry.columns.deleted, created: entry.columns.added }); if (created.length > 0) { columnCreates.push({ table: entry.name, columns: created }); } if (deleted.length > 0) { columnDeletes.push({ table: entry.name, columns: deleted }); } if (renamed.length > 0) { columnRenames.push({ table: entry.name, renames: renamed }); } } const columnRenamesDict = columnRenames.reduce( (acc, it) => { acc[it.table] = it.renames; return acc; }, {} ); const columnsPatchedSnap1 = copy(tablesPatchedSnap1); columnsPatchedSnap1.tables = mapEntries( columnsPatchedSnap1.tables, (tableKey2, tableValue) => { const patchedColumns = mapKeys( tableValue.columns, (columnKey, column11) => { const rens = columnRenamesDict[tableValue.name] || []; const newName = columnChangeFor(columnKey, rens); column11.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 k3 of Object.keys(it.alteredUniqueConstraints)) { added[k3] = it.alteredUniqueConstraints[k3].__new; deleted[k3] = it.alteredUniqueConstraints[k3].__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 k3 of Object.keys(it.alteredCheckConstraints)) { added[k3] = it.alteredCheckConstraints[k3].__new; deleted[k3] = it.alteredCheckConstraints[k3].__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( (t4) => t4.type === "create_reference" ); const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter( (t4) => t4.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 (e4) { console.error(e4); throw e4; } }; tablesResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "table" ); return { created, deleted, moved, renamed }; } catch (e4) { console.error(e4); throw e4; } }; viewsResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "view" ); return { created, deleted, moved, renamed }; } catch (e4) { console.error(e4); throw e4; } }; mySqlViewsResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "view" ); return { created, deleted, moved, renamed }; } catch (e4) { console.error(e4); throw e4; } }; sqliteViewsResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "view" ); return { created, deleted, moved, renamed }; } catch (e4) { console.error(e4); throw e4; } }; sequencesResolver = async (input) => { try { const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict( input.created, input.deleted, "sequence" ); return { created, deleted, moved, renamed }; } catch (e4) { console.error(e4); throw e4; } }; 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 (e4) { console.error(e4); throw e4; } }; 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); } }; 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 (e4) { console.error(e4); } }; 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 index6 = 0; let leftMissing = [...missingColumns]; do { const created = newColumns[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newColumns.length); console.log( source_default.gray(`--- all columns conflicts in ${tableName} table resolved --- `) ); result.deleted.push(...leftMissing); return result; }; promptNamedConflict = async (newItems, missingItems, entity) => { if (missingItems.length === 0 || newItems.length === 0) { return { created: newItems, renamed: [], deleted: missingItems }; } const result = { created: [], renamed: [], deleted: [] }; let index6 = 0; let leftMissing = [...missingItems]; do { const created = newItems[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newItems.length); console.log(source_default.gray(`--- all ${entity} conflicts resolved --- `)); result.deleted.push(...leftMissing); return result; }; promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => { if (missingItems.length === 0 || newItems.length === 0) { return { created: newItems, renamed: [], moved: [], deleted: missingItems }; } const result = { created: [], renamed: [], moved: [], deleted: [] }; let index6 = 0; let leftMissing = [...missingItems]; do { const created = newItems[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newItems.length); console.log(source_default.gray(`--- all ${entity} conflicts resolved --- `)); result.deleted.push(...leftMissing); return result; }; promptSchemasConflict = async (newSchemas, missingSchemas) => { if (missingSchemas.length === 0 || newSchemas.length === 0) { return { created: newSchemas, renamed: [], deleted: missingSchemas }; } const result = { created: [], renamed: [], deleted: [] }; let index6 = 0; let leftMissing = [...missingSchemas]; do { const created = newSchemas[index6]; const renames = leftMissing.map((it) => { return { from: it, to: created }; }); const promptData = [created, ...renames]; const { status, data } = await (0, import_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); } index6 += 1; } while (index6 < newSchemas.length); console.log(source_default.gray("--- all schemas conflicts resolved ---\n")); result.deleted.push(...leftMissing); return result; }; BREAKPOINT = "--> statement-breakpoint\n"; 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.7.2/node_modules/semver/internal/constants.js var require_constants = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js"(exports2, module2) { "use strict"; var SEMVER_SPEC_VERSION = "2.0.0"; var MAX_LENGTH = 256; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; var MAX_SAFE_COMPONENT_LENGTH = 16; var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; var RELEASE_TYPES = [ "major", "premajor", "minor", "preminor", "patch", "prepatch", "prerelease" ]; module2.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 1, FLAG_LOOSE: 2 }; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js var require_debug = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js"(exports2, module2) { "use strict"; var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { }; module2.exports = debug; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js var require_re = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js"(exports2, module2) { "use strict"; var { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH } = require_constants(); var debug = require_debug(); exports2 = module2.exports = {}; var re = exports2.re = []; var safeRe = exports2.safeRe = []; var src = exports2.src = []; var safeSrc = exports2.safeSrc = []; var t4 = exports2.t = {}; var R = 0; var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; var safeRegexReplacements = [ ["\\s", 1], ["\\d", MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] ]; var makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); } return value; }; var createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value); const index6 = R++; debug(name, index6, value); t4[name] = index6; src[index6] = value; safeSrc[index6] = safe; re[index6] = new RegExp(value, isGlobal ? "g" : void 0); safeRe[index6] = new RegExp(safe, isGlobal ? "g" : void 0); }; createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); createToken("MAINVERSION", `(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})`); createToken("MAINVERSIONLOOSE", `(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})`); createToken("PRERELEASEIDENTIFIER", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIER]})`); createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIERLOOSE]})`); createToken("PRERELEASE", `(?:-(${src[t4.PRERELEASEIDENTIFIER]}(?:\\.${src[t4.PRERELEASEIDENTIFIER]})*))`); createToken("PRERELEASELOOSE", `(?:-?(${src[t4.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t4.PRERELEASEIDENTIFIERLOOSE]})*))`); createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); createToken("BUILD", `(?:\\+(${src[t4.BUILDIDENTIFIER]}(?:\\.${src[t4.BUILDIDENTIFIER]})*))`); createToken("FULLPLAIN", `v?${src[t4.MAINVERSION]}${src[t4.PRERELEASE]}?${src[t4.BUILD]}?`); createToken("FULL", `^${src[t4.FULLPLAIN]}$`); createToken("LOOSEPLAIN", `[v=\\s]*${src[t4.MAINVERSIONLOOSE]}${src[t4.PRERELEASELOOSE]}?${src[t4.BUILD]}?`); createToken("LOOSE", `^${src[t4.LOOSEPLAIN]}$`); createToken("GTLT", "((?:<|>)?=?)"); createToken("XRANGEIDENTIFIERLOOSE", `${src[t4.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); createToken("XRANGEIDENTIFIER", `${src[t4.NUMERICIDENTIFIER]}|x|X|\\*`); createToken("XRANGEPLAIN", `[v=\\s]*(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:${src[t4.PRERELEASE]})?${src[t4.BUILD]}?)?)?`); createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:${src[t4.PRERELEASELOOSE]})?${src[t4.BUILD]}?)?)?`); createToken("XRANGE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAIN]}$`); createToken("XRANGELOOSE", `^${src[t4.GTLT]}\\s*${src[t4.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[t4.COERCEPLAIN]}(?:$|[^\\d])`); createToken("COERCEFULL", src[t4.COERCEPLAIN] + `(?:${src[t4.PRERELEASE]})?(?:${src[t4.BUILD]})?(?:$|[^\\d])`); createToken("COERCERTL", src[t4.COERCE], true); createToken("COERCERTLFULL", src[t4.COERCEFULL], true); createToken("LONETILDE", "(?:~>?)"); createToken("TILDETRIM", `(\\s*)${src[t4.LONETILDE]}\\s+`, true); exports2.tildeTrimReplace = "$1~"; createToken("TILDE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAIN]}$`); createToken("TILDELOOSE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAINLOOSE]}$`); createToken("LONECARET", "(?:\\^)"); createToken("CARETTRIM", `(\\s*)${src[t4.LONECARET]}\\s+`, true); exports2.caretTrimReplace = "$1^"; createToken("CARET", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAIN]}$`); createToken("CARETLOOSE", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAINLOOSE]}$`); createToken("COMPARATORLOOSE", `^${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]})$|^$`); createToken("COMPARATOR", `^${src[t4.GTLT]}\\s*(${src[t4.FULLPLAIN]})$|^$`); createToken("COMPARATORTRIM", `(\\s*)${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]}|${src[t4.XRANGEPLAIN]})`, true); exports2.comparatorTrimReplace = "$1$2$3"; createToken("HYPHENRANGE", `^\\s*(${src[t4.XRANGEPLAIN]})\\s+-\\s+(${src[t4.XRANGEPLAIN]})\\s*$`); createToken("HYPHENRANGELOOSE", `^\\s*(${src[t4.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t4.XRANGEPLAINLOOSE]})\\s*$`); createToken("STAR", "(<|>)?=?\\s*\\*"); createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js var require_parse_options = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js"(exports2, module2) { "use strict"; var looseOption = Object.freeze({ loose: true }); var emptyOpts = Object.freeze({}); var parseOptions2 = (options) => { if (!options) { return emptyOpts; } if (typeof options !== "object") { return looseOption; } return options; }; module2.exports = parseOptions2; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js var require_identifiers = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js"(exports2, module2) { "use strict"; var numeric = /^[0-9]+$/; var compareIdentifiers = (a3, b3) => { const anum = numeric.test(a3); const bnum = numeric.test(b3); if (anum && bnum) { a3 = +a3; b3 = +b3; } return a3 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a3 < b3 ? -1 : 1; }; var rcompareIdentifiers = (a3, b3) => compareIdentifiers(b3, a3); module2.exports = { compareIdentifiers, rcompareIdentifiers }; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js var require_semver = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js"(exports2, module2) { "use strict"; var debug = require_debug(); var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); var { safeRe: re, t: t4 } = 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 m4 = version3.trim().match(options.loose ? re[t4.LOOSE] : re[t4.FULL]); if (!m4) { throw new TypeError(`Invalid Version: ${version3}`); } this.raw = version3; this.major = +m4[1]; this.minor = +m4[2]; this.patch = +m4[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 (!m4[4]) { this.prerelease = []; } else { this.prerelease = m4[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 = m4[5] ? m4[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 i4 = 0; do { const a3 = this.prerelease[i4]; const b3 = other.prerelease[i4]; debug("prerelease compare", i4, a3, b3); if (a3 === void 0 && b3 === void 0) { return 0; } else if (b3 === void 0) { return 1; } else if (a3 === void 0) { return -1; } else if (a3 === b3) { continue; } else { return compareIdentifiers(a3, b3); } } while (++i4); } compareBuild(other) { if (!(other instanceof _SemVer)) { other = new _SemVer(other, this.options); } let i4 = 0; do { const a3 = this.build[i4]; const b3 = other.build[i4]; debug("build compare", i4, a3, b3); if (a3 === void 0 && b3 === void 0) { return 0; } else if (b3 === void 0) { return 1; } else if (a3 === void 0) { return -1; } else if (a3 === b3) { continue; } else { return compareIdentifiers(a3, b3); } } while (++i4); } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc(release, identifier, identifierBase) { if (release.startsWith("pre")) { if (!identifier && identifierBase === false) { throw new Error("invalid increment argument: identifier is empty"); } if (identifier) { const match2 = `-${identifier}`.match(this.options.loose ? re[t4.PRERELEASELOOSE] : re[t4.PRERELEASE]); if (!match2 || match2[1] !== identifier) { throw new Error(`invalid identifier: ${identifier}`); } } } 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; // If the input is a non-prerelease version, this acts the same as // prepatch. case "prerelease": if (this.prerelease.length === 0) { this.inc("patch", identifier, identifierBase); } this.inc("pre", identifier, identifierBase); break; case "release": if (this.prerelease.length === 0) { throw new Error(`version ${this.raw} is not a prerelease`); } this.prerelease.length = 0; break; case "major": if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++; } this.minor = 0; this.patch = 0; this.prerelease = []; break; case "minor": if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++; } this.patch = 0; this.prerelease = []; break; case "patch": if (this.prerelease.length === 0) { this.patch++; } this.prerelease = []; break; // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case "pre": { const base = Number(identifierBase) ? 1 : 0; if (this.prerelease.length === 0) { this.prerelease = [base]; } else { let i4 = this.prerelease.length; while (--i4 >= 0) { if (typeof this.prerelease[i4] === "number") { this.prerelease[i4]++; i4 = -2; } } if (i4 === -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.7.2/node_modules/semver/functions/parse.js var require_parse2 = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var parse4 = (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 = parse4; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js var require_valid = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js"(exports2, module2) { "use strict"; var parse4 = require_parse2(); var valid = (version3, options) => { const v6 = parse4(version3, options); return v6 ? v6.version : null; }; module2.exports = valid; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js var require_clean = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js"(exports2, module2) { "use strict"; var parse4 = require_parse2(); var clean = (version3, options) => { const s4 = parse4(version3.trim().replace(/^[=v]+/, ""), options); return s4 ? s4.version : null; }; module2.exports = clean; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js var require_inc = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var inc = (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.7.2/node_modules/semver/functions/diff.js var require_diff = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js"(exports2, module2) { "use strict"; var parse4 = require_parse2(); var diff2 = (version1, version22) => { const v12 = parse4(version1, null, true); const v22 = parse4(version22, null, true); const comparison = v12.compare(v22); if (comparison === 0) { return null; } const v1Higher = comparison > 0; const highVersion = v1Higher ? v12 : v22; const lowVersion = v1Higher ? v22 : v12; const highHasPre = !!highVersion.prerelease.length; const lowHasPre = !!lowVersion.prerelease.length; if (lowHasPre && !highHasPre) { if (!lowVersion.patch && !lowVersion.minor) { return "major"; } if (lowVersion.compareMain(highVersion) === 0) { if (lowVersion.minor && !lowVersion.patch) { return "minor"; } return "patch"; } } const prefix2 = highHasPre ? "pre" : ""; if (v12.major !== v22.major) { return prefix2 + "major"; } if (v12.minor !== v22.minor) { return prefix2 + "minor"; } if (v12.patch !== v22.patch) { return prefix2 + "patch"; } return "prerelease"; }; module2.exports = diff2; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js var require_major = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var major = (a3, loose) => new SemVer(a3, loose).major; module2.exports = major; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js var require_minor = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var minor = (a3, loose) => new SemVer(a3, loose).minor; module2.exports = minor; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js var require_patch = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var patch = (a3, loose) => new SemVer(a3, loose).patch; module2.exports = patch; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js var require_prerelease = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js"(exports2, module2) { "use strict"; var parse4 = require_parse2(); var prerelease = (version3, options) => { const parsed = parse4(version3, options); return parsed && parsed.prerelease.length ? parsed.prerelease : null; }; module2.exports = prerelease; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js var require_compare = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var compare = (a3, b3, loose) => new SemVer(a3, loose).compare(new SemVer(b3, loose)); module2.exports = compare; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js var require_rcompare = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js"(exports2, module2) { "use strict"; var compare = require_compare(); var rcompare = (a3, b3, loose) => compare(b3, a3, loose); module2.exports = rcompare; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js var require_compare_loose = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js"(exports2, module2) { "use strict"; var compare = require_compare(); var compareLoose = (a3, b3) => compare(a3, b3, true); module2.exports = compareLoose; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js var require_compare_build = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var compareBuild = (a3, b3, loose) => { const versionA = new SemVer(a3, loose); const versionB = new SemVer(b3, loose); return versionA.compare(versionB) || versionA.compareBuild(versionB); }; module2.exports = compareBuild; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js var require_sort = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js"(exports2, module2) { "use strict"; var compareBuild = require_compare_build(); var sort = (list, loose) => list.sort((a3, b3) => compareBuild(a3, b3, loose)); module2.exports = sort; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js var require_rsort = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js"(exports2, module2) { "use strict"; var compareBuild = require_compare_build(); var rsort = (list, loose) => list.sort((a3, b3) => compareBuild(b3, a3, loose)); module2.exports = rsort; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js var require_gt = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js"(exports2, module2) { "use strict"; var compare = require_compare(); var gt = (a3, b3, loose) => compare(a3, b3, loose) > 0; module2.exports = gt; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js var require_lt = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js"(exports2, module2) { "use strict"; var compare = require_compare(); var lt = (a3, b3, loose) => compare(a3, b3, loose) < 0; module2.exports = lt; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js var require_eq = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js"(exports2, module2) { "use strict"; var compare = require_compare(); var eq = (a3, b3, loose) => compare(a3, b3, loose) === 0; module2.exports = eq; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js var require_neq = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js"(exports2, module2) { "use strict"; var compare = require_compare(); var neq = (a3, b3, loose) => compare(a3, b3, loose) !== 0; module2.exports = neq; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js var require_gte = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js"(exports2, module2) { "use strict"; var compare = require_compare(); var gte = (a3, b3, loose) => compare(a3, b3, loose) >= 0; module2.exports = gte; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js var require_lte = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js"(exports2, module2) { "use strict"; var compare = require_compare(); var lte = (a3, b3, loose) => compare(a3, b3, loose) <= 0; module2.exports = lte; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js var require_cmp = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js"(exports2, module2) { "use strict"; var eq = require_eq(); var neq = require_neq(); var gt = require_gt(); var gte = require_gte(); var lt = require_lt(); var lte = require_lte(); var cmp = (a3, op, b3, loose) => { switch (op) { case "===": if (typeof a3 === "object") { a3 = a3.version; } if (typeof b3 === "object") { b3 = b3.version; } return a3 === b3; case "!==": if (typeof a3 === "object") { a3 = a3.version; } if (typeof b3 === "object") { b3 = b3.version; } return a3 !== b3; case "": case "=": case "==": return eq(a3, b3, loose); case "!=": return neq(a3, b3, loose); case ">": return gt(a3, b3, loose); case ">=": return gte(a3, b3, loose); case "<": return lt(a3, b3, loose); case "<=": return lte(a3, b3, loose); default: throw new TypeError(`Invalid operator: ${op}`); } }; module2.exports = cmp; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js var require_coerce = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var parse4 = require_parse2(); var { safeRe: re, t: t4 } = 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[t4.COERCEFULL] : re[t4.COERCE]); } else { const coerceRtlRegex = options.includePrerelease ? re[t4.COERCERTLFULL] : re[t4.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 parse4(`${major}.${minor}.${patch}${prerelease}${build}`, options); }; module2.exports = coerce2; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js var require_lrucache = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js"(exports2, module2) { "use strict"; var LRUCache = class { constructor() { this.max = 1e3; this.map = /* @__PURE__ */ new Map(); } get(key) { const value = this.map.get(key); if (value === void 0) { return void 0; } else { this.map.delete(key); this.map.set(key, value); return value; } } delete(key) { return this.map.delete(key); } set(key, value) { const deleted = this.delete(key); if (!deleted && value !== void 0) { if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value; this.delete(firstKey); } this.map.set(key, value); } return this; } }; module2.exports = LRUCache; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js var require_range = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js"(exports2, module2) { "use strict"; var SPACE_CHARACTERS = /\s+/g; var Range = class _Range { constructor(range, options) { options = 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.formatted = void 0; return this; } this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; this.raw = range.trim().replace(SPACE_CHARACTERS, " "); this.set = this.raw.split("||").map((r4) => this.parseRange(r4.trim())).filter((c3) => c3.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((c3) => !isNullSet(c3[0])); if (this.set.length === 0) { this.set = [first]; } else if (this.set.length > 1) { for (const c3 of this.set) { if (c3.length === 1 && isAny(c3[0])) { this.set = [c3]; break; } } } } this.formatted = void 0; } get range() { if (this.formatted === void 0) { this.formatted = ""; for (let i4 = 0; i4 < this.set.length; i4++) { if (i4 > 0) { this.formatted += "||"; } const comps = this.set[i4]; for (let k3 = 0; k3 < comps.length; k3++) { if (k3 > 0) { this.formatted += " "; } this.formatted += comps[k3].toString().trim(); } } } return this.formatted; } format() { return this.range; } toString() { return this.range; } parseRange(range) { const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); const memoKey = memoOpts + ":" + range; const cached = cache3.get(memoKey); if (cached) { return cached; } const loose = this.options.loose; const hr = loose ? re[t4.HYPHENRANGELOOSE] : re[t4.HYPHENRANGE]; range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); debug("hyphen replace", range); range = range.replace(re[t4.COMPARATORTRIM], comparatorTrimReplace); debug("comparator trim", range); range = range.replace(re[t4.TILDETRIM], tildeTrimReplace); debug("tilde trim", range); range = range.replace(re[t4.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[t4.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()]; cache3.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 i4 = 0; i4 < this.set.length; i4++) { if (testSet(this.set[i4], version3, this.options)) { return true; } } return false; } }; module2.exports = Range; var LRU = require_lrucache(); var cache3 = new LRU(); var parseOptions2 = require_parse_options(); var Comparator = require_comparator(); var debug = require_debug(); var SemVer = require_semver(); var { safeRe: re, t: t4, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace } = require_re(); var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants(); var isNullSet = (c3) => c3.value === "<0.0.0-0"; var isAny = (c3) => c3.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((c3) => replaceTilde(c3, options)).join(" "); }; var replaceTilde = (comp, options) => { const r4 = options.loose ? re[t4.TILDELOOSE] : re[t4.TILDE]; return comp.replace(r4, (_3, M, m4, p3, pr) => { debug("tilde", comp, _3, M, m4, p3, pr); let ret; if (isX(M)) { ret = ""; } else if (isX(m4)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; } else if (isX(p3)) { ret = `>=${M}.${m4}.0 <${M}.${+m4 + 1}.0-0`; } else if (pr) { debug("replaceTilde pr", pr); ret = `>=${M}.${m4}.${p3}-${pr} <${M}.${+m4 + 1}.0-0`; } else { ret = `>=${M}.${m4}.${p3} <${M}.${+m4 + 1}.0-0`; } debug("tilde return", ret); return ret; }); }; var replaceCarets = (comp, options) => { return comp.trim().split(/\s+/).map((c3) => replaceCaret(c3, options)).join(" "); }; var replaceCaret = (comp, options) => { debug("caret", comp, options); const r4 = options.loose ? re[t4.CARETLOOSE] : re[t4.CARET]; const z2 = options.includePrerelease ? "-0" : ""; return comp.replace(r4, (_3, M, m4, p3, pr) => { debug("caret", comp, _3, M, m4, p3, pr); let ret; if (isX(M)) { ret = ""; } else if (isX(m4)) { ret = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`; } else if (isX(p3)) { if (M === "0") { ret = `>=${M}.${m4}.0${z2} <${M}.${+m4 + 1}.0-0`; } else { ret = `>=${M}.${m4}.0${z2} <${+M + 1}.0.0-0`; } } else if (pr) { debug("replaceCaret pr", pr); if (M === "0") { if (m4 === "0") { ret = `>=${M}.${m4}.${p3}-${pr} <${M}.${m4}.${+p3 + 1}-0`; } else { ret = `>=${M}.${m4}.${p3}-${pr} <${M}.${+m4 + 1}.0-0`; } } else { ret = `>=${M}.${m4}.${p3}-${pr} <${+M + 1}.0.0-0`; } } else { debug("no pr"); if (M === "0") { if (m4 === "0") { ret = `>=${M}.${m4}.${p3}${z2} <${M}.${m4}.${+p3 + 1}-0`; } else { ret = `>=${M}.${m4}.${p3}${z2} <${M}.${+m4 + 1}.0-0`; } } else { ret = `>=${M}.${m4}.${p3} <${+M + 1}.0.0-0`; } } debug("caret return", ret); return ret; }); }; var replaceXRanges = (comp, options) => { debug("replaceXRanges", comp, options); return comp.split(/\s+/).map((c3) => replaceXRange(c3, options)).join(" "); }; var replaceXRange = (comp, options) => { comp = comp.trim(); const r4 = options.loose ? re[t4.XRANGELOOSE] : re[t4.XRANGE]; return comp.replace(r4, (ret, gtlt, M, m4, p3, pr) => { debug("xRange", comp, ret, gtlt, M, m4, p3, pr); const xM = isX(M); const xm = xM || isX(m4); const xp = xm || isX(p3); 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) { m4 = 0; } p3 = 0; if (gtlt === ">") { gtlt = ">="; if (xm) { M = +M + 1; m4 = 0; p3 = 0; } else { m4 = +m4 + 1; p3 = 0; } } else if (gtlt === "<=") { gtlt = "<"; if (xm) { M = +M + 1; } else { m4 = +m4 + 1; } } if (gtlt === "<") { pr = "-0"; } ret = `${gtlt + M}.${m4}.${p3}${pr}`; } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; } else if (xp) { ret = `>=${M}.${m4}.0${pr} <${M}.${+m4 + 1}.0-0`; } debug("xRange return", ret); return ret; }); }; var replaceStars = (comp, options) => { debug("replaceStars", comp, options); return comp.trim().replace(re[t4.STAR], ""); }; var replaceGTE0 = (comp, options) => { debug("replaceGTE0", comp, options); return comp.trim().replace(re[options.includePrerelease ? t4.GTE0PRE : t4.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 i4 = 0; i4 < set.length; i4++) { if (!set[i4].test(version3)) { return false; } } if (version3.prerelease.length && !options.includePrerelease) { for (let i4 = 0; i4 < set.length; i4++) { debug(set[i4].semver); if (set[i4].semver === Comparator.ANY) { continue; } if (set[i4].semver.prerelease.length > 0) { const allowed = set[i4].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.7.2/node_modules/semver/classes/comparator.js var require_comparator = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js"(exports2, module2) { "use strict"; var ANY = Symbol("SemVer ANY"); var Comparator = class _Comparator { static get ANY() { return ANY; } constructor(comp, options) { options = 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 r4 = this.options.loose ? re[t4.COMPARATORLOOSE] : re[t4.COMPARATOR]; const m4 = comp.match(r4); if (!m4) { throw new TypeError(`Invalid comparator: ${comp}`); } this.operator = m4[1] !== void 0 ? m4[1] : ""; if (this.operator === "=") { this.operator = ""; } if (!m4[2]) { this.semver = ANY; } else { this.semver = new SemVer(m4[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: t4 } = require_re(); var cmp = require_cmp(); var debug = require_debug(); var SemVer = require_semver(); var Range = require_range(); } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js var require_satisfies = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js"(exports2, module2) { "use strict"; var Range = require_range(); var satisfies = (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.7.2/node_modules/semver/ranges/to-comparators.js var require_to_comparators = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js"(exports2, module2) { "use strict"; var Range = require_range(); var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c3) => c3.value).join(" ").trim().split(" ")); module2.exports = toComparators; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js var require_max_satisfying = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Range = require_range(); var maxSatisfying = (versions, range, options) => { let max = null; let maxSV = null; let rangeObj = null; try { rangeObj = new Range(range, options); } catch (er) { return null; } versions.forEach((v6) => { if (rangeObj.test(v6)) { if (!max || maxSV.compare(v6) === -1) { max = v6; maxSV = new SemVer(max, options); } } }); return max; }; module2.exports = maxSatisfying; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js var require_min_satisfying = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Range = require_range(); var minSatisfying = (versions, range, options) => { let min = null; let minSV = null; let rangeObj = null; try { rangeObj = new Range(range, options); } catch (er) { return null; } versions.forEach((v6) => { if (rangeObj.test(v6)) { if (!min || minSV.compare(v6) === 1) { min = v6; minSV = new SemVer(min, options); } } }); return min; }; module2.exports = minSatisfying; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js var require_min_version = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Range = require_range(); var gt = require_gt(); var minVersion = (range, loose) => { range = new Range(range, loose); let minver = new SemVer("0.0.0"); if (range.test(minver)) { return minver; } minver = new SemVer("0.0.0-0"); if (range.test(minver)) { return minver; } minver = null; for (let i4 = 0; i4 < range.set.length; ++i4) { const comparators = range.set[i4]; let setMin = null; comparators.forEach((comparator) => { const compver = new SemVer(comparator.semver.version); switch (comparator.operator) { case ">": if (compver.prerelease.length === 0) { compver.patch++; } else { compver.prerelease.push(0); } compver.raw = compver.format(); /* fallthrough */ case "": case ">=": if (!setMin || gt(compver, setMin)) { setMin = compver; } break; case "<": case "<=": break; /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`); } }); if (setMin && (!minver || gt(minver, setMin))) { minver = setMin; } } if (minver && range.test(minver)) { return minver; } return null; }; module2.exports = minVersion; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js var require_valid2 = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js"(exports2, module2) { "use strict"; var Range = require_range(); var validRange = (range, options) => { try { return new Range(range, options).range || "*"; } catch (er) { return null; } }; module2.exports = validRange; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js var require_outside = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js"(exports2, module2) { "use strict"; var SemVer = require_semver(); var Comparator = require_comparator(); var { ANY } = Comparator; var Range = require_range(); var satisfies = require_satisfies(); var gt = require_gt(); var lt = require_lt(); var lte = require_lte(); var gte = require_gte(); var outside = (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 i4 = 0; i4 < range.set.length; ++i4) { const comparators = range.set[i4]; let high = null; let low = null; comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator(">=0.0.0"); } high = high || comparator; low = low || comparator; if (gtfn(comparator.semver, high.semver, 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.7.2/node_modules/semver/ranges/gtr.js var require_gtr = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js"(exports2, module2) { "use strict"; var outside = require_outside(); var gtr = (version3, range, options) => outside(version3, range, ">", options); module2.exports = gtr; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js var require_ltr = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js"(exports2, module2) { "use strict"; var outside = require_outside(); var ltr = (version3, range, options) => outside(version3, range, "<", options); module2.exports = ltr; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js var require_intersects = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js"(exports2, module2) { "use strict"; var Range = require_range(); var intersects = (r1, r22, options) => { r1 = new Range(r1, options); r22 = new Range(r22, options); return r1.intersects(r22, options); }; module2.exports = intersects; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js var require_simplify = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js"(exports2, module2) { "use strict"; var satisfies = require_satisfies(); var compare = require_compare(); module2.exports = (versions, range, options) => { const set = []; let first = null; let prev = null; const v6 = versions.sort((a3, b3) => compare(a3, b3, options)); for (const version3 of v6) { 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 === v6[0]) { ranges.push("*"); } else if (!max) { ranges.push(`>=${min}`); } else if (min === v6[0]) { ranges.push(`<=${max}`); } else { ranges.push(`${min} - ${max}`); } } const simplified = ranges.join(" || "); const original = typeof range.raw === "string" ? range.raw : String(range); return simplified.length < original.length ? simplified : range; }; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js var require_subset = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js"(exports2, module2) { "use strict"; var Range = require_range(); var Comparator = require_comparator(); var { ANY } = Comparator; var satisfies = require_satisfies(); var compare = require_compare(); var subset = (sub, dom, options = {}) => { if (sub === dom) { return true; } sub = new Range(sub, options); dom = new Range(dom, options); let sawNonNull = false; OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options); sawNonNull = sawNonNull || isSub !== null; if (isSub) { continue OUTER; } } if (sawNonNull) { return false; } } return true; }; var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; var minimumVersion = [new Comparator(">=0.0.0")]; var simpleSubset = (sub, dom, options) => { if (sub === dom) { return true; } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true; } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease; } else { sub = minimumVersion; } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true; } else { dom = minimumVersion; } } const eqSet = /* @__PURE__ */ new Set(); let gt, lt; for (const c3 of sub) { if (c3.operator === ">" || c3.operator === ">=") { gt = higherGT(gt, c3, options); } else if (c3.operator === "<" || c3.operator === "<=") { lt = lowerLT(lt, c3, options); } else { eqSet.add(c3.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 c3 of dom) { if (!satisfies(eq, String(c3), 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 c3 of dom) { hasDomGT = hasDomGT || c3.operator === ">" || c3.operator === ">="; hasDomLT = hasDomLT || c3.operator === "<" || c3.operator === "<="; if (gt) { if (needDomGTPre) { if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomGTPre.major && c3.semver.minor === needDomGTPre.minor && c3.semver.patch === needDomGTPre.patch) { needDomGTPre = false; } } if (c3.operator === ">" || c3.operator === ">=") { higher = higherGT(gt, c3, options); if (higher === c3 && higher !== gt) { return false; } } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c3), options)) { return false; } } if (lt) { if (needDomLTPre) { if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomLTPre.major && c3.semver.minor === needDomLTPre.minor && c3.semver.patch === needDomLTPre.patch) { needDomLTPre = false; } } if (c3.operator === "<" || c3.operator === "<=") { lower2 = lowerLT(lt, c3, options); if (lower2 === c3 && lower2 !== lt) { return false; } } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c3), options)) { return false; } } if (!c3.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 = (a3, b3, options) => { if (!a3) { return b3; } const comp = compare(a3.semver, b3.semver, options); return comp > 0 ? a3 : comp < 0 ? b3 : b3.operator === ">" && a3.operator === ">=" ? b3 : a3; }; var lowerLT = (a3, b3, options) => { if (!a3) { return b3; } const comp = compare(a3.semver, b3.semver, options); return comp < 0 ? a3 : comp > 0 ? b3 : b3.operator === "<" && a3.operator === "<=" ? b3 : a3; }; module2.exports = subset; } }); // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js var require_semver2 = __commonJS({ "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js"(exports2, module2) { "use strict"; var internalRe = require_re(); var constants = require_constants(); var SemVer = require_semver(); var identifiers = require_identifiers(); var parse4 = 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: parse4, valid, clean, inc, diff: diff2, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce: coerce2, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers }; } }); // src/cli/utils.ts var import_semver, 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 (e4) { return false; } }; assertPackages = async (...pkgs) => { try { for (let i4 = 0; i4 < pkgs.length; i4++) { const it = pkgs[i4]; await import(it); } } catch (e4) { 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 (e4) { 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 (e4) { 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 i4 = 1; i4 < meta.length; i4++) { if (meta[i4] === "base64") { base64 = true; } else if (meta[i4]) { typeFull += `;${meta[i4]}`; if (meta[i4].indexOf("charset=") === 0) { charset = meta[i4].substring(8); } } } if (!meta[0] && !charset.length) { typeFull += ";charset=US-ASCII"; charset = "US-ASCII"; } const encoding = 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.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js var require_ponyfill_es2018 = __commonJS({ "../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports2, module2) { (function(global2, factory) { typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); })(exports2, function(exports3) { "use strict"; function noop2() { return void 0; } function typeIsObject(x4) { return typeof x4 === "object" && x4 !== null || typeof x4 === "function"; } const rethrowAssertionErrorRejection = noop2; function setFunctionName(fn, name) { try { Object.defineProperty(fn, "name", { value: name, configurable: true }); } catch (_a3) { } } const originalPromise = Promise; const originalPromiseThen = Promise.prototype.then; const originalPromiseReject = Promise.reject.bind(originalPromise); function newPromise(executor) { return new originalPromise(executor); } function promiseResolvedWith(value) { return newPromise((resolve2) => resolve2(value)); } function promiseRejectedWith(reason) { return originalPromiseReject(reason); } function PerformPromiseThen(promise, onFulfilled, onRejected) { return originalPromiseThen.call(promise, onFulfilled, onRejected); } function uponPromise(promise, onFulfilled, onRejected) { PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection); } function uponFulfillment(promise, onFulfilled) { uponPromise(promise, onFulfilled); } function uponRejection(promise, onRejected) { uponPromise(promise, void 0, onRejected); } function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); } function setPromiseIsHandledToTrue(promise) { PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection); } let _queueMicrotask = (callback) => { if (typeof queueMicrotask === "function") { _queueMicrotask = queueMicrotask; } else { const resolvedPromise = promiseResolvedWith(void 0); _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb); } return _queueMicrotask(callback); }; function reflectCall(F3, V, args) { if (typeof F3 !== "function") { throw new TypeError("Argument is not a function"); } return Function.prototype.apply.call(F3, V, args); } function promiseCall(F3, V, args) { try { return promiseResolvedWith(reflectCall(F3, V, args)); } catch (value) { return promiseRejectedWith(value); } } const QUEUE_MAX_ARRAY_SIZE = 16384; class SimpleQueue { constructor() { this._cursor = 0; this._size = 0; this._front = { _elements: [], _next: void 0 }; this._back = this._front; this._cursor = 0; this._size = 0; } get length() { return this._size; } // For exception safety, this method is structured in order: // 1. Read state // 2. Calculate required state mutations // 3. Perform state mutations push(element) { const oldBack = this._back; let newBack = oldBack; if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { newBack = { _elements: [], _next: void 0 }; } oldBack._elements.push(element); if (newBack !== oldBack) { this._back = newBack; oldBack._next = newBack; } ++this._size; } // Like push(), shift() follows the read -> calculate -> mutate pattern for // exception safety. shift() { const oldFront = this._front; let newFront = oldFront; const oldCursor = this._cursor; let newCursor = oldCursor + 1; const elements = oldFront._elements; const element = elements[oldCursor]; if (newCursor === QUEUE_MAX_ARRAY_SIZE) { newFront = oldFront._next; newCursor = 0; } --this._size; this._cursor = newCursor; if (oldFront !== newFront) { this._front = newFront; } elements[oldCursor] = void 0; return element; } // The tricky thing about forEach() is that it can be called // re-entrantly. The queue may be mutated inside the callback. It is easy to // see that push() within the callback has no negative effects since the end // of the queue is checked for on every iteration. If shift() is called // repeatedly within the callback then the next iteration may return an // element that has been removed. In this case the callback will be called // with undefined values until we either "catch up" with elements that still // exist or reach the back of the queue. forEach(callback) { let i4 = this._cursor; let node = this._front; let elements = node._elements; while (i4 !== elements.length || node._next !== void 0) { if (i4 === elements.length) { node = node._next; elements = node._elements; i4 = 0; if (elements.length === 0) { break; } } callback(elements[i4]); ++i4; } } // Return the element that would be returned if shift() was called now, // without modifying the queue. peek() { const front = this._front; const cursor = this._cursor; return front._elements[cursor]; } } const AbortSteps = Symbol("[[AbortSteps]]"); const ErrorSteps = Symbol("[[ErrorSteps]]"); const CancelSteps = Symbol("[[CancelSteps]]"); const PullSteps = Symbol("[[PullSteps]]"); const ReleaseSteps = Symbol("[[ReleaseSteps]]"); function ReadableStreamReaderGenericInitialize(reader, stream) { reader._ownerReadableStream = stream; stream._reader = reader; if (stream._state === "readable") { defaultReaderClosedPromiseInitialize(reader); } else if (stream._state === "closed") { defaultReaderClosedPromiseInitializeAsResolved(reader); } else { defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); } } function ReadableStreamReaderGenericCancel(reader, reason) { const stream = reader._ownerReadableStream; return ReadableStreamCancel(stream, reason); } function ReadableStreamReaderGenericRelease(reader) { const stream = reader._ownerReadableStream; if (stream._state === "readable") { defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } else { defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } stream._readableStreamController[ReleaseSteps](); stream._reader = void 0; reader._ownerReadableStream = void 0; } function readerLockException(name) { return new TypeError("Cannot " + name + " a stream using a released reader"); } function defaultReaderClosedPromiseInitialize(reader) { reader._closedPromise = newPromise((resolve2, reject) => { reader._closedPromise_resolve = resolve2; reader._closedPromise_reject = reject; }); } function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseReject(reader, reason); } function defaultReaderClosedPromiseInitializeAsResolved(reader) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseResolve(reader); } function defaultReaderClosedPromiseReject(reader, reason) { if (reader._closedPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(reader._closedPromise); reader._closedPromise_reject(reason); reader._closedPromise_resolve = void 0; reader._closedPromise_reject = void 0; } function defaultReaderClosedPromiseResetToRejected(reader, reason) { defaultReaderClosedPromiseInitializeAsRejected(reader, reason); } function defaultReaderClosedPromiseResolve(reader) { if (reader._closedPromise_resolve === void 0) { return; } reader._closedPromise_resolve(void 0); reader._closedPromise_resolve = void 0; reader._closedPromise_reject = void 0; } const NumberIsFinite = Number.isFinite || function(x4) { return typeof x4 === "number" && isFinite(x4); }; const MathTrunc = Math.trunc || function(v6) { return v6 < 0 ? Math.ceil(v6) : Math.floor(v6); }; function isDictionary(x4) { return typeof x4 === "object" || typeof x4 === "function"; } function assertDictionary(obj, context) { if (obj !== void 0 && !isDictionary(obj)) { throw new TypeError(`${context} is not an object.`); } } function assertFunction(x4, context) { if (typeof x4 !== "function") { throw new TypeError(`${context} is not a function.`); } } function isObject(x4) { return typeof x4 === "object" && x4 !== null || typeof x4 === "function"; } function assertObject(x4, context) { if (!isObject(x4)) { throw new TypeError(`${context} is not an object.`); } } function assertRequiredArgument(x4, position, context) { if (x4 === void 0) { throw new TypeError(`Parameter ${position} is required in '${context}'.`); } } function assertRequiredField(x4, field, context) { if (x4 === void 0) { throw new TypeError(`${field} is required in '${context}'.`); } } function convertUnrestrictedDouble(value) { return Number(value); } function censorNegativeZero(x4) { return x4 === 0 ? 0 : x4; } function integerPart(x4) { return censorNegativeZero(MathTrunc(x4)); } function convertUnsignedLongLongWithEnforceRange(value, context) { const lowerBound = 0; const upperBound = Number.MAX_SAFE_INTEGER; let x4 = Number(value); x4 = censorNegativeZero(x4); if (!NumberIsFinite(x4)) { throw new TypeError(`${context} is not a finite number`); } x4 = integerPart(x4); if (x4 < lowerBound || x4 > upperBound) { throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); } if (!NumberIsFinite(x4) || x4 === 0) { return 0; } return x4; } function assertReadableStream(x4, context) { if (!IsReadableStream(x4)) { 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: (e4) => rejectPromise(e4) }; ReadableStreamDefaultReaderRead(this, readRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamDefaultReader(this)) { throw defaultReaderBrandCheckException("releaseLock"); } if (this._ownerReadableStream === void 0) { return; } ReadableStreamDefaultReaderRelease(this); } } Object.defineProperties(ReadableStreamDefaultReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel"); setFunctionName(ReadableStreamDefaultReader.prototype.read, "read"); setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { value: "ReadableStreamDefaultReader", configurable: true }); } function IsReadableStreamDefaultReader(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_readRequests")) { return false; } return x4 instanceof ReadableStreamDefaultReader; } function ReadableStreamDefaultReaderRead(reader, readRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === "closed") { readRequest._closeSteps(); } else if (stream._state === "errored") { readRequest._errorSteps(stream._storedError); } else { stream._readableStreamController[PullSteps](readRequest); } } function ReadableStreamDefaultReaderRelease(reader) { ReadableStreamReaderGenericRelease(reader); const e4 = new TypeError("Reader was released"); ReadableStreamDefaultReaderErrorReadRequests(reader, e4); } function ReadableStreamDefaultReaderErrorReadRequests(reader, e4) { const readRequests = reader._readRequests; reader._readRequests = new SimpleQueue(); readRequests.forEach((readRequest) => { readRequest._errorSteps(e4); }); } function defaultReaderBrandCheckException(name) { return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); } const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); class ReadableStreamAsyncIteratorImpl { constructor(reader, preventCancel) { this._ongoingPromise = void 0; this._isFinished = false; this._reader = reader; this._preventCancel = preventCancel; } next() { const nextSteps = () => this._nextSteps(); this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); return this._ongoingPromise; } return(value) { const returnSteps = () => this._returnSteps(value); return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); } _nextSteps() { if (this._isFinished) { return Promise.resolve({ value: void 0, done: true }); } const reader = this._reader; let resolvePromise; let rejectPromise; const promise = newPromise((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 (!this._preventCancel) { const result = ReadableStreamReaderGenericCancel(reader, value); ReadableStreamReaderGenericRelease(reader); return transformPromiseWith(result, () => ({ value, done: true })); } ReadableStreamReaderGenericRelease(reader); return promiseResolvedWith({ value, done: true }); } } const ReadableStreamAsyncIteratorPrototype = { next() { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); } return this._asyncIteratorImpl.next(); }, return(value) { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); } return this._asyncIteratorImpl.return(value); } }; Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); function AcquireReadableStreamAsyncIterator(stream, preventCancel) { const reader = AcquireReadableStreamDefaultReader(stream); const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); iterator._asyncIteratorImpl = impl; return iterator; } function IsReadableStreamAsyncIterator(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_asyncIteratorImpl")) { return false; } try { return x4._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; } catch (_a3) { return false; } } function streamAsyncIteratorBrandCheckException(name) { return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); } const NumberIsNaN = Number.isNaN || function(x4) { return x4 !== x4; }; var _a2, _b, _c; function CreateArrayFromList(elements) { return elements.slice(); } function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n3) { new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n3), destOffset); } let TransferArrayBuffer = (O) => { if (typeof O.transfer === "function") { TransferArrayBuffer = (buffer) => buffer.transfer(); } else if (typeof structuredClone === "function") { TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] }); } else { TransferArrayBuffer = (buffer) => buffer; } return TransferArrayBuffer(O); }; let IsDetachedBuffer = (O) => { if (typeof O.detached === "boolean") { IsDetachedBuffer = (buffer) => buffer.detached; } else { IsDetachedBuffer = (buffer) => buffer.byteLength === 0; } return IsDetachedBuffer(O); }; function ArrayBufferSlice(buffer, begin, end) { if (buffer.slice) { return buffer.slice(begin, end); } const length = end - begin; const slice = new ArrayBuffer(length); CopyDataBlockBytes(slice, 0, buffer, begin, length); return slice; } function GetMethod(receiver, prop) { const func = receiver[prop]; if (func === void 0 || func === null) { return void 0; } if (typeof func !== "function") { throw new TypeError(`${String(prop)} is not a function`); } return func; } function CreateAsyncFromSyncIterator(syncIteratorRecord) { const syncIterable = { [Symbol.iterator]: () => syncIteratorRecord.iterator }; const asyncIterator = async function* () { return yield* syncIterable; }(); const nextMethod = asyncIterator.next; return { iterator: asyncIterator, nextMethod, done: false }; } const SymbolAsyncIterator = (_c = (_a2 = Symbol.asyncIterator) !== null && _a2 !== void 0 ? _a2 : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== void 0 ? _c : "@@asyncIterator"; function GetIterator(obj, hint = "sync", method) { if (method === void 0) { if (hint === "async") { method = GetMethod(obj, SymbolAsyncIterator); if (method === void 0) { const syncMethod = GetMethod(obj, Symbol.iterator); const syncIteratorRecord = GetIterator(obj, "sync", syncMethod); return CreateAsyncFromSyncIterator(syncIteratorRecord); } } else { method = GetMethod(obj, Symbol.iterator); } } if (method === void 0) { throw new TypeError("The object is not iterable"); } const iterator = reflectCall(method, obj, []); if (!typeIsObject(iterator)) { throw new TypeError("The iterator method must return an object"); } const nextMethod = iterator.next; return { iterator, nextMethod, done: false }; } function IteratorNext(iteratorRecord) { const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); if (!typeIsObject(result)) { throw new TypeError("The iterator.next() method must return an object"); } return result; } function IteratorComplete(iterResult) { return Boolean(iterResult.done); } function IteratorValue(iterResult) { return iterResult.value; } function IsNonNegativeNumber(v6) { if (typeof v6 !== "number") { return false; } if (NumberIsNaN(v6)) { return false; } if (v6 < 0) { return false; } return true; } function CloneAsUint8Array(O) { const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); return new Uint8Array(buffer); } function DequeueValue(container) { const pair = container._queue.shift(); container._queueTotalSize -= pair.size; if (container._queueTotalSize < 0) { container._queueTotalSize = 0; } return pair.value; } function EnqueueValueWithSize(container, value, size) { if (!IsNonNegativeNumber(size) || size === Infinity) { throw new RangeError("Size must be a finite, non-NaN, non-negative number."); } container._queue.push({ value, size }); container._queueTotalSize += size; } function PeekQueueValue(container) { const pair = container._queue.peek(); return pair.value; } function ResetQueue(container) { container._queue = new SimpleQueue(); container._queueTotalSize = 0; } function isDataViewConstructor(ctor) { return ctor === DataView; } function isDataView(view5) { return isDataViewConstructor(view5.constructor); } function arrayBufferViewElementSize(ctor) { if (isDataViewConstructor(ctor)) { return 1; } return ctor.BYTES_PER_ELEMENT; } class ReadableStreamBYOBRequest { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. */ get view() { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException("view"); } return this._view; } respond(bytesWritten) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException("respond"); } assertRequiredArgument(bytesWritten, 1, "respond"); bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); if (this._associatedReadableByteStreamController === void 0) { throw new TypeError("This BYOB request has been invalidated"); } if (IsDetachedBuffer(this._view.buffer)) { throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); } ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); } respondWithNewView(view5) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException("respondWithNewView"); } assertRequiredArgument(view5, 1, "respondWithNewView"); if (!ArrayBuffer.isView(view5)) { throw new TypeError("You can only respond with array buffer views"); } if (this._associatedReadableByteStreamController === void 0) { throw new TypeError("This BYOB request has been invalidated"); } if (IsDetachedBuffer(view5.buffer)) { throw new TypeError("The given view's buffer has been detached and so cannot be used as a response"); } ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view5); } } Object.defineProperties(ReadableStreamBYOBRequest.prototype, { respond: { enumerable: true }, respondWithNewView: { enumerable: true }, view: { enumerable: true } }); setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond"); setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { value: "ReadableStreamBYOBRequest", configurable: true }); } class ReadableByteStreamController { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the current BYOB pull request, or `null` if there isn't one. */ get byobRequest() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("byobRequest"); } return ReadableByteStreamControllerGetBYOBRequest(this); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("desiredSize"); } return ReadableByteStreamControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("close"); } if (this._closeRequested) { throw new TypeError("The stream has already been closed; do not close it again!"); } const state2 = this._controlledReadableByteStream._state; if (state2 !== "readable") { throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be closed`); } ReadableByteStreamControllerClose(this); } enqueue(chunk) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("enqueue"); } assertRequiredArgument(chunk, 1, "enqueue"); if (!ArrayBuffer.isView(chunk)) { throw new TypeError("chunk must be an array buffer view"); } if (chunk.byteLength === 0) { throw new TypeError("chunk must have non-zero byteLength"); } if (chunk.buffer.byteLength === 0) { throw new TypeError(`chunk's buffer must have non-zero byteLength`); } if (this._closeRequested) { throw new TypeError("stream is closed or draining"); } const state2 = this._controlledReadableByteStream._state; if (state2 !== "readable") { throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be enqueued to`); } ReadableByteStreamControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e4 = void 0) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException("error"); } ReadableByteStreamControllerError(this, e4); } /** @internal */ [CancelSteps](reason) { ReadableByteStreamControllerClearPendingPullIntos(this); ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableByteStreamControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableByteStream; if (this._queueTotalSize > 0) { ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); return; } const autoAllocateChunkSize = this._autoAllocateChunkSize; if (autoAllocateChunkSize !== void 0) { let buffer; try { buffer = new ArrayBuffer(autoAllocateChunkSize); } catch (bufferE) { readRequest._errorSteps(bufferE); return; } const pullIntoDescriptor = { buffer, bufferByteLength: autoAllocateChunkSize, byteOffset: 0, byteLength: autoAllocateChunkSize, bytesFilled: 0, minimumFill: 1, elementSize: 1, viewConstructor: Uint8Array, readerType: "default" }; this._pendingPullIntos.push(pullIntoDescriptor); } ReadableStreamAddReadRequest(stream, readRequest); ReadableByteStreamControllerCallPullIfNeeded(this); } /** @internal */ [ReleaseSteps]() { if (this._pendingPullIntos.length > 0) { const firstPullInto = this._pendingPullIntos.peek(); firstPullInto.readerType = "none"; this._pendingPullIntos = new SimpleQueue(); this._pendingPullIntos.push(firstPullInto); } } } Object.defineProperties(ReadableByteStreamController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, byobRequest: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(ReadableByteStreamController.prototype.close, "close"); setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue"); setFunctionName(ReadableByteStreamController.prototype.error, "error"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { value: "ReadableByteStreamController", configurable: true }); } function IsReadableByteStreamController(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_controlledReadableByteStream")) { return false; } return x4 instanceof ReadableByteStreamController; } function IsReadableStreamBYOBRequest(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_associatedReadableByteStreamController")) { return false; } return x4 instanceof ReadableStreamBYOBRequest; } function ReadableByteStreamControllerCallPullIfNeeded(controller) { const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableByteStreamControllerCallPullIfNeeded(controller); } return null; }, (e4) => { ReadableByteStreamControllerError(controller, e4); return null; }); } function ReadableByteStreamControllerClearPendingPullIntos(controller) { ReadableByteStreamControllerInvalidateBYOBRequest(controller); controller._pendingPullIntos = new SimpleQueue(); } function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { let done = false; if (stream._state === "closed") { done = true; } const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); if (pullIntoDescriptor.readerType === "default") { ReadableStreamFulfillReadRequest(stream, filledView, done); } else { ReadableStreamFulfillReadIntoRequest(stream, filledView, done); } } function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { const bytesFilled = pullIntoDescriptor.bytesFilled; const elementSize = pullIntoDescriptor.elementSize; return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); } function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { controller._queue.push({ buffer, byteOffset, byteLength }); controller._queueTotalSize += byteLength; } function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { let clonedChunk; try { clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); } catch (cloneE) { ReadableByteStreamControllerError(controller, cloneE); throw cloneE; } ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); } function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { if (firstDescriptor.bytesFilled > 0) { ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); } ReadableByteStreamControllerShiftPendingPullInto(controller); } function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; let totalBytesToCopyRemaining = maxBytesToCopy; let ready = false; const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; const maxAlignedBytes = maxBytesFilled - remainderBytes; if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; ready = true; } const queue = controller._queue; while (totalBytesToCopyRemaining > 0) { const headOfQueue = queue.peek(); const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); if (headOfQueue.byteLength === bytesToCopy) { queue.shift(); } else { headOfQueue.byteOffset += bytesToCopy; headOfQueue.byteLength -= bytesToCopy; } controller._queueTotalSize -= bytesToCopy; ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); totalBytesToCopyRemaining -= bytesToCopy; } return ready; } function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { pullIntoDescriptor.bytesFilled += size; } function ReadableByteStreamControllerHandleQueueDrain(controller) { if (controller._queueTotalSize === 0 && controller._closeRequested) { ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(controller._controlledReadableByteStream); } else { ReadableByteStreamControllerCallPullIfNeeded(controller); } } function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { if (controller._byobRequest === null) { return; } controller._byobRequest._associatedReadableByteStreamController = void 0; controller._byobRequest._view = null; controller._byobRequest = null; } function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { while (controller._pendingPullIntos.length > 0) { if (controller._queueTotalSize === 0) { return; } const pullIntoDescriptor = controller._pendingPullIntos.peek(); if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); } } } function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { const reader = controller._controlledReadableByteStream._reader; while (reader._readRequests.length > 0) { if (controller._queueTotalSize === 0) { return; } const readRequest = reader._readRequests.shift(); ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); } } function ReadableByteStreamControllerPullInto(controller, view5, min, readIntoRequest) { const stream = controller._controlledReadableByteStream; const ctor = view5.constructor; const elementSize = arrayBufferViewElementSize(ctor); const { byteOffset, byteLength } = view5; const minimumFill = min * elementSize; let buffer; try { buffer = TransferArrayBuffer(view5.buffer); } catch (e4) { readIntoRequest._errorSteps(e4); return; } const pullIntoDescriptor = { buffer, bufferByteLength: buffer.byteLength, byteOffset, byteLength, bytesFilled: 0, minimumFill, elementSize, viewConstructor: ctor, readerType: "byob" }; if (controller._pendingPullIntos.length > 0) { controller._pendingPullIntos.push(pullIntoDescriptor); ReadableStreamAddReadIntoRequest(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 e4 = new TypeError("Insufficient bytes to fill elements in the given buffer"); ReadableByteStreamControllerError(controller, e4); readIntoRequest._errorSteps(e4); return; } } controller._pendingPullIntos.push(pullIntoDescriptor); ReadableStreamAddReadIntoRequest(stream, readIntoRequest); ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { if (firstDescriptor.readerType === "none") { ReadableByteStreamControllerShiftPendingPullInto(controller); } const stream = controller._controlledReadableByteStream; if (ReadableStreamHasBYOBReader(stream)) { while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); } } } function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); if (pullIntoDescriptor.readerType === "none") { ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); return; } if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { return; } ReadableByteStreamControllerShiftPendingPullInto(controller); const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; if (remainderSize > 0) { const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); } pullIntoDescriptor.bytesFilled -= remainderSize; ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); ReadableByteStreamControllerInvalidateBYOBRequest(controller); const state2 = controller._controlledReadableByteStream._state; if (state2 === "closed") { ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); } else { ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerShiftPendingPullInto(controller) { const descriptor = controller._pendingPullIntos.shift(); return descriptor; } function ReadableByteStreamControllerShouldCallPull(controller) { const stream = controller._controlledReadableByteStream; if (stream._state !== "readable") { return false; } if (controller._closeRequested) { return false; } if (!controller._started) { return false; } if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { return true; } const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableByteStreamControllerClearAlgorithms(controller) { controller._pullAlgorithm = void 0; controller._cancelAlgorithm = void 0; } function ReadableByteStreamControllerClose(controller) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== "readable") { return; } if (controller._queueTotalSize > 0) { controller._closeRequested = true; return; } if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { const e4 = new TypeError("Insufficient bytes to fill elements in the given buffer"); ReadableByteStreamControllerError(controller, e4); throw e4; } } ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(stream); } function ReadableByteStreamControllerEnqueue(controller, chunk) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== "readable") { return; } const { buffer, byteOffset, byteLength } = chunk; if (IsDetachedBuffer(buffer)) { throw new TypeError("chunk's buffer is detached and so cannot be enqueued"); } const transferredBuffer = TransferArrayBuffer(buffer); if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (IsDetachedBuffer(firstPendingPullInto.buffer)) { throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk"); } ReadableByteStreamControllerInvalidateBYOBRequest(controller); firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); if (firstPendingPullInto.readerType === "none") { ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); } } if (ReadableStreamHasDefaultReader(stream)) { ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); if (ReadableStreamGetNumReadRequests(stream) === 0) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } else { if (controller._pendingPullIntos.length > 0) { ReadableByteStreamControllerShiftPendingPullInto(controller); } const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); ReadableStreamFulfillReadRequest(stream, transferredView, false); } } else if (ReadableStreamHasBYOBReader(stream)) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } else { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerError(controller, e4) { const stream = controller._controlledReadableByteStream; if (stream._state !== "readable") { return; } ReadableByteStreamControllerClearPendingPullIntos(controller); ResetQueue(controller); ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamError(stream, e4); } function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { const entry = controller._queue.shift(); controller._queueTotalSize -= entry.byteLength; ReadableByteStreamControllerHandleQueueDrain(controller); const view5 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); readRequest._chunkSteps(view5); } function ReadableByteStreamControllerGetBYOBRequest(controller) { if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { const firstDescriptor = controller._pendingPullIntos.peek(); const view5 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); SetUpReadableStreamBYOBRequest(byobRequest, controller, view5); controller._byobRequest = byobRequest; } return controller._byobRequest; } function ReadableByteStreamControllerGetDesiredSize(controller) { const state2 = controller._controlledReadableByteStream._state; if (state2 === "errored") { return null; } if (state2 === "closed") { return 0; } return controller._strategyHWM - controller._queueTotalSize; } function ReadableByteStreamControllerRespond(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); const state2 = controller._controlledReadableByteStream._state; if (state2 === "closed") { if (bytesWritten !== 0) { throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); } } else { if (bytesWritten === 0) { throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); } if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { throw new RangeError("bytesWritten out of range"); } } firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); ReadableByteStreamControllerRespondInternal(controller, bytesWritten); } function ReadableByteStreamControllerRespondWithNewView(controller, view5) { const firstDescriptor = controller._pendingPullIntos.peek(); const state2 = controller._controlledReadableByteStream._state; if (state2 === "closed") { if (view5.byteLength !== 0) { throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); } } else { if (view5.byteLength === 0) { throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); } } if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view5.byteOffset) { throw new RangeError("The region specified by view does not match byobRequest"); } if (firstDescriptor.bufferByteLength !== view5.buffer.byteLength) { throw new RangeError("The buffer of view has different capacity than byobRequest"); } if (firstDescriptor.bytesFilled + view5.byteLength > firstDescriptor.byteLength) { throw new RangeError("The region specified by view is larger than byobRequest"); } const viewByteLength = view5.byteLength; firstDescriptor.buffer = TransferArrayBuffer(view5.buffer); ReadableByteStreamControllerRespondInternal(controller, viewByteLength); } function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { controller._controlledReadableByteStream = stream; controller._pullAgain = false; controller._pulling = false; controller._byobRequest = null; controller._queue = controller._queueTotalSize = void 0; ResetQueue(controller); controller._closeRequested = false; controller._started = false; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; controller._autoAllocateChunkSize = autoAllocateChunkSize; controller._pendingPullIntos = new SimpleQueue(); stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableByteStreamControllerCallPullIfNeeded(controller); return null; }, (r4) => { ReadableByteStreamControllerError(controller, r4); return null; }); } function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { const controller = Object.create(ReadableByteStreamController.prototype); let startAlgorithm; let pullAlgorithm; let cancelAlgorithm; if (underlyingByteSource.start !== void 0) { startAlgorithm = () => underlyingByteSource.start(controller); } else { startAlgorithm = () => void 0; } if (underlyingByteSource.pull !== void 0) { pullAlgorithm = () => underlyingByteSource.pull(controller); } else { pullAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingByteSource.cancel !== void 0) { cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(void 0); } const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; if (autoAllocateChunkSize === 0) { throw new TypeError("autoAllocateChunkSize must be greater than 0"); } SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); } function SetUpReadableStreamBYOBRequest(request, controller, view5) { request._associatedReadableByteStreamController = controller; request._view = view5; } function byobRequestBrandCheckException(name) { return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); } function byteStreamControllerBrandCheckException(name) { return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); } function convertReaderOptions(options, context) { assertDictionary(options, context); const mode = options === null || options === void 0 ? void 0 : options.mode; return { mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) }; } function convertReadableStreamReaderMode(mode, context) { mode = `${mode}`; if (mode !== "byob") { throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); } return mode; } function convertByobReadOptions(options, context) { var _a3; assertDictionary(options, context); const min = (_a3 = options === null || options === void 0 ? void 0 : options.min) !== null && _a3 !== void 0 ? _a3 : 1; return { min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) }; } function AcquireReadableStreamBYOBReader(stream) { return new ReadableStreamBYOBReader(stream); } function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { stream._reader._readIntoRequests.push(readIntoRequest); } function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { const reader = stream._reader; const readIntoRequest = reader._readIntoRequests.shift(); if (done) { readIntoRequest._closeSteps(chunk); } else { readIntoRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadIntoRequests(stream) { return stream._reader._readIntoRequests.length; } function ReadableStreamHasBYOBReader(stream) { const reader = stream._reader; if (reader === void 0) { return false; } if (!IsReadableStreamBYOBReader(reader)) { return false; } return true; } class ReadableStreamBYOBReader { constructor(stream) { assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader"); assertReadableStream(stream, "First parameter"); if (IsReadableStreamLocked(stream)) { throw new TypeError("This stream has already been locked for exclusive reading by another reader"); } if (!IsReadableByteStreamController(stream._readableStreamController)) { throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source"); } ReadableStreamReaderGenericInitialize(this, stream); this._readIntoRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException("closed")); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = void 0) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException("cancel")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("cancel")); } return ReadableStreamReaderGenericCancel(this, reason); } read(view5, rawOptions = {}) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException("read")); } if (!ArrayBuffer.isView(view5)) { return promiseRejectedWith(new TypeError("view must be an array buffer view")); } if (view5.byteLength === 0) { return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); } if (view5.buffer.byteLength === 0) { return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); } if (IsDetachedBuffer(view5.buffer)) { return promiseRejectedWith(new TypeError("view's buffer has been detached")); } let options; try { options = convertByobReadOptions(rawOptions, "options"); } catch (e4) { return promiseRejectedWith(e4); } const min = options.min; if (min === 0) { return promiseRejectedWith(new TypeError("options.min must be greater than 0")); } if (!isDataView(view5)) { if (min > view5.length) { return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length")); } } else if (min > view5.byteLength) { return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength")); } if (this._ownerReadableStream === void 0) { return promiseRejectedWith(readerLockException("read from")); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve2, reject) => { resolvePromise = resolve2; rejectPromise = reject; }); const readIntoRequest = { _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), _errorSteps: (e4) => rejectPromise(e4) }; ReadableStreamBYOBReaderRead(this, view5, min, readIntoRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamBYOBReader(this)) { throw byobReaderBrandCheckException("releaseLock"); } if (this._ownerReadableStream === void 0) { return; } ReadableStreamBYOBReaderRelease(this); } } Object.defineProperties(ReadableStreamBYOBReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel"); setFunctionName(ReadableStreamBYOBReader.prototype.read, "read"); setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { value: "ReadableStreamBYOBReader", configurable: true }); } function IsReadableStreamBYOBReader(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_readIntoRequests")) { return false; } return x4 instanceof ReadableStreamBYOBReader; } function ReadableStreamBYOBReaderRead(reader, view5, min, readIntoRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === "errored") { readIntoRequest._errorSteps(stream._storedError); } else { ReadableByteStreamControllerPullInto(stream._readableStreamController, view5, min, readIntoRequest); } } function ReadableStreamBYOBReaderRelease(reader) { ReadableStreamReaderGenericRelease(reader); const e4 = new TypeError("Reader was released"); ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4); } function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4) { const readIntoRequests = reader._readIntoRequests; reader._readIntoRequests = new SimpleQueue(); readIntoRequests.forEach((readIntoRequest) => { readIntoRequest._errorSteps(e4); }); } 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(x4, context) { if (!IsWritableStream(x4)) { 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 (_a3) { return false; } } const supportsAbortController = typeof AbortController === "function"; function createAbortController() { if (supportsAbortController) { return new AbortController(); } return void 0; } class WritableStream { constructor(rawUnderlyingSink = {}, rawStrategy = {}) { if (rawUnderlyingSink === void 0) { rawUnderlyingSink = null; } else { assertObject(rawUnderlyingSink, "First parameter"); } const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); InitializeWritableStream(this); const type = underlyingSink.type; if (type !== void 0) { throw new RangeError("Invalid type is specified"); } const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); } /** * Returns whether or not the writable stream is locked to a writer. */ get locked() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2("locked"); } return IsWritableStreamLocked(this); } /** * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort * mechanism of the underlying sink. * * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel * the stream) if the stream is currently locked. */ abort(reason = void 0) { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2("abort")); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); } return WritableStreamAbort(this, reason); } /** * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its * close behavior. During this time any further attempts to write will fail (without erroring the stream). * * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. */ close() { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2("close")); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); } if (WritableStreamCloseQueuedOrInFlight(this)) { return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); } return WritableStreamClose(this); } /** * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream * is locked, no other writer can be acquired until this one is released. * * This functionality is especially useful for creating abstractions that desire the ability to write to a stream * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at * the same time, which would cause the resulting written data to be unpredictable and probably useless. */ getWriter() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2("getWriter"); } return AcquireWritableStreamDefaultWriter(this); } } Object.defineProperties(WritableStream.prototype, { abort: { enumerable: true }, close: { enumerable: true }, getWriter: { enumerable: true }, locked: { enumerable: true } }); setFunctionName(WritableStream.prototype.abort, "abort"); setFunctionName(WritableStream.prototype.close, "close"); setFunctionName(WritableStream.prototype.getWriter, "getWriter"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { value: "WritableStream", configurable: true }); } function AcquireWritableStreamDefaultWriter(stream) { return new WritableStreamDefaultWriter(stream); } function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(WritableStream.prototype); InitializeWritableStream(stream); const controller = Object.create(WritableStreamDefaultController.prototype); SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); return stream; } function InitializeWritableStream(stream) { stream._state = "writable"; stream._storedError = void 0; stream._writer = void 0; stream._writableStreamController = void 0; stream._writeRequests = new SimpleQueue(); stream._inFlightWriteRequest = void 0; stream._closeRequest = void 0; stream._inFlightCloseRequest = void 0; stream._pendingAbortRequest = void 0; stream._backpressure = false; } function IsWritableStream(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_writableStreamController")) { return false; } return x4 instanceof WritableStream; } function IsWritableStreamLocked(stream) { if (stream._writer === void 0) { return false; } return true; } function WritableStreamAbort(stream, reason) { var _a3; if (stream._state === "closed" || stream._state === "errored") { return promiseResolvedWith(void 0); } stream._writableStreamController._abortReason = reason; (_a3 = stream._writableStreamController._abortController) === null || _a3 === void 0 ? void 0 : _a3.abort(reason); const state2 = stream._state; if (state2 === "closed" || state2 === "errored") { return promiseResolvedWith(void 0); } if (stream._pendingAbortRequest !== void 0) { return stream._pendingAbortRequest._promise; } let wasAlreadyErroring = false; if (state2 === "erroring") { wasAlreadyErroring = true; reason = void 0; } const promise = newPromise((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 state2 = stream._state; if (state2 === "closed" || state2 === "errored") { return promiseRejectedWith(new TypeError(`The stream (in ${state2} state) is not in the writable state and cannot be closed`)); } const promise = newPromise((resolve2, reject) => { const closeRequest = { _resolve: resolve2, _reject: reject }; stream._closeRequest = closeRequest; }); const writer = stream._writer; if (writer !== void 0 && stream._backpressure && state2 === "writable") { defaultWriterReadyPromiseResolve(writer); } WritableStreamDefaultControllerClose(stream._writableStreamController); return promise; } function WritableStreamAddWriteRequest(stream) { const promise = newPromise((resolve2, reject) => { const writeRequest = { _resolve: resolve2, _reject: reject }; stream._writeRequests.push(writeRequest); }); return promise; } function WritableStreamDealWithRejection(stream, error2) { const state2 = stream._state; if (state2 === "writable") { WritableStreamStartErroring(stream, error2); return; } WritableStreamFinishErroring(stream); } function WritableStreamStartErroring(stream, reason) { const controller = stream._writableStreamController; stream._state = "erroring"; stream._storedError = reason; const writer = stream._writer; if (writer !== void 0) { WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); } if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { WritableStreamFinishErroring(stream); } } function WritableStreamFinishErroring(stream) { stream._state = "errored"; stream._writableStreamController[ErrorSteps](); const storedError = stream._storedError; stream._writeRequests.forEach((writeRequest) => { writeRequest._reject(storedError); }); stream._writeRequests = new SimpleQueue(); if (stream._pendingAbortRequest === void 0) { WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const abortRequest = stream._pendingAbortRequest; stream._pendingAbortRequest = void 0; if (abortRequest._wasAlreadyErroring) { abortRequest._reject(storedError); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); uponPromise(promise, () => { abortRequest._resolve(); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return null; }, (reason) => { abortRequest._reject(reason); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return null; }); } function WritableStreamFinishInFlightWrite(stream) { stream._inFlightWriteRequest._resolve(void 0); stream._inFlightWriteRequest = void 0; } function WritableStreamFinishInFlightWriteWithError(stream, error2) { stream._inFlightWriteRequest._reject(error2); stream._inFlightWriteRequest = void 0; WritableStreamDealWithRejection(stream, error2); } function WritableStreamFinishInFlightClose(stream) { stream._inFlightCloseRequest._resolve(void 0); stream._inFlightCloseRequest = void 0; const state2 = stream._state; if (state2 === "erroring") { stream._storedError = void 0; if (stream._pendingAbortRequest !== void 0) { stream._pendingAbortRequest._resolve(); stream._pendingAbortRequest = void 0; } } stream._state = "closed"; const writer = stream._writer; if (writer !== void 0) { defaultWriterClosedPromiseResolve(writer); } } function WritableStreamFinishInFlightCloseWithError(stream, error2) { stream._inFlightCloseRequest._reject(error2); stream._inFlightCloseRequest = void 0; if (stream._pendingAbortRequest !== void 0) { stream._pendingAbortRequest._reject(error2); stream._pendingAbortRequest = void 0; } WritableStreamDealWithRejection(stream, error2); } function WritableStreamCloseQueuedOrInFlight(stream) { if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) { return false; } return true; } function WritableStreamHasOperationMarkedInFlight(stream) { if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) { return false; } return true; } function WritableStreamMarkCloseRequestInFlight(stream) { stream._inFlightCloseRequest = stream._closeRequest; stream._closeRequest = void 0; } function WritableStreamMarkFirstWriteRequestInFlight(stream) { stream._inFlightWriteRequest = stream._writeRequests.shift(); } function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { if (stream._closeRequest !== void 0) { stream._closeRequest._reject(stream._storedError); stream._closeRequest = void 0; } const writer = stream._writer; if (writer !== void 0) { defaultWriterClosedPromiseReject(writer, stream._storedError); } } function WritableStreamUpdateBackpressure(stream, backpressure) { const writer = stream._writer; if (writer !== void 0 && backpressure !== stream._backpressure) { if (backpressure) { defaultWriterReadyPromiseReset(writer); } else { defaultWriterReadyPromiseResolve(writer); } } stream._backpressure = backpressure; } class WritableStreamDefaultWriter { constructor(stream) { assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter"); assertWritableStream(stream, "First parameter"); if (IsWritableStreamLocked(stream)) { throw new TypeError("This stream has already been locked for exclusive writing by another writer"); } this._ownerWritableStream = stream; stream._writer = this; const state2 = stream._state; if (state2 === "writable") { if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { defaultWriterReadyPromiseInitialize(this); } else { defaultWriterReadyPromiseInitializeAsResolved(this); } defaultWriterClosedPromiseInitialize(this); } else if (state2 === "erroring") { defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); defaultWriterClosedPromiseInitialize(this); } else if (state2 === "closed") { defaultWriterReadyPromiseInitializeAsResolved(this); defaultWriterClosedPromiseInitializeAsResolved(this); } else { const storedError = stream._storedError; defaultWriterReadyPromiseInitializeAsRejected(this, storedError); defaultWriterClosedPromiseInitializeAsRejected(this, storedError); } } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the writer’s lock is released before the stream finishes closing. */ get closed() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("closed")); } return this._closedPromise; } /** * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. * A producer can use this information to determine the right amount of data to write. * * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when * the writer’s lock is released. */ get desiredSize() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException("desiredSize"); } if (this._ownerWritableStream === void 0) { throw defaultWriterLockException("desiredSize"); } return WritableStreamDefaultWriterGetDesiredSize(this); } /** * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips * back to zero or below, the getter will return a new promise that stays pending until the next transition. * * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become * rejected. */ get ready() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("ready")); } return this._readyPromise; } /** * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. */ abort(reason = void 0) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("abort")); } if (this._ownerWritableStream === void 0) { return promiseRejectedWith(defaultWriterLockException("abort")); } return WritableStreamDefaultWriterAbort(this, reason); } /** * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. */ close() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("close")); } const stream = this._ownerWritableStream; if (stream === void 0) { return promiseRejectedWith(defaultWriterLockException("close")); } if (WritableStreamCloseQueuedOrInFlight(stream)) { return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); } return WritableStreamDefaultWriterClose(this); } /** * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from * now on; otherwise, the writer will appear closed. * * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents * other producers from writing in an interleaved manner. */ releaseLock() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException("releaseLock"); } const stream = this._ownerWritableStream; if (stream === void 0) { return; } WritableStreamDefaultWriterRelease(this); } write(chunk = void 0) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException("write")); } if (this._ownerWritableStream === void 0) { return promiseRejectedWith(defaultWriterLockException("write to")); } return WritableStreamDefaultWriterWrite(this, chunk); } } Object.defineProperties(WritableStreamDefaultWriter.prototype, { abort: { enumerable: true }, close: { enumerable: true }, releaseLock: { enumerable: true }, write: { enumerable: true }, closed: { enumerable: true }, desiredSize: { enumerable: true }, ready: { enumerable: true } }); setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort"); setFunctionName(WritableStreamDefaultWriter.prototype.close, "close"); setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock"); setFunctionName(WritableStreamDefaultWriter.prototype.write, "write"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { value: "WritableStreamDefaultWriter", configurable: true }); } function IsWritableStreamDefaultWriter(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_ownerWritableStream")) { return false; } return x4 instanceof WritableStreamDefaultWriter; } function WritableStreamDefaultWriterAbort(writer, reason) { const stream = writer._ownerWritableStream; return WritableStreamAbort(stream, reason); } function WritableStreamDefaultWriterClose(writer) { const stream = writer._ownerWritableStream; return WritableStreamClose(stream); } function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { const stream = writer._ownerWritableStream; const state2 = stream._state; if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") { return promiseResolvedWith(void 0); } if (state2 === "errored") { return promiseRejectedWith(stream._storedError); } return WritableStreamDefaultWriterClose(writer); } function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error2) { if (writer._closedPromiseState === "pending") { defaultWriterClosedPromiseReject(writer, error2); } else { defaultWriterClosedPromiseResetToRejected(writer, error2); } } function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error2) { if (writer._readyPromiseState === "pending") { defaultWriterReadyPromiseReject(writer, error2); } else { defaultWriterReadyPromiseResetToRejected(writer, error2); } } function WritableStreamDefaultWriterGetDesiredSize(writer) { const stream = writer._ownerWritableStream; const state2 = stream._state; if (state2 === "errored" || state2 === "erroring") { return null; } if (state2 === "closed") { return 0; } return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); } function WritableStreamDefaultWriterRelease(writer) { const stream = writer._ownerWritableStream; const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); stream._writer = void 0; writer._ownerWritableStream = void 0; } function WritableStreamDefaultWriterWrite(writer, chunk) { const stream = writer._ownerWritableStream; const controller = stream._writableStreamController; const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); if (stream !== writer._ownerWritableStream) { return promiseRejectedWith(defaultWriterLockException("write to")); } const state2 = stream._state; if (state2 === "errored") { return promiseRejectedWith(stream._storedError); } if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") { return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); } if (state2 === "erroring") { return promiseRejectedWith(stream._storedError); } const promise = WritableStreamAddWriteRequest(stream); WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); return promise; } const closeSentinel = {}; class WritableStreamDefaultController { constructor() { throw new TypeError("Illegal constructor"); } /** * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. * * @deprecated * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. */ get abortReason() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2("abortReason"); } return this._abortReason; } /** * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. */ get signal() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2("signal"); } if (this._abortController === void 0) { throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); } return this._abortController.signal; } /** * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. * * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the * normal lifecycle of interactions with the underlying sink. */ error(e4 = void 0) { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2("error"); } const state2 = this._controlledWritableStream._state; if (state2 !== "writable") { return; } WritableStreamDefaultControllerError(this, e4); } /** @internal */ [AbortSteps](reason) { const result = this._abortAlgorithm(reason); WritableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [ErrorSteps]() { ResetQueue(this); } } Object.defineProperties(WritableStreamDefaultController.prototype, { abortReason: { enumerable: true }, signal: { enumerable: true }, error: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { value: "WritableStreamDefaultController", configurable: true }); } function IsWritableStreamDefaultController(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_controlledWritableStream")) { return false; } return x4 instanceof WritableStreamDefaultController; } function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledWritableStream = stream; stream._writableStreamController = controller; controller._queue = void 0; controller._queueTotalSize = void 0; ResetQueue(controller); controller._abortReason = void 0; controller._abortController = createAbortController(); controller._started = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._writeAlgorithm = writeAlgorithm; controller._closeAlgorithm = closeAlgorithm; controller._abortAlgorithm = abortAlgorithm; const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); const startResult = startAlgorithm(); const startPromise = promiseResolvedWith(startResult); uponPromise(startPromise, () => { controller._started = true; WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); return null; }, (r4) => { controller._started = true; WritableStreamDealWithRejection(stream, r4); return null; }); } function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { const controller = Object.create(WritableStreamDefaultController.prototype); let startAlgorithm; let writeAlgorithm; let closeAlgorithm; let abortAlgorithm; if (underlyingSink.start !== void 0) { startAlgorithm = () => underlyingSink.start(controller); } else { startAlgorithm = () => void 0; } if (underlyingSink.write !== void 0) { writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); } else { writeAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingSink.close !== void 0) { closeAlgorithm = () => underlyingSink.close(); } else { closeAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingSink.abort !== void 0) { abortAlgorithm = (reason) => underlyingSink.abort(reason); } else { abortAlgorithm = () => promiseResolvedWith(void 0); } SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); } function WritableStreamDefaultControllerClearAlgorithms(controller) { controller._writeAlgorithm = void 0; controller._closeAlgorithm = void 0; controller._abortAlgorithm = void 0; controller._strategySizeAlgorithm = void 0; } function WritableStreamDefaultControllerClose(controller) { EnqueueValueWithSize(controller, closeSentinel, 0); WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { try { return controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); return 1; } } function WritableStreamDefaultControllerGetDesiredSize(controller) { return controller._strategyHWM - controller._queueTotalSize; } function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); return; } const stream = controller._controlledWritableStream; if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { const stream = controller._controlledWritableStream; if (!controller._started) { return; } if (stream._inFlightWriteRequest !== void 0) { return; } const state2 = stream._state; if (state2 === "erroring") { WritableStreamFinishErroring(stream); return; } if (controller._queue.length === 0) { return; } const value = PeekQueueValue(controller); if (value === closeSentinel) { WritableStreamDefaultControllerProcessClose(controller); } else { WritableStreamDefaultControllerProcessWrite(controller, value); } } function WritableStreamDefaultControllerErrorIfNeeded(controller, error2) { if (controller._controlledWritableStream._state === "writable") { WritableStreamDefaultControllerError(controller, error2); } } function WritableStreamDefaultControllerProcessClose(controller) { const stream = controller._controlledWritableStream; WritableStreamMarkCloseRequestInFlight(stream); DequeueValue(controller); const sinkClosePromise = controller._closeAlgorithm(); WritableStreamDefaultControllerClearAlgorithms(controller); uponPromise(sinkClosePromise, () => { WritableStreamFinishInFlightClose(stream); return null; }, (reason) => { WritableStreamFinishInFlightCloseWithError(stream, reason); return null; }); } function WritableStreamDefaultControllerProcessWrite(controller, chunk) { const stream = controller._controlledWritableStream; WritableStreamMarkFirstWriteRequestInFlight(stream); const sinkWritePromise = controller._writeAlgorithm(chunk); uponPromise(sinkWritePromise, () => { WritableStreamFinishInFlightWrite(stream); const state2 = stream._state; DequeueValue(controller); if (!WritableStreamCloseQueuedOrInFlight(stream) && state2 === "writable") { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); return null; }, (reason) => { if (stream._state === "writable") { WritableStreamDefaultControllerClearAlgorithms(controller); } WritableStreamFinishInFlightWriteWithError(stream, reason); return null; }); } function WritableStreamDefaultControllerGetBackpressure(controller) { const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); return desiredSize <= 0; } function WritableStreamDefaultControllerError(controller, error2) { const stream = controller._controlledWritableStream; WritableStreamDefaultControllerClearAlgorithms(controller); WritableStreamStartErroring(stream, error2); } function streamBrandCheckException$2(name) { return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); } function defaultControllerBrandCheckException$2(name) { return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); } function defaultWriterBrandCheckException(name) { return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); } function defaultWriterLockException(name) { return new TypeError("Cannot " + name + " a stream using a released writer"); } function defaultWriterClosedPromiseInitialize(writer) { writer._closedPromise = newPromise((resolve2, reject) => { writer._closedPromise_resolve = resolve2; writer._closedPromise_reject = reject; writer._closedPromiseState = "pending"; }); } function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseReject(writer, reason); } function defaultWriterClosedPromiseInitializeAsResolved(writer) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseResolve(writer); } function defaultWriterClosedPromiseReject(writer, reason) { if (writer._closedPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(writer._closedPromise); writer._closedPromise_reject(reason); writer._closedPromise_resolve = void 0; writer._closedPromise_reject = void 0; writer._closedPromiseState = "rejected"; } function defaultWriterClosedPromiseResetToRejected(writer, reason) { defaultWriterClosedPromiseInitializeAsRejected(writer, reason); } function defaultWriterClosedPromiseResolve(writer) { if (writer._closedPromise_resolve === void 0) { return; } writer._closedPromise_resolve(void 0); writer._closedPromise_resolve = void 0; writer._closedPromise_reject = void 0; writer._closedPromiseState = "resolved"; } function defaultWriterReadyPromiseInitialize(writer) { writer._readyPromise = newPromise((resolve2, reject) => { writer._readyPromise_resolve = resolve2; writer._readyPromise_reject = reject; }); writer._readyPromiseState = "pending"; } function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseReject(writer, reason); } function defaultWriterReadyPromiseInitializeAsResolved(writer) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseResolve(writer); } function defaultWriterReadyPromiseReject(writer, reason) { if (writer._readyPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(writer._readyPromise); writer._readyPromise_reject(reason); writer._readyPromise_resolve = void 0; writer._readyPromise_reject = void 0; writer._readyPromiseState = "rejected"; } function defaultWriterReadyPromiseReset(writer) { defaultWriterReadyPromiseInitialize(writer); } function defaultWriterReadyPromiseResetToRejected(writer, reason) { defaultWriterReadyPromiseInitializeAsRejected(writer, reason); } function defaultWriterReadyPromiseResolve(writer) { if (writer._readyPromise_resolve === void 0) { return; } writer._readyPromise_resolve(void 0); writer._readyPromise_resolve = void 0; writer._readyPromise_reject = void 0; writer._readyPromiseState = "fulfilled"; } function getGlobals() { if (typeof globalThis !== "undefined") { return globalThis; } else if (typeof self !== "undefined") { return self; } else if (typeof global !== "undefined") { return global; } return void 0; } const globals = getGlobals(); function isDOMExceptionConstructor(ctor) { if (!(typeof ctor === "function" || typeof ctor === "object")) { return false; } if (ctor.name !== "DOMException") { return false; } try { new ctor(); return true; } catch (_a3) { return false; } } function getFromGlobal() { const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; return isDOMExceptionConstructor(ctor) ? ctor : void 0; } function createPolyfill() { const ctor = function DOMException3(message, name) { this.message = message || ""; this.name = name || "Error"; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } }; setFunctionName(ctor, "DOMException"); ctor.prototype = Object.create(Error.prototype); Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); return ctor; } const DOMException2 = getFromGlobal() || createPolyfill(); function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { const reader = AcquireReadableStreamDefaultReader(source); const writer = AcquireWritableStreamDefaultWriter(dest); source._disturbed = true; let shuttingDown = false; let currentWrite = promiseResolvedWith(void 0); return newPromise((resolve2, reject) => { let abortAlgorithm; if (signal !== void 0) { abortAlgorithm = () => { const error2 = signal.reason !== void 0 ? signal.reason : new DOMException2("Aborted", "AbortError"); const actions = []; if (!preventAbort) { actions.push(() => { if (dest._state === "writable") { return WritableStreamAbort(dest, error2); } return promiseResolvedWith(void 0); }); } if (!preventCancel) { actions.push(() => { if (source._state === "readable") { return ReadableStreamCancel(source, error2); } return promiseResolvedWith(void 0); }); } shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error2); }; if (signal.aborted) { abortAlgorithm(); return; } signal.addEventListener("abort", abortAlgorithm); } function pipeLoop() { return newPromise((resolveLoop, rejectLoop) => { function next(done) { if (done) { resolveLoop(); } else { PerformPromiseThen(pipeStep(), next, rejectLoop); } } next(false); }); } function pipeStep() { if (shuttingDown) { return promiseResolvedWith(true); } return PerformPromiseThen(writer._readyPromise, () => { return newPromise((resolveRead, rejectRead) => { ReadableStreamDefaultReaderRead(reader, { _chunkSteps: (chunk) => { currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2); resolveRead(false); }, _closeSteps: () => resolveRead(true), _errorSteps: rejectRead }); }); }); } isOrBecomesErrored(source, reader._closedPromise, (storedError) => { if (!preventAbort) { shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); } else { shutdown(true, storedError); } return null; }); isOrBecomesErrored(dest, writer._closedPromise, (storedError) => { if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); } else { shutdown(true, storedError); } return null; }); isOrBecomesClosed(source, reader._closedPromise, () => { if (!preventClose) { shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); } else { shutdown(); } return null; }); if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); } else { shutdown(true, destClosed); } } setPromiseIsHandledToTrue(pipeLoop()); function waitForWritesToFinish() { const oldCurrentWrite = currentWrite; return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0); } function isOrBecomesErrored(stream, promise, action) { if (stream._state === "errored") { action(stream._storedError); } else { uponRejection(promise, action); } } function isOrBecomesClosed(stream, promise, action) { if (stream._state === "closed") { action(); } else { uponFulfillment(promise, action); } } function shutdownWithAction(action, originalIsError, originalError) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), doTheRest); } else { doTheRest(); } function doTheRest() { uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError)); return null; } } function shutdown(isError, error2) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error2)); } else { finalize(isError, error2); } } function finalize(isError, error2) { WritableStreamDefaultWriterRelease(writer); ReadableStreamReaderGenericRelease(reader); if (signal !== void 0) { signal.removeEventListener("abort", abortAlgorithm); } if (isError) { reject(error2); } else { resolve2(void 0); } return null; } }); } class ReadableStreamDefaultController { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("desiredSize"); } return ReadableStreamDefaultControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("close"); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError("The stream is not in a state that permits close"); } ReadableStreamDefaultControllerClose(this); } enqueue(chunk = void 0) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("enqueue"); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError("The stream is not in a state that permits enqueue"); } return ReadableStreamDefaultControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e4 = void 0) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1("error"); } ReadableStreamDefaultControllerError(this, e4); } /** @internal */ [CancelSteps](reason) { ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableStream; if (this._queue.length > 0) { const chunk = DequeueValue(this); if (this._closeRequested && this._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(this); ReadableStreamClose(stream); } else { ReadableStreamDefaultControllerCallPullIfNeeded(this); } readRequest._chunkSteps(chunk); } else { ReadableStreamAddReadRequest(stream, readRequest); ReadableStreamDefaultControllerCallPullIfNeeded(this); } } /** @internal */ [ReleaseSteps]() { } } Object.defineProperties(ReadableStreamDefaultController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(ReadableStreamDefaultController.prototype.close, "close"); setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue"); setFunctionName(ReadableStreamDefaultController.prototype.error, "error"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { value: "ReadableStreamDefaultController", configurable: true }); } function IsReadableStreamDefaultController(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_controlledReadableStream")) { return false; } return x4 instanceof ReadableStreamDefaultController; } function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableStreamDefaultControllerCallPullIfNeeded(controller); } return null; }, (e4) => { ReadableStreamDefaultControllerError(controller, e4); return null; }); } function ReadableStreamDefaultControllerShouldCallPull(controller) { const stream = controller._controlledReadableStream; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return false; } if (!controller._started) { return false; } if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableStreamDefaultControllerClearAlgorithms(controller) { controller._pullAlgorithm = void 0; controller._cancelAlgorithm = void 0; controller._strategySizeAlgorithm = void 0; } function ReadableStreamDefaultControllerClose(controller) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; controller._closeRequested = true; if (controller._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamClose(stream); } } function ReadableStreamDefaultControllerEnqueue(controller, chunk) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { ReadableStreamFulfillReadRequest(stream, chunk, false); } else { let chunkSize; try { chunkSize = controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { ReadableStreamDefaultControllerError(controller, chunkSizeE); throw chunkSizeE; } try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { ReadableStreamDefaultControllerError(controller, enqueueE); throw enqueueE; } } ReadableStreamDefaultControllerCallPullIfNeeded(controller); } function ReadableStreamDefaultControllerError(controller, e4) { const stream = controller._controlledReadableStream; if (stream._state !== "readable") { return; } ResetQueue(controller); ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamError(stream, e4); } function ReadableStreamDefaultControllerGetDesiredSize(controller) { const state2 = controller._controlledReadableStream._state; if (state2 === "errored") { return null; } if (state2 === "closed") { return 0; } return controller._strategyHWM - controller._queueTotalSize; } function ReadableStreamDefaultControllerHasBackpressure(controller) { if (ReadableStreamDefaultControllerShouldCallPull(controller)) { return false; } return true; } function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { const state2 = controller._controlledReadableStream._state; if (!controller._closeRequested && state2 === "readable") { return true; } return false; } function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledReadableStream = stream; controller._queue = void 0; controller._queueTotalSize = void 0; ResetQueue(controller); controller._started = false; controller._closeRequested = false; controller._pullAgain = false; controller._pulling = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableStreamDefaultControllerCallPullIfNeeded(controller); return null; }, (r4) => { ReadableStreamDefaultControllerError(controller, r4); return null; }); } function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { const controller = Object.create(ReadableStreamDefaultController.prototype); let startAlgorithm; let pullAlgorithm; let cancelAlgorithm; if (underlyingSource.start !== void 0) { startAlgorithm = () => underlyingSource.start(controller); } else { startAlgorithm = () => void 0; } if (underlyingSource.pull !== void 0) { pullAlgorithm = () => underlyingSource.pull(controller); } else { pullAlgorithm = () => promiseResolvedWith(void 0); } if (underlyingSource.cancel !== void 0) { cancelAlgorithm = (reason) => underlyingSource.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(void 0); } SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); } function defaultControllerBrandCheckException$1(name) { return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); } function ReadableStreamTee(stream, cloneForBranch2) { if (IsReadableByteStreamController(stream._readableStreamController)) { return ReadableByteStreamTee(stream); } return ReadableStreamDefaultTee(stream); } function ReadableStreamDefaultTee(stream, cloneForBranch2) { const reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgain = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise((resolve2) => { resolveCancelPromise = resolve2; }); function pullAlgorithm() { if (reading) { readAgain = true; return promiseResolvedWith(void 0); } reading = true; const readRequest = { _chunkSteps: (chunk) => { _queueMicrotask(() => { readAgain = false; const chunk1 = chunk; const chunk2 = chunk; if (!canceled1) { ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgain) { pullAlgorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableStreamDefaultControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableStreamDefaultControllerClose(branch2._readableStreamController); } if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promiseResolvedWith(void 0); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { } branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); uponRejection(reader._closedPromise, (r4) => { ReadableStreamDefaultControllerError(branch1._readableStreamController, r4); ReadableStreamDefaultControllerError(branch2._readableStreamController, r4); if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } return null; }); return [branch1, branch2]; } function ReadableByteStreamTee(stream) { let reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgainForBranch1 = false; let readAgainForBranch2 = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise((resolve2) => { resolveCancelPromise = resolve2; }); function forwardReaderError(thisReader) { uponRejection(thisReader._closedPromise, (r4) => { if (thisReader !== reader) { return null; } ReadableByteStreamControllerError(branch1._readableStreamController, r4); ReadableByteStreamControllerError(branch2._readableStreamController, r4); if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } return null; }); } function pullWithDefaultReader() { if (IsReadableStreamBYOBReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamDefaultReader(stream); forwardReaderError(reader); } const readRequest = { _chunkSteps: (chunk) => { _queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const chunk1 = chunk; let chunk2 = chunk; if (!canceled1 && !canceled2) { try { chunk2 = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } } if (!canceled1) { ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableByteStreamControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableByteStreamControllerClose(branch2._readableStreamController); } if (branch1._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); } if (branch2._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); } if (!canceled1 || !canceled2) { resolveCancelPromise(void 0); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); } function pullWithBYOBReader(view5, forBranch2) { if (IsReadableStreamDefaultReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamBYOBReader(stream); forwardReaderError(reader); } const byobBranch = forBranch2 ? branch2 : branch1; const otherBranch = forBranch2 ? branch1 : branch2; const readIntoRequest = { _chunkSteps: (chunk) => { _queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!otherCanceled) { let clonedChunk; try { clonedChunk = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); } else if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: (chunk) => { reading = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!byobCanceled) { ReadableByteStreamControllerClose(byobBranch._readableStreamController); } if (!otherCanceled) { ReadableByteStreamControllerClose(otherBranch._readableStreamController); } if (chunk !== void 0) { if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); } } if (!byobCanceled || !otherCanceled) { resolveCancelPromise(void 0); } }, _errorSteps: () => { reading = false; } }; ReadableStreamBYOBReaderRead(reader, view5, 1, readIntoRequest); } function pull1Algorithm() { if (reading) { readAgainForBranch1 = true; return promiseResolvedWith(void 0); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, false); } return promiseResolvedWith(void 0); } function pull2Algorithm() { if (reading) { readAgainForBranch2 = true; return promiseResolvedWith(void 0); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, true); } return promiseResolvedWith(void 0); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { return; } branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); forwardReaderError(reader); return [branch1, branch2]; } function isReadableStreamLike(stream) { return typeIsObject(stream) && typeof stream.getReader !== "undefined"; } function ReadableStreamFrom(source) { if (isReadableStreamLike(source)) { return ReadableStreamFromDefaultReader(source.getReader()); } return ReadableStreamFromIterable(source); } function ReadableStreamFromIterable(asyncIterable) { let stream; const iteratorRecord = GetIterator(asyncIterable, "async"); const startAlgorithm = noop2; function pullAlgorithm() { let nextResult; try { nextResult = IteratorNext(iteratorRecord); } catch (e4) { return promiseRejectedWith(e4); } const nextPromise = promiseResolvedWith(nextResult); return transformPromiseWith(nextPromise, (iterResult) => { if (!typeIsObject(iterResult)) { throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object"); } const done = IteratorComplete(iterResult); if (done) { ReadableStreamDefaultControllerClose(stream._readableStreamController); } else { const value = IteratorValue(iterResult); ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); } }); } function cancelAlgorithm(reason) { const iterator = iteratorRecord.iterator; let returnMethod; try { returnMethod = GetMethod(iterator, "return"); } catch (e4) { return promiseRejectedWith(e4); } if (returnMethod === void 0) { return promiseResolvedWith(void 0); } let returnResult; try { returnResult = reflectCall(returnMethod, iterator, [reason]); } catch (e4) { return promiseRejectedWith(e4); } const returnPromise = promiseResolvedWith(returnResult); return transformPromiseWith(returnPromise, (iterResult) => { if (!typeIsObject(iterResult)) { throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object"); } return void 0; }); } stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); return stream; } function ReadableStreamFromDefaultReader(reader) { let stream; const startAlgorithm = noop2; function pullAlgorithm() { let readPromise; try { readPromise = reader.read(); } catch (e4) { return promiseRejectedWith(e4); } return transformPromiseWith(readPromise, (readResult) => { if (!typeIsObject(readResult)) { throw new TypeError("The promise returned by the reader.read() method must fulfill with an object"); } if (readResult.done) { ReadableStreamDefaultControllerClose(stream._readableStreamController); } else { const value = readResult.value; ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); } }); } function cancelAlgorithm(reason) { try { return promiseResolvedWith(reader.cancel(reason)); } catch (e4) { return promiseRejectedWith(e4); } } stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); return stream; } function convertUnderlyingDefaultOrByteSource(source, context) { assertDictionary(source, context); const original = source; const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; const cancel = original === null || original === void 0 ? void 0 : original.cancel; const 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 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 (e4) { return promiseRejectedWith(e4); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); } if (IsWritableStreamLocked(destination)) { return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); } return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); } /** * Tees this readable stream, returning a two-element array containing the two resulting branches as * new {@link ReadableStream} instances. * * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be * propagated to the stream's underlying source. * * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, * this could allow interference between the two branches. */ tee() { if (!IsReadableStream(this)) { throw streamBrandCheckException$1("tee"); } const branches = ReadableStreamTee(this); return CreateArrayFromList(branches); } values(rawOptions = void 0) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1("values"); } const options = convertIteratorOptions(rawOptions, "First parameter"); return AcquireReadableStreamAsyncIterator(this, options.preventCancel); } [SymbolAsyncIterator](options) { return this.values(options); } /** * Creates a new ReadableStream wrapping the provided iterable or async iterable. * * This can be used to adapt various kinds of objects into a readable stream, * such as an array, an async generator, or a Node.js readable stream. */ static from(asyncIterable) { return ReadableStreamFrom(asyncIterable); } } Object.defineProperties(ReadableStream2, { from: { enumerable: true } }); Object.defineProperties(ReadableStream2.prototype, { cancel: { enumerable: true }, getReader: { enumerable: true }, pipeThrough: { enumerable: true }, pipeTo: { enumerable: true }, tee: { enumerable: true }, values: { enumerable: true }, locked: { enumerable: true } }); setFunctionName(ReadableStream2.from, "from"); setFunctionName(ReadableStream2.prototype.cancel, "cancel"); setFunctionName(ReadableStream2.prototype.getReader, "getReader"); setFunctionName(ReadableStream2.prototype.pipeThrough, "pipeThrough"); setFunctionName(ReadableStream2.prototype.pipeTo, "pipeTo"); setFunctionName(ReadableStream2.prototype.tee, "tee"); setFunctionName(ReadableStream2.prototype.values, "values"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ReadableStream2.prototype, Symbol.toStringTag, { value: "ReadableStream", configurable: true }); } Object.defineProperty(ReadableStream2.prototype, SymbolAsyncIterator, { value: ReadableStream2.prototype.values, writable: true, configurable: true }); function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(ReadableStream2.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableStreamDefaultController.prototype); SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); return stream; } function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { const stream = Object.create(ReadableStream2.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableByteStreamController.prototype); SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0); return stream; } function InitializeReadableStream(stream) { stream._state = "readable"; stream._reader = void 0; stream._storedError = void 0; stream._disturbed = false; } function IsReadableStream(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_readableStreamController")) { return false; } return x4 instanceof ReadableStream2; } function IsReadableStreamLocked(stream) { if (stream._reader === void 0) { return false; } return true; } function ReadableStreamCancel(stream, reason) { stream._disturbed = true; if (stream._state === "closed") { return promiseResolvedWith(void 0); } if (stream._state === "errored") { return promiseRejectedWith(stream._storedError); } ReadableStreamClose(stream); const reader = stream._reader; if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) { const readIntoRequests = reader._readIntoRequests; reader._readIntoRequests = new SimpleQueue(); readIntoRequests.forEach((readIntoRequest) => { readIntoRequest._closeSteps(void 0); }); } const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); return transformPromiseWith(sourceCancelPromise, noop2); } function ReadableStreamClose(stream) { stream._state = "closed"; const reader = stream._reader; if (reader === void 0) { return; } defaultReaderClosedPromiseResolve(reader); if (IsReadableStreamDefaultReader(reader)) { const readRequests = reader._readRequests; reader._readRequests = new SimpleQueue(); readRequests.forEach((readRequest) => { readRequest._closeSteps(); }); } } function ReadableStreamError(stream, e4) { stream._state = "errored"; stream._storedError = e4; const reader = stream._reader; if (reader === void 0) { return; } defaultReaderClosedPromiseReject(reader, e4); if (IsReadableStreamDefaultReader(reader)) { ReadableStreamDefaultReaderErrorReadRequests(reader, e4); } else { ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4); } } function streamBrandCheckException$1(name) { return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); } function convertQueuingStrategyInit(init2, context) { assertDictionary(init2, context); const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark; assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); return { highWaterMark: convertUnrestrictedDouble(highWaterMark) }; } const byteLengthSizeFunction = (chunk) => { return chunk.byteLength; }; setFunctionName(byteLengthSizeFunction, "size"); class ByteLengthQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); options = convertQueuingStrategyInit(options, "First parameter"); this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException("highWaterMark"); } return this._byteLengthQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by returning the value of its `byteLength` property. */ get size() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException("size"); } return byteLengthSizeFunction; } } Object.defineProperties(ByteLengthQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { value: "ByteLengthQueuingStrategy", configurable: true }); } function byteLengthBrandCheckException(name) { return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); } function IsByteLengthQueuingStrategy(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_byteLengthQueuingStrategyHighWaterMark")) { return false; } return x4 instanceof ByteLengthQueuingStrategy; } const countSizeFunction = () => { return 1; }; setFunctionName(countSizeFunction, "size"); class CountQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, "CountQueuingStrategy"); options = convertQueuingStrategyInit(options, "First parameter"); this._countQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException("highWaterMark"); } return this._countQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by always returning 1. * This ensures that the total queue size is a count of the number of chunks in the queue. */ get size() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException("size"); } return countSizeFunction; } } Object.defineProperties(CountQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { value: "CountQueuingStrategy", configurable: true }); } function countBrandCheckException(name) { return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); } function IsCountQueuingStrategy(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_countQueuingStrategyHighWaterMark")) { return false; } return x4 instanceof CountQueuingStrategy; } function convertTransformer(original, context) { assertDictionary(original, context); const cancel = original === null || original === void 0 ? void 0 : original.cancel; const flush = original === null || original === void 0 ? void 0 : original.flush; const readableType = original === null || original === void 0 ? void 0 : original.readableType; const start = original === null || original === void 0 ? void 0 : original.start; const transform = original === null || original === void 0 ? void 0 : original.transform; const writableType = original === null || original === void 0 ? void 0 : original.writableType; return { cancel: cancel === void 0 ? void 0 : convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), flush: 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]); } function convertTransformerCancelCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } class TransformStream2 { constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { if (rawTransformer === void 0) { rawTransformer = null; } const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); const transformer = convertTransformer(rawTransformer, "First parameter"); if (transformer.readableType !== void 0) { throw new RangeError("Invalid readableType specified"); } if (transformer.writableType !== void 0) { throw new RangeError("Invalid writableType specified"); } const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); let startPromise_resolve; const startPromise = newPromise((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(TransformStream2.prototype, { readable: { enumerable: true }, writable: { enumerable: true } }); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, { value: "TransformStream", configurable: true }); } function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { function startAlgorithm() { return startPromise; } function writeAlgorithm(chunk) { return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); } function abortAlgorithm(reason) { return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); } function closeAlgorithm() { return TransformStreamDefaultSinkCloseAlgorithm(stream); } stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); function pullAlgorithm() { return TransformStreamDefaultSourcePullAlgorithm(stream); } function cancelAlgorithm(reason) { return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); } stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); stream._backpressure = void 0; stream._backpressureChangePromise = void 0; stream._backpressureChangePromise_resolve = void 0; TransformStreamSetBackpressure(stream, true); stream._transformStreamController = void 0; } function IsTransformStream(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_transformStreamController")) { return false; } return x4 instanceof TransformStream2; } function TransformStreamError(stream, e4) { ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e4); TransformStreamErrorWritableAndUnblockWrite(stream, e4); } function TransformStreamErrorWritableAndUnblockWrite(stream, e4) { TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e4); TransformStreamUnblockWrite(stream); } function TransformStreamUnblockWrite(stream) { if (stream._backpressure) { TransformStreamSetBackpressure(stream, false); } } function TransformStreamSetBackpressure(stream, backpressure) { if (stream._backpressureChangePromise !== void 0) { stream._backpressureChangePromise_resolve(); } stream._backpressureChangePromise = newPromise((resolve2) => { stream._backpressureChangePromise_resolve = resolve2; }); stream._backpressure = backpressure; } class TransformStreamDefaultController { constructor() { throw new TypeError("Illegal constructor"); } /** * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. */ get desiredSize() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("desiredSize"); } const readableController = this._controlledTransformStream._readable._readableStreamController; return ReadableStreamDefaultControllerGetDesiredSize(readableController); } enqueue(chunk = void 0) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("enqueue"); } TransformStreamDefaultControllerEnqueue(this, chunk); } /** * Errors both the readable side and the writable side of the controlled transform stream, making all future * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. */ error(reason = void 0) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("error"); } TransformStreamDefaultControllerError(this, reason); } /** * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the * transformer only needs to consume a portion of the chunks written to the writable side. */ terminate() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException("terminate"); } TransformStreamDefaultControllerTerminate(this); } } Object.defineProperties(TransformStreamDefaultController.prototype, { enqueue: { enumerable: true }, error: { enumerable: true }, terminate: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue"); setFunctionName(TransformStreamDefaultController.prototype.error, "error"); setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate"); if (typeof Symbol.toStringTag === "symbol") { Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { value: "TransformStreamDefaultController", configurable: true }); } function IsTransformStreamDefaultController(x4) { if (!typeIsObject(x4)) { return false; } if (!Object.prototype.hasOwnProperty.call(x4, "_controlledTransformStream")) { return false; } return x4 instanceof TransformStreamDefaultController; } function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { controller._controlledTransformStream = stream; stream._transformStreamController = controller; controller._transformAlgorithm = transformAlgorithm; controller._flushAlgorithm = flushAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; controller._finishPromise = void 0; controller._finishPromise_resolve = void 0; controller._finishPromise_reject = void 0; } function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { const controller = Object.create(TransformStreamDefaultController.prototype); let transformAlgorithm; let flushAlgorithm; let cancelAlgorithm; if (transformer.transform !== void 0) { transformAlgorithm = (chunk) => transformer.transform(chunk, controller); } else { transformAlgorithm = (chunk) => { try { TransformStreamDefaultControllerEnqueue(controller, chunk); return promiseResolvedWith(void 0); } catch (transformResultE) { return promiseRejectedWith(transformResultE); } }; } if (transformer.flush !== void 0) { flushAlgorithm = () => transformer.flush(controller); } else { flushAlgorithm = () => promiseResolvedWith(void 0); } if (transformer.cancel !== void 0) { cancelAlgorithm = (reason) => transformer.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(void 0); } SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); } function TransformStreamDefaultControllerClearAlgorithms(controller) { controller._transformAlgorithm = void 0; controller._flushAlgorithm = void 0; controller._cancelAlgorithm = void 0; } function TransformStreamDefaultControllerEnqueue(controller, chunk) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { throw new TypeError("Readable side is not in a state that permits enqueue"); } try { ReadableStreamDefaultControllerEnqueue(readableController, chunk); } catch (e4) { TransformStreamErrorWritableAndUnblockWrite(stream, e4); throw stream._readable._storedError; } const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); if (backpressure !== stream._backpressure) { TransformStreamSetBackpressure(stream, true); } } function TransformStreamDefaultControllerError(controller, e4) { TransformStreamError(controller._controlledTransformStream, e4); } function TransformStreamDefaultControllerPerformTransform(controller, chunk) { const transformPromise = controller._transformAlgorithm(chunk); return transformPromiseWith(transformPromise, void 0, (r4) => { TransformStreamError(controller._controlledTransformStream, r4); throw r4; }); } function TransformStreamDefaultControllerTerminate(controller) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; ReadableStreamDefaultControllerClose(readableController); const error2 = new TypeError("TransformStream terminated"); TransformStreamErrorWritableAndUnblockWrite(stream, error2); } function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { const controller = stream._transformStreamController; if (stream._backpressure) { const backpressureChangePromise = stream._backpressureChangePromise; return transformPromiseWith(backpressureChangePromise, () => { const writable = stream._writable; const state2 = writable._state; if (state2 === "erroring") { throw writable._storedError; } return TransformStreamDefaultControllerPerformTransform(controller, chunk); }); } return TransformStreamDefaultControllerPerformTransform(controller, chunk); } function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { const controller = stream._transformStreamController; if (controller._finishPromise !== void 0) { return controller._finishPromise; } const readable = stream._readable; controller._finishPromise = newPromise((resolve2, reject) => { controller._finishPromise_resolve = resolve2; controller._finishPromise_reject = reject; }); const cancelPromise = controller._cancelAlgorithm(reason); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(cancelPromise, () => { if (readable._state === "errored") { defaultControllerFinishPromiseReject(controller, readable._storedError); } else { ReadableStreamDefaultControllerError(readable._readableStreamController, reason); defaultControllerFinishPromiseResolve(controller); } return null; }, (r4) => { ReadableStreamDefaultControllerError(readable._readableStreamController, r4); defaultControllerFinishPromiseReject(controller, r4); return null; }); return controller._finishPromise; } function TransformStreamDefaultSinkCloseAlgorithm(stream) { const controller = stream._transformStreamController; if (controller._finishPromise !== void 0) { return controller._finishPromise; } const readable = stream._readable; controller._finishPromise = newPromise((resolve2, reject) => { controller._finishPromise_resolve = resolve2; controller._finishPromise_reject = reject; }); const flushPromise = controller._flushAlgorithm(); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(flushPromise, () => { if (readable._state === "errored") { defaultControllerFinishPromiseReject(controller, readable._storedError); } else { ReadableStreamDefaultControllerClose(readable._readableStreamController); defaultControllerFinishPromiseResolve(controller); } return null; }, (r4) => { ReadableStreamDefaultControllerError(readable._readableStreamController, r4); defaultControllerFinishPromiseReject(controller, r4); return null; }); return controller._finishPromise; } function TransformStreamDefaultSourcePullAlgorithm(stream) { TransformStreamSetBackpressure(stream, false); return stream._backpressureChangePromise; } function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { const controller = stream._transformStreamController; if (controller._finishPromise !== void 0) { return controller._finishPromise; } const writable = stream._writable; controller._finishPromise = newPromise((resolve2, reject) => { controller._finishPromise_resolve = resolve2; controller._finishPromise_reject = reject; }); const cancelPromise = controller._cancelAlgorithm(reason); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(cancelPromise, () => { if (writable._state === "errored") { defaultControllerFinishPromiseReject(controller, writable._storedError); } else { WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); TransformStreamUnblockWrite(stream); defaultControllerFinishPromiseResolve(controller); } return null; }, (r4) => { WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r4); TransformStreamUnblockWrite(stream); defaultControllerFinishPromiseReject(controller, r4); return null; }); return controller._finishPromise; } function defaultControllerBrandCheckException(name) { return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); } function defaultControllerFinishPromiseResolve(controller) { if (controller._finishPromise_resolve === void 0) { return; } controller._finishPromise_resolve(); controller._finishPromise_resolve = void 0; controller._finishPromise_reject = void 0; } function defaultControllerFinishPromiseReject(controller, reason) { if (controller._finishPromise_reject === void 0) { return; } setPromiseIsHandledToTrue(controller._finishPromise); controller._finishPromise_reject(reason); controller._finishPromise_resolve = void 0; controller._finishPromise_reject = void 0; } function streamBrandCheckException(name) { return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); } exports3.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; exports3.CountQueuingStrategy = CountQueuingStrategy; exports3.ReadableByteStreamController = ReadableByteStreamController; exports3.ReadableStream = ReadableStream2; exports3.ReadableStreamBYOBReader = ReadableStreamBYOBReader; exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; exports3.ReadableStreamDefaultController = ReadableStreamDefaultController; exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader; exports3.TransformStream = TransformStream2; exports3.TransformStreamDefaultController = TransformStreamDefaultController; exports3.WritableStream = WritableStream; exports3.WritableStreamDefaultController = WritableStreamDefaultController; exports3.WritableStreamDefaultWriter = WritableStreamDefaultWriter; }); } }); // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs var require_streams = __commonJS({ "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs"() { 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, b3 = ( /** @type {Blob} */ part ); while (position !== b3.size) { const chunk = b3.slice(position, Math.min(b3.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(F3, B2 = fetch_blob_default) { var b3 = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c3 = [], p3 = `--${b3}\r Content-Disposition: form-data; name="`; F3.forEach((v6, n3) => typeof v6 == "string" ? c3.push(p3 + e(n3) + `"\r \r ${v6.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r `) : c3.push(p3 + e(n3) + `"; filename="${e(v6.name, 1)}"\r Content-Type: ${v6.type || "application/octet-stream"}\r \r `, v6, "\r\n")); c3.push(`--${b3}--`); return new B2(c3, { type: "multipart/form-data; boundary=" + b3 }); } 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 = (a3, b3, c3) => (a3 += "", /^(Blob|File)$/.test(b3 && b3[t]) ? [(c3 = c3 !== void 0 ? c3 + "" : b3[t] == "File" ? b3.name : "blob", a3), b3.name !== c3 || b3[t] == "blob" ? new file_default([b3], c3, b3) : b3] : [a3, b3 + ""]); e = (c3, f5) => (f5 ? c3 : c3.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); x = (n3, a3, e4) => { if (a3.length < e4) { throw new TypeError(`Failed to execute '${n3}' on 'FormData': ${e4} arguments required, but only ${a3.length} present.`); } }; FormData = class FormData2 { #d = []; constructor(...a3) { if (a3.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](o3) { return o3 && typeof o3 === "object" && o3[t] === "FormData" && !m.some((m4) => typeof o3[m4] != "function"); } append(...a3) { x("append", arguments, 2); this.#d.push(f(...a3)); } delete(a3) { x("delete", arguments, 1); a3 += ""; this.#d = this.#d.filter(([b3]) => b3 !== a3); } get(a3) { x("get", arguments, 1); a3 += ""; for (var b3 = this.#d, l3 = b3.length, c3 = 0; c3 < l3; c3++) if (b3[c3][0] === a3) return b3[c3][1]; return null; } getAll(a3, b3) { x("getAll", arguments, 1); b3 = []; a3 += ""; this.#d.forEach((c3) => c3[0] === a3 && b3.push(c3[1])); return b3; } has(a3) { x("has", arguments, 1); a3 += ""; return this.#d.some((b3) => b3[0] === a3); } forEach(a3, b3) { x("forEach", arguments, 1); for (var [c3, d3] of this) a3.call(b3, d3, c3, this); } set(...a3) { x("set", arguments, 2); var b3 = [], c3 = true; a3 = f(...a3); this.#d.forEach((d3) => { d3[0] === a3[0] ? c3 && (c3 = !b3.push(a3)) : b3.push(d3); }); c3 && b3.push(a3); this.#d = b3; } *entries() { yield* this.#d; } *keys() { for (var [a3] of this) yield a3; } *values() { for (var [, a3] of this) yield a3; } }; } }); // ../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, isBlob2, 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"; }; isBlob2 = (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 m4 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); if (!m4) { return; } const match2 = m4[2] || m4[3] || ""; let filename = match2.slice(match2.lastIndexOf("\\") + 1); filename = filename.replace(/%22/g, '"'); filename = filename.replace(/&#(\d{4});/g, (m5, code) => { return String.fromCharCode(code); }); return filename; } async function toFormData(Body2, ct) { if (!/multipart/i.test(ct)) { throw new TypeError("Failed to fetch"); } const m4 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); if (!m4) { throw new TypeError("no or bad content-type header, no multipart boundary"); } const parser = new MultipartParser(m4[1] || m4[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 m5 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); if (m5) { entryName = m5[2] || m5[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 = (c3) => c3 | 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 i4 = 0; i4 < boundary.length; i4++) { ui8a[i4] = boundary.charCodeAt(i4); this.boundaryChars[ui8a[i4]] = true; } this.boundary = ui8a; this.lookbehind = new Uint8Array(this.boundary.length + 8); this.state = S.START_BOUNDARY; } /** * @param {Uint8Array} data */ write(data) { let i4 = 0; const length_ = data.length; let previousIndex = this.index; let { lookbehind, boundary, boundaryChars, index: index6, state: state2, flags } = this; const boundaryLength = this.boundary.length; const boundaryEnd = boundaryLength - 1; const bufferLength = data.length; let c3; let cl; const mark = (name) => { this[name + "Mark"] = i4; }; 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], i4, data); delete this[markSymbol]; } else { callback(name, this[markSymbol], data.length, data); this[markSymbol] = 0; } }; for (i4 = 0; i4 < length_; i4++) { c3 = data[i4]; switch (state2) { case S.START_BOUNDARY: if (index6 === boundary.length - 2) { if (c3 === HYPHEN) { flags |= F.LAST_BOUNDARY; } else if (c3 !== CR) { return; } index6++; break; } else if (index6 - 1 === boundary.length - 2) { if (flags & F.LAST_BOUNDARY && c3 === HYPHEN) { state2 = S.END; flags = 0; } else if (!(flags & F.LAST_BOUNDARY) && c3 === LF) { index6 = 0; callback("onPartBegin"); state2 = S.HEADER_FIELD_START; } else { return; } break; } if (c3 !== boundary[index6 + 2]) { index6 = -2; } if (c3 === boundary[index6 + 2]) { index6++; } break; case S.HEADER_FIELD_START: state2 = S.HEADER_FIELD; mark("onHeaderField"); index6 = 0; // falls through case S.HEADER_FIELD: if (c3 === CR) { clear("onHeaderField"); state2 = S.HEADERS_ALMOST_DONE; break; } index6++; if (c3 === HYPHEN) { break; } if (c3 === COLON) { if (index6 === 1) { return; } dataCallback("onHeaderField", true); state2 = S.HEADER_VALUE_START; break; } cl = lower(c3); if (cl < A || cl > Z) { return; } break; case S.HEADER_VALUE_START: if (c3 === SPACE) { break; } mark("onHeaderValue"); state2 = S.HEADER_VALUE; // falls through case S.HEADER_VALUE: if (c3 === CR) { dataCallback("onHeaderValue", true); callback("onHeaderEnd"); state2 = S.HEADER_VALUE_ALMOST_DONE; } break; case S.HEADER_VALUE_ALMOST_DONE: if (c3 !== LF) { return; } state2 = S.HEADER_FIELD_START; break; case S.HEADERS_ALMOST_DONE: if (c3 !== LF) { return; } callback("onHeadersEnd"); state2 = S.PART_DATA_START; break; case S.PART_DATA_START: state2 = S.PART_DATA; mark("onPartData"); // falls through case S.PART_DATA: previousIndex = index6; if (index6 === 0) { i4 += boundaryEnd; while (i4 < bufferLength && !(data[i4] in boundaryChars)) { i4 += boundaryLength; } i4 -= boundaryEnd; c3 = data[i4]; } if (index6 < boundary.length) { if (boundary[index6] === c3) { if (index6 === 0) { dataCallback("onPartData", true); } index6++; } else { index6 = 0; } } else if (index6 === boundary.length) { index6++; if (c3 === CR) { flags |= F.PART_BOUNDARY; } else if (c3 === HYPHEN) { flags |= F.LAST_BOUNDARY; } else { index6 = 0; } } else if (index6 - 1 === boundary.length) { if (flags & F.PART_BOUNDARY) { index6 = 0; if (c3 === LF) { flags &= ~F.PART_BOUNDARY; callback("onPartEnd"); callback("onPartBegin"); state2 = S.HEADER_FIELD_START; break; } } else if (flags & F.LAST_BOUNDARY) { if (c3 === HYPHEN) { callback("onPartEnd"); state2 = S.END; flags = 0; } else { index6 = 0; } } else { index6 = 0; } } if (index6 > 0) { lookbehind[index6 - 1] = c3; } else if (previousIndex > 0) { const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); callback("onPartData", 0, previousIndex, _lookbehind); previousIndex = 0; mark("onPartData"); i4--; } break; case S.END: break; default: throw new Error(`Unexpected state entered: ${state2}`); } } dataCallback("onHeaderField"); dataCallback("onHeaderValue"); dataCallback("onPartData"); this.index = index6; this.state = state2; this.flags = flags; } end() { if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) { this.onPartEnd(); } else if (this.state !== S.END) { throw new Error("MultipartParser.end(): stream ended unexpectedly"); } } }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js async function consumeBody(data) { if (data[INTERNALS].disturbed) { throw new TypeError(`body used already for: ${data.url}`); } data[INTERNALS].disturbed = true; if (data[INTERNALS].error) { throw data[INTERNALS].error; } const { body } = data; if (body === null) { return import_node_buffer.Buffer.alloc(0); } if (!(body instanceof import_node_stream.default)) { return import_node_buffer.Buffer.alloc(0); } const accum = []; let accumBytes = 0; try { for await (const chunk of body) { if (data.size > 0 && accumBytes + chunk.length > data.size) { const error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); body.destroy(error2); throw error2; } accumBytes += chunk.length; accum.push(chunk); } } catch (error2) { const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2); throw error_; } if (body.readableEnded === true || body._readableState.ended === true) { try { if (accum.every((c3) => typeof c3 === "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 (isBlob2(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 (isBlob2(body)) { stream = import_node_stream.default.Readable.from(body.stream()); } this[INTERNALS] = { body, stream, boundary, disturbed: false, error: null }; this.size = size; if (body instanceof import_node_stream.default) { body.on("error", (error_) => { const error2 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); this[INTERNALS].error = error2; }); } } get body() { return this[INTERNALS].stream; } get bodyUsed() { return this[INTERNALS].disturbed; } /** * Decode response as ArrayBuffer * * @return Promise */ async arrayBuffer() { const { buffer, byteOffset, byteLength } = await consumeBody(this); return buffer.slice(byteOffset, byteOffset + byteLength); } async formData() { const ct = this.headers.get("content-type"); if (ct.startsWith("application/x-www-form-urlencoded")) { const formData = new FormData(); const parameters = new URLSearchParams(await this.text()); for (const [name, value] of parameters) { formData.append(name, value); } return formData; } const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports)); return toFormData2(this.body, ct); } /** * Return raw response as Blob * * @return Promise */ async blob() { const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; const buf = await this.arrayBuffer(); return new fetch_blob_default([buf], { type: ct }); } /** * Decode response as json * * @return Promise */ async json() { const text = await this.text(); return JSON.parse(text); } /** * Decode response as text * * @return Promise */ async text() { const buffer = await consumeBody(this); return new TextDecoder().decode(buffer); } /** * Decode response as buffer (non-spec api) * * @return Promise */ buffer() { return consumeBody(this); } }; Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); Object.defineProperties(Body.prototype, { body: { enumerable: true }, bodyUsed: { enumerable: true }, arrayBuffer: { enumerable: true }, blob: { enumerable: true }, json: { enumerable: true }, text: { enumerable: true }, data: { get: (0, import_node_util.deprecate)( () => { }, "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (response)" ) } }); clone = (instance, highWaterMark) => { let p1; let p22; let { body } = instance[INTERNALS]; if (instance.bodyUsed) { throw new Error("cannot clone body after it is used"); } if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") { p1 = new import_node_stream.PassThrough({ highWaterMark }); p22 = new import_node_stream.PassThrough({ highWaterMark }); body.pipe(p1); body.pipe(p22); instance[INTERNALS].stream = p1; body = p22; } return body; }; getNonSpecFormDataBoundary = (0, import_node_util.deprecate)( (body) => body.getBoundary(), "form-data doesn't follow the spec and requires special treatment. Use alternative package", "https://github.com/node-fetch/node-fetch/issues/1167" ); extractContentType = (body, 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 (isBlob2(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 (isBlob2(body)) { return body.size; } if (import_node_buffer.Buffer.isBuffer(body)) { return body.length; } if (body && typeof body.getLengthSync === "function") { return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; } return null; }; writeToStream = async (dest, { body }) => { if (body === null) { dest.end(); } else { await pipeline(body, dest); } }; } }); // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js function fromRawHeaders(headers = []) { return new Headers2( headers.reduce((result, value, index6, array2) => { if (index6 % 2 === 0) { result.push(array2.slice(index6, index6 + 2)); } return result; }, []).filter(([name, value]) => { try { validateHeaderName(name); validateHeaderValue(name, String(value)); return true; } catch { return false; } }) ); } var import_node_util2, import_node_http, validateHeaderName, validateHeaderValue, Headers2; var init_headers = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js"() { 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, p3, receiver) { switch (p3) { case "append": case "set": return (name, value) => { validateHeaderName(name); validateHeaderValue(name, String(value)); return URLSearchParams.prototype[p3].call( target, String(name).toLowerCase(), String(value) ); }; case "delete": case "has": case "getAll": return (name) => { validateHeaderName(name); return URLSearchParams.prototype[p3].call( target, String(name).toLowerCase() ); }; case "keys": return () => { target.sort(); return new Set(URLSearchParams.prototype.keys.call(target)).keys(); }; default: return Reflect.get(target, p3, 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 policy5 = 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 (policy5) { case "no-referrer": return "no-referrer"; case "origin": return referrerOrigin; case "unsafe-url": return referrerURL; case "strict-origin": if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return "no-referrer"; } return referrerOrigin.toString(); case "strict-origin-when-cross-origin": if (referrerURL.origin === currentURL.origin) { return referrerURL; } if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return "no-referrer"; } return referrerOrigin; case "same-origin": if (referrerURL.origin === currentURL.origin) { return referrerURL; } return "no-referrer"; case "origin-when-cross-origin": if (referrerURL.origin === currentURL.origin) { return referrerURL; } return referrerOrigin; case "no-referrer-when-downgrade": if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return "no-referrer"; } return referrerURL; default: throw new TypeError(`Invalid referrerPolicy: ${policy5}`); } } function parseReferrerPolicyFromHeader(headers) { const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); let policy5 = ""; for (const token of policyTokens) { if (token && ReferrerPolicy.has(token)) { policy5 = token; } } return policy5; } var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY; var init_referrer = __esm({ "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js"() { 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", (s4) => { let endedWithEventsCount; s4.prependListener("end", () => { endedWithEventsCount = s4._eventsCount; }); s4.prependListener("close", (hadError) => { if (response && endedWithEventsCount < s4._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.18.2/node_modules/ws/lib/constants.js var require_constants2 = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/constants.js"(exports2, module2) { "use strict"; var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; var hasBlob = typeof Blob !== "undefined"; if (hasBlob) BINARY_TYPES.push("blob"); module2.exports = { BINARY_TYPES, EMPTY_BUFFER: Buffer.alloc(0), GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", hasBlob, kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), kListener: Symbol("kListener"), kStatusCode: Symbol("status-code"), kWebSocket: Symbol("websocket"), NOOP: () => { } }; } }); // ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js var require_node_gyp_build = __commonJS({ "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) { 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(a3, b3) { return a3.architectures.length - b3.architectures.length; } function parseTags(file) { var arr = file.split("."); var extension = arr.pop(); var tags = { file, specificity: 0 }; if (extension !== "node") return; for (var i4 = 0; i4 < arr.length; i4++) { var tag = arr[i4]; 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(a3, b3) { if (a3.runtime !== b3.runtime) { return a3.runtime === runtime2 ? -1 : 1; } else if (a3.abi !== b3.abi) { return a3.abi ? -1 : 1; } else if (a3.specificity !== b3.specificity) { return a3.specificity > b3.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.4/node_modules/node-gyp-build/index.js var require_node_gyp_build2 = __commonJS({ "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports2, module2) { 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 i4 = 0; i4 < length; i4++) { output[offset + i4] = source[i4] ^ mask2[i4 & 3]; } }; var unmask = (buffer, mask2) => { const length = buffer.length; for (var i4 = 0; i4 < length; i4++) { buffer[i4] ^= mask2[i4 & 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 (e4) { module2.exports = require_fallback(); } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/buffer-util.js var require_buffer_util = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/buffer-util.js"(exports2, module2) { "use strict"; var { EMPTY_BUFFER } = require_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 i4 = 0; i4 < list.length; i4++) { const buf = list[i4]; 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 i4 = 0; i4 < length; i4++) { output[offset + i4] = source[i4] ^ mask[i4 & 3]; } } function _unmask(buffer, mask) { for (let i4 = 0; i4 < buffer.length; i4++) { buffer[i4] ^= mask[i4 & 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 (e4) { } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/limiter.js var require_limiter = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/limiter.js"(exports2, module2) { "use strict"; var kDone = Symbol("kDone"); var kRun = Symbol("kRun"); var Limiter = class { /** * Creates a new `Limiter`. * * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed * to run concurrently */ constructor(concurrency) { this[kDone] = () => { this.pending--; this[kRun](); }; this.concurrency = concurrency || Infinity; this.jobs = []; this.pending = 0; } /** * Adds a job to the queue. * * @param {Function} job The job to run * @public */ add(job) { this.jobs.push(job); this[kRun](); } /** * Removes a job from the queue and runs it if possible. * * @private */ [kRun]() { if (this.pending === this.concurrency) return; if (this.jobs.length) { const job = this.jobs.shift(); this.pending++; job(this[kDone]); } } }; module2.exports = Limiter; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/permessage-deflate.js var require_permessage_deflate = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) { "use strict"; var zlib2 = require("zlib"); var bufferUtil = require_buffer_util(); var Limiter = require_limiter(); var { kStatusCode } = require_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; if (this[kError]) { this[kCallback](this[kError]); return; } err2[kStatusCode] = 1007; this[kCallback](err2); } } }); // ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js var require_fallback2 = __commonJS({ "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js"(exports2, module2) { "use strict"; function isValidUTF8(buf) { const len = buf.length; let i4 = 0; while (i4 < len) { if ((buf[i4] & 128) === 0) { i4++; } else if ((buf[i4] & 224) === 192) { if (i4 + 1 === len || (buf[i4 + 1] & 192) !== 128 || (buf[i4] & 254) === 192) { return false; } i4 += 2; } else if ((buf[i4] & 240) === 224) { if (i4 + 2 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || buf[i4] === 224 && (buf[i4 + 1] & 224) === 128 || // overlong buf[i4] === 237 && (buf[i4 + 1] & 224) === 160) { return false; } i4 += 3; } else if ((buf[i4] & 248) === 240) { if (i4 + 3 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || (buf[i4 + 3] & 192) !== 128 || buf[i4] === 240 && (buf[i4 + 1] & 240) === 128 || // overlong buf[i4] === 244 && buf[i4 + 1] > 143 || buf[i4] > 244) { return false; } i4 += 4; } else { return false; } } return true; } 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 (e4) { module2.exports = require_fallback2(); } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/validation.js var require_validation = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/validation.js"(exports2, module2) { "use strict"; var { isUtf8 } = require("buffer"); var { hasBlob } = require_constants2(); 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 i4 = 0; while (i4 < len) { if ((buf[i4] & 128) === 0) { i4++; } else if ((buf[i4] & 224) === 192) { if (i4 + 1 === len || (buf[i4 + 1] & 192) !== 128 || (buf[i4] & 254) === 192) { return false; } i4 += 2; } else if ((buf[i4] & 240) === 224) { if (i4 + 2 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || buf[i4] === 224 && (buf[i4 + 1] & 224) === 128 || // Overlong buf[i4] === 237 && (buf[i4 + 1] & 224) === 160) { return false; } i4 += 3; } else if ((buf[i4] & 248) === 240) { if (i4 + 3 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || (buf[i4 + 3] & 192) !== 128 || buf[i4] === 240 && (buf[i4 + 1] & 240) === 128 || // Overlong buf[i4] === 244 && buf[i4 + 1] > 143 || buf[i4] > 244) { return false; } i4 += 4; } else { return false; } } return true; } function isBlob3(value) { return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); } module2.exports = { isBlob: isBlob3, isValidStatusCode, isValidUTF8: _isValidUTF8, tokenChars }; if (isUtf8) { module2.exports.isValidUTF8 = function(buf) { return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); }; } else if (!process.env.WS_NO_UTF_8_VALIDATE) { try { const isValidUTF8 = require_utf_8_validate(); module2.exports.isValidUTF8 = function(buf) { return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); }; } catch (e4) { } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/receiver.js var require_receiver = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/receiver.js"(exports2, module2) { "use strict"; var { Writable } = 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(n3) { this._bufferedBytes -= n3; if (n3 === this._buffers[0].length) return this._buffers.shift(); if (n3 < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n3, buf.length - n3 ); return new FastBuffer(buf.buffer, buf.byteOffset, n3); } const dst = Buffer.allocUnsafe(n3); do { const buf = this._buffers[0]; const offset = dst.length - n3; if (n3 >= buf.length) { dst.set(this._buffers.shift(), offset); } else { dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n3), offset); this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n3, buf.length - n3 ); } n3 -= buf.length; } while (n3 > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { this._loop = true; do { switch (this._state) { case GET_INFO: this.getInfo(cb); break; case GET_PAYLOAD_LENGTH_16: this.getPayloadLength16(cb); break; case GET_PAYLOAD_LENGTH_64: this.getPayloadLength64(cb); break; case GET_MASK: this.getMask(); break; case GET_DATA: this.getData(cb); break; case INFLATING: case DEFER_EVENT: this._loop = false; return; } } while (this._loop); if (!this._errored) cb(); } /** * Reads the first two bytes of a frame. * * @param {Function} cb Callback * @private */ getInfo(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 48) !== 0) { const error2 = this.createError( RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3" ); cb(error2); return; } const compressed = (buf[0] & 64) === 64; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { const error2 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error2); return; } this._fin = (buf[0] & 128) === 128; this._opcode = buf[0] & 15; this._payloadLength = buf[1] & 127; if (this._opcode === 0) { if (compressed) { const error2 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error2); return; } if (!this._fragmented) { const error2 = this.createError( RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error2); return; } this._opcode = this._fragmented; } else if (this._opcode === 1 || this._opcode === 2) { if (this._fragmented) { const error2 = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error2); return; } this._compressed = compressed; } else if (this._opcode > 7 && this._opcode < 11) { if (!this._fin) { const error2 = this.createError( RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN" ); cb(error2); return; } if (compressed) { const error2 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error2); return; } if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { const error2 = this.createError( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" ); cb(error2); return; } } else { const error2 = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error2); return; } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 128) === 128; if (this._isServer) { if (!this._masked) { const error2 = this.createError( RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK" ); cb(error2); return; } } else if (this._masked) { const error2 = this.createError( RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK" ); cb(error2); return; } if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else this.haveLength(cb); } /** * Gets extended payload length (7+16). * * @param {Function} cb Callback * @private */ getPayloadLength16(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); this.haveLength(cb); } /** * Gets extended payload length (7+64). * * @param {Function} cb Callback * @private */ getPayloadLength64(cb) { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); if (num > Math.pow(2, 53 - 32) - 1) { const error2 = this.createError( RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" ); cb(error2); return; } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); this.haveLength(cb); } /** * Payload length has been read. * * @param {Function} cb Callback * @private */ haveLength(cb) { if (this._payloadLength && this._opcode < 8) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { const error2 = this.createError( RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ); cb(error2); return; } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @private */ getData(cb) { let data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { unmask(data, this._mask); } } if (this._opcode > 7) { this.controlMessage(data, cb); return; } if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { this._messageLength = this._totalPayloadLength; this._fragments.push(data); } this.dataMessage(cb); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err2, buf) => { if (err2) return cb(err2); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { const error2 = this.createError( RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ); cb(error2); return; } this._fragments.push(buf); } this.dataMessage(cb); if (this._state === GET_INFO) this.startLoop(cb); }); } /** * Handles a data message. * * @param {Function} cb Callback * @private */ dataMessage(cb) { if (!this._fin) { this._state = GET_INFO; return; } const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._fragments = []; if (this._opcode === 2) { let data; if (this._binaryType === "nodebuffer") { data = concat(fragments, messageLength); } else if (this._binaryType === "arraybuffer") { data = toArrayBuffer(concat(fragments, messageLength)); } else if (this._binaryType === "blob") { data = new Blob(fragments); } else { data = fragments; } if (this._allowSynchronousEvents) { this.emit("message", data, true); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit("message", data, true); this._state = GET_INFO; this.startLoop(cb); }); } } else { const buf = concat(fragments, messageLength); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error2 = this.createError( Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8" ); cb(error2); return; } if (this._state === INFLATING || this._allowSynchronousEvents) { this.emit("message", buf, false); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit("message", buf, false); this._state = GET_INFO; this.startLoop(cb); }); } } } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data, cb) { if (this._opcode === 8) { if (data.length === 0) { this._loop = false; this.emit("conclude", 1005, EMPTY_BUFFER); this.end(); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { const error2 = this.createError( RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE" ); cb(error2); return; } const buf = new FastBuffer( data.buffer, data.byteOffset + 2, data.length - 2 ); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error2 = this.createError( Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8" ); cb(error2); return; } this._loop = false; this.emit("conclude", code, buf); this.end(); } this._state = GET_INFO; return; } if (this._allowSynchronousEvents) { this.emit(this._opcode === 9 ? "ping" : "pong", data); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit(this._opcode === 9 ? "ping" : "pong", data); this._state = GET_INFO; this.startLoop(cb); }); } } /** * Builds an error object. * * @param {function(new:Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @param {String} errorCode The exposed error code * @return {(Error|RangeError)} The error * @private */ createError(ErrorCtor, message, prefix2, statusCode, errorCode) { this._loop = false; this._errored = true; const err2 = new ErrorCtor( prefix2 ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err2, this.createError); err2.code = errorCode; err2[kStatusCode] = statusCode; return err2; } }; module2.exports = Receiver2; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/sender.js var require_sender = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/sender.js"(exports2, module2) { "use strict"; var { Duplex } = require("stream"); var { randomFillSync } = require("crypto"); var PerMessageDeflate = require_permessage_deflate(); var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants2(); var { isBlob: isBlob3, isValidStatusCode } = require_validation(); var { mask: applyMask, toBuffer } = require_buffer_util(); var kByteLength = Symbol("kByteLength"); var maskBuffer = Buffer.alloc(4); var RANDOM_POOL_SIZE = 8 * 1024; var randomPool; var randomPoolPointer = RANDOM_POOL_SIZE; var DEFAULT = 0; var DEFLATING = 1; var GET_BLOB_DATA = 2; var Sender2 = class _Sender { /** * Creates a Sender instance. * * @param {Duplex} socket The connection socket * @param {Object} [extensions] An object containing the negotiated extensions * @param {Function} [generateMask] The function used to generate the masking * key */ constructor(socket, extensions, generateMask) { this._extensions = extensions || {}; if (generateMask) { this._generateMask = generateMask; this._maskBuffer = Buffer.alloc(4); } this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._queue = []; this._state = DEFAULT; this.onerror = NOOP; this[kWebSocket] = void 0; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {(Buffer|String)} data The data to frame * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @return {(Buffer|String)[]} The framed data * @public */ static frame(data, options) { let mask; let merge = false; let offset = 2; let skipMasking = false; if (options.mask) { mask = options.maskBuffer || maskBuffer; if (options.generateMask) { options.generateMask(mask); } else { if (randomPoolPointer === RANDOM_POOL_SIZE) { if (randomPool === void 0) { randomPool = Buffer.alloc(RANDOM_POOL_SIZE); } randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); randomPoolPointer = 0; } mask[0] = randomPool[randomPoolPointer++]; mask[1] = randomPool[randomPoolPointer++]; mask[2] = randomPool[randomPoolPointer++]; mask[3] = randomPool[randomPoolPointer++]; } skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; offset = 6; } let dataLength; if (typeof data === "string") { if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { dataLength = options[kByteLength]; } else { data = Buffer.from(data); dataLength = data.length; } } else { dataLength = data.length; 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._state !== DEFAULT) { this.enqueue([this.dispatch, buf, false, options, cb]); } else { this.sendFrame(_Sender.frame(buf, options), cb); } } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ ping(data, mask, cb) { let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob3(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError("The data size must not be greater than 125 bytes"); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 9, readOnly, rsv1: false }; if (isBlob3(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(_Sender.frame(data, options), cb); } } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ pong(data, mask, cb) { let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob3(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError("The data size must not be greater than 125 bytes"); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 10, readOnly, rsv1: false }; if (isBlob3(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(_Sender.frame(data, options), cb); } } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} [options.binary=false] Specifies whether `data` is binary * or text * @param {Boolean} [options.compress=false] Specifies whether or not to * compress `data` * @param {Boolean} [options.fin=false] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Function} [cb] Callback * @public */ send(data, options, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; let opcode = options.binary ? 2 : 1; let rsv1 = options.compress; let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob3(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (this._firstFragment) { this._firstFragment = false; if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { rsv1 = byteLength >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; const opts = { [kByteLength]: byteLength, fin: options.fin, generateMask: this._generateMask, mask: options.mask, maskBuffer: this._maskBuffer, opcode, readOnly, rsv1 }; if (isBlob3(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, this._compress, opts, cb]); } else { this.getBlobData(data, this._compress, opts, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, this._compress, opts, cb]); } else { this.dispatch(data, this._compress, opts, cb); } } /** * Gets the contents of a blob as binary data. * * @param {Blob} blob The blob * @param {Boolean} [compress=false] Specifies whether or not to compress * the data * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ getBlobData(blob, compress2, options, cb) { this._bufferedBytes += options[kByteLength]; this._state = GET_BLOB_DATA; blob.arrayBuffer().then((arrayBuffer) => { if (this._socket.destroyed) { const err2 = new Error( "The socket was closed while the blob was being read" ); process.nextTick(callCallbacks, this, err2, cb); return; } this._bufferedBytes -= options[kByteLength]; const data = toBuffer(arrayBuffer); if (!compress2) { this._state = DEFAULT; this.sendFrame(_Sender.frame(data, options), cb); this.dequeue(); } else { this.dispatch(data, compress2, options, cb); } }).catch((err2) => { process.nextTick(onError, this, err2, cb); }); } /** * Dispatches a message. * * @param {(Buffer|String)} data The message to send * @param {Boolean} [compress=false] Specifies whether or not to compress * `data` * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ dispatch(data, compress2, options, cb) { if (!compress2) { this.sendFrame(_Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._bufferedBytes += options[kByteLength]; this._state = DEFLATING; perMessageDeflate.compress(data, options.fin, (_3, buf) => { if (this._socket.destroyed) { const err2 = new Error( "The socket was closed while data was being compressed" ); callCallbacks(this, err2, cb); return; } this._bufferedBytes -= options[kByteLength]; this._state = DEFAULT; options.readOnly = false; this.sendFrame(_Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (this._state === DEFAULT && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[3][kByteLength]; Reflect.apply(params[0], this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[3][kByteLength]; this._queue.push(params); } /** * Sends a frame. * * @param {(Buffer | String)[]} list The frame to send * @param {Function} [cb] Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } }; module2.exports = Sender2; function callCallbacks(sender, err2, cb) { if (typeof cb === "function") cb(err2); for (let i4 = 0; i4 < sender._queue.length; i4++) { const params = sender._queue[i4]; const callback = params[params.length - 1]; if (typeof callback === "function") callback(err2); } } function onError(sender, err2, cb) { callCallbacks(sender, err2, cb); sender.onerror(err2); } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/event-target.js var require_event_target = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/event-target.js"(exports2, module2) { "use strict"; var { kForOnEventAttribute, kListener } = require_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.18.2/node_modules/ws/lib/extension.js var require_extension = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/extension.js"(exports2, module2) { "use strict"; var { tokenChars } = require_validation(); function push2(dest, name, elem) { if (dest[name] === void 0) dest[name] = [elem]; else dest[name].push(elem); } function parse4(header) { const offers = /* @__PURE__ */ Object.create(null); let params = /* @__PURE__ */ Object.create(null); let mustUnescape = false; let isEscaping = false; let inQuotes = false; let extensionName; let paramName; let start = -1; let code = -1; let end = -1; let i4 = 0; for (; i4 < header.length; i4++) { code = header.charCodeAt(i4); if (extensionName === void 0) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i4; } else if (i4 !== 0 && (code === 32 || code === 9)) { if (end === -1 && start !== -1) end = i4; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i4}`); } if (end === -1) end = i4; 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 ${i4}`); } } else if (paramName === void 0) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i4; } else if (code === 32 || code === 9) { if (end === -1 && start !== -1) end = i4; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i4}`); } if (end === -1) end = i4; 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, i4); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i4}`); } } else { if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i4}`); } if (start === -1) start = i4; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i4; } else if (code === 34 && start !== -1) { inQuotes = false; end = i4; } else if (code === 92) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i4}`); } } else if (code === 34 && header.charCodeAt(i4 - 1) === 61) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i4; } else if (start !== -1 && (code === 32 || code === 9)) { if (end === -1) end = i4; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i4}`); } if (end === -1) end = i4; 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 ${i4}`); } } } if (start === -1 || inQuotes || code === 32 || code === 9) { throw new SyntaxError("Unexpected end of input"); } if (end === -1) end = i4; 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((k3) => { let values = params[k3]; if (!Array.isArray(values)) values = [values]; return values.map((v6) => v6 === true ? k3 : `${k3}=${v6}`).join("; "); }) ).join("; "); }).join(", "); }).join(", "); } module2.exports = { format, parse: parse4 }; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket.js var require_websocket = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket.js"(exports2, module2) { "use strict"; var EventEmitter = require("events"); var https2 = require("https"); var http3 = require("http"); var net = require("net"); var tls = require("tls"); var { randomBytes, createHash: 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 { isBlob: isBlob3 } = require_validation(); var { BINARY_TYPES, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants2(); var { EventTarget: { addEventListener: addEventListener2, removeEventListener } } = require_event_target(); var { format, parse: parse4 } = require_extension(); var { toBuffer } = require_buffer_util(); var closeTimeout = 30 * 1e3; var kAborted = Symbol("kAborted"); var protocolVersions = [8, 13]; var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; var WebSocket2 = class _WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|URL)} address The URL to which to connect * @param {(String|String[])} [protocols] The subprotocols * @param {Object} [options] Connection options */ constructor(address, protocols, options) { super(); this._binaryType = BINARY_TYPES[0]; this._closeCode = 1006; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = EMPTY_BUFFER; this._closeTimer = null; this._errorEmitted = false; this._extensions = {}; this._paused = false; this._protocol = ""; this._readyState = _WebSocket.CONNECTING; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._bufferedAmount = 0; this._isServer = false; this._redirects = 0; if (protocols === void 0) { protocols = []; } else if (!Array.isArray(protocols)) { if (typeof protocols === "object" && protocols !== null) { options = protocols; protocols = []; } else { protocols = [protocols]; } } initAsClient(this, address, protocols, options); } else { this._autoPong = options.autoPong; this._isServer = true; } } /** * For historical reasons, the custom "nodebuffer" type is used by the default * instead of "blob". * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return this._bufferedAmount; return this._socket._writableState.length + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * @type {Boolean} */ get isPaused() { return this._paused; } /** * @type {Function} */ /* istanbul ignore next */ get onclose() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onerror() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onopen() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onmessage() { return null; } /** * @type {String} */ get protocol() { return this._protocol; } /** * @type {Number} */ get readyState() { return this._readyState; } /** * @type {String} */ get url() { return this._url; } /** * Set up the socket and the internal resources. * * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Object} options Options object * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.maxPayload=0] The maximum allowed message size * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private */ setSocket(socket, head, options) { const receiver = new Receiver2({ allowSynchronousEvents: options.allowSynchronousEvents, binaryType: this.binaryType, extensions: this._extensions, isServer: this._isServer, maxPayload: options.maxPayload, skipUTF8Validation: options.skipUTF8Validation }); const sender = new Sender2(socket, this._extensions, options.generateMask); this._receiver = receiver; this._sender = sender; this._socket = socket; receiver[kWebSocket] = this; sender[kWebSocket] = this; socket[kWebSocket] = this; receiver.on("conclude", receiverOnConclude); receiver.on("drain", receiverOnDrain); receiver.on("error", receiverOnError); receiver.on("message", receiverOnMessage); receiver.on("ping", receiverOnPing); receiver.on("pong", receiverOnPong); sender.onerror = senderOnError; if (socket.setTimeout) socket.setTimeout(0); if (socket.setNoDelay) socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on("close", socketOnClose); socket.on("data", socketOnData); socket.on("end", socketOnEnd); socket.on("error", socketOnError); this._readyState = _WebSocket.OPEN; this.emit("open"); } /** * Emit the `'close'` event. * * @private */ emitClose() { if (!this._socket) { this._readyState = _WebSocket.CLOSED; this.emit("close", this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this._readyState = _WebSocket.CLOSED; this.emit("close", this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} [code] Status code explaining why the connection is closing * @param {(String|Buffer)} [data] The reason why the connection is * closing * @public */ close(code, data) { if (this.readyState === _WebSocket.CLOSED) return; if (this.readyState === _WebSocket.CONNECTING) { const msg = "WebSocket was closed before the connection was established"; abortHandshake(this, this._req, msg); return; } if (this.readyState === _WebSocket.CLOSING) { if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { this._socket.end(); } return; } this._readyState = _WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err2) => { if (err2) return; this._closeFrameSent = true; if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { this._socket.end(); } }); setCloseTimer(this); } /** * Pause the socket. * * @public */ pause() { if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { return; } this._paused = true; this._socket.pause(); } /** * Send a ping. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof data === "function") { cb = data; data = mask = void 0; } else if (typeof mask === "function") { cb = mask; mask = void 0; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === void 0) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof data === "function") { cb = data; data = mask = void 0; } else if (typeof mask === "function") { cb = mask; mask = void 0; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === void 0) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Resume the socket. * * @public */ resume() { if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { return; } this._paused = false; if (!this._receiver._writableState.needDrain) this._socket.resume(); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} [options] Options object * @param {Boolean} [options.binary] Specifies whether `data` is binary or * text * @param {Boolean} [options.compress] Specifies whether or not to compress * `data` * @param {Boolean} [options.fin=true] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask] Specifies whether or not to mask `data` * @param {Function} [cb] Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof options === "function") { cb = options; options = {}; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== "string", mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === _WebSocket.CLOSED) return; if (this.readyState === _WebSocket.CONNECTING) { const msg = "WebSocket was closed before the connection was established"; abortHandshake(this, this._req, msg); return; } if (this._socket) { this._readyState = _WebSocket.CLOSING; this._socket.destroy(); } } }; Object.defineProperty(WebSocket2, "CONNECTING", { enumerable: true, value: readyStates.indexOf("CONNECTING") }); Object.defineProperty(WebSocket2.prototype, "CONNECTING", { enumerable: true, value: readyStates.indexOf("CONNECTING") }); Object.defineProperty(WebSocket2, "OPEN", { enumerable: true, value: readyStates.indexOf("OPEN") }); Object.defineProperty(WebSocket2.prototype, "OPEN", { enumerable: true, value: readyStates.indexOf("OPEN") }); Object.defineProperty(WebSocket2, "CLOSING", { enumerable: true, value: readyStates.indexOf("CLOSING") }); Object.defineProperty(WebSocket2.prototype, "CLOSING", { enumerable: true, value: readyStates.indexOf("CLOSING") }); Object.defineProperty(WebSocket2, "CLOSED", { enumerable: true, value: readyStates.indexOf("CLOSED") }); Object.defineProperty(WebSocket2.prototype, "CLOSED", { enumerable: true, value: readyStates.indexOf("CLOSED") }); [ "binaryType", "bufferedAmount", "extensions", "isPaused", "protocol", "readyState", "url" ].forEach((property) => { Object.defineProperty(WebSocket2.prototype, property, { enumerable: true }); }); ["open", "error", "close", "message"].forEach((method) => { Object.defineProperty(WebSocket2.prototype, `on${method}`, { enumerable: true, get() { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) return listener[kListener]; } return null; }, set(handler) { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) { this.removeListener(method, listener); break; } } if (typeof handler !== "function") return; this.addEventListener(method, handler, { [kForOnEventAttribute]: true }); } }); }); WebSocket2.prototype.addEventListener = addEventListener2; WebSocket2.prototype.removeEventListener = removeEventListener; module2.exports = WebSocket2; function initAsClient(websocket, address, protocols, options) { const opts = { allowSynchronousEvents: true, autoPong: true, protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, socketPath: void 0, hostname: void 0, protocol: void 0, timeout: void 0, method: "GET", host: void 0, path: void 0, port: void 0 }; websocket._autoPong = opts.autoPong; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` ); } let parsedUrl; if (address instanceof URL3) { parsedUrl = address; } else { try { parsedUrl = new URL3(address); } catch (e4) { throw new SyntaxError(`Invalid URL: ${address}`); } } if (parsedUrl.protocol === "http:") { parsedUrl.protocol = "ws:"; } else if (parsedUrl.protocol === "https:") { parsedUrl.protocol = "wss:"; } websocket._url = parsedUrl.href; const isSecure = parsedUrl.protocol === "wss:"; const isIpcUrl = parsedUrl.protocol === "ws+unix:"; let invalidUrlMessage; if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`; } else if (isIpcUrl && !parsedUrl.pathname) { invalidUrlMessage = "The URL's pathname is empty"; } else if (parsedUrl.hash) { invalidUrlMessage = "The URL contains a fragment identifier"; } if (invalidUrlMessage) { const err2 = new SyntaxError(invalidUrlMessage); if (websocket._redirects === 0) { throw err2; } else { emitErrorAndClose(websocket, err2); return; } } const defaultPort = isSecure ? 443 : 80; const key = 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 (e4) { const err2 = new SyntaxError(`Invalid URL: ${location}`); emitErrorAndClose(websocket, err2); return; } initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit("unexpected-response", req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on("upgrade", (res, socket, head) => { websocket.emit("upgrade", res); if (websocket.readyState !== WebSocket2.CONNECTING) return; req = websocket._req = null; const upgrade = res.headers.upgrade; if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { abortHandshake(websocket, socket, "Invalid Upgrade header"); return; } const digest = 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 = parse4(secWebSocketExtensions); } catch (err2) { const message = "Invalid Sec-WebSocket-Extensions header"; abortHandshake(websocket, socket, message); return; } const extensionNames = Object.keys(extensions); if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { const message = "Server indicated an extension that was not requested"; abortHandshake(websocket, socket, message); return; } try { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); } catch (err2) { const message = "Invalid Sec-WebSocket-Extensions header"; abortHandshake(websocket, socket, message); return; } websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } websocket.setSocket(socket, head, { allowSynchronousEvents: opts.allowSynchronousEvents, generateMask: opts.generateMask, maxPayload: opts.maxPayload, skipUTF8Validation: opts.skipUTF8Validation }); }); if (opts.finishRequest) { opts.finishRequest(req, websocket); } else { req.end(); } } function emitErrorAndClose(websocket, err2) { websocket._readyState = WebSocket2.CLOSING; websocket._errorEmitted = true; websocket.emit("error", err2); websocket.emitClose(); } function netConnect(options) { options.path = options.socketPath; return net.connect(options); } function tlsConnect(options) { options.path = void 0; if (!options.servername && options.servername !== "") { options.servername = net.isIP(options.host) ? "" : options.host; } return tls.connect(options); } function abortHandshake(websocket, stream, message) { websocket._readyState = WebSocket2.CLOSING; const err2 = new Error(message); Error.captureStackTrace(err2, abortHandshake); if (stream.setHeader) { stream[kAborted] = true; stream.abort(); if (stream.socket && !stream.socket.destroyed) { stream.socket.destroy(); } process.nextTick(emitErrorAndClose, websocket, err2); } else { stream.destroy(err2); stream.once("error", websocket.emit.bind(websocket, "error")); stream.once("close", websocket.emitClose.bind(websocket)); } } function sendAfterClose(websocket, data, cb) { if (data) { const length = isBlob3(data) ? data.size : toBuffer(data).length; if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err2 = new Error( `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` ); process.nextTick(cb, err2); } } function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (websocket._socket[kWebSocket] === void 0) return; websocket._socket.removeListener("data", socketOnData); process.nextTick(resume, websocket._socket); if (code === 1005) websocket.close(); else websocket.close(code, reason); } function receiverOnDrain() { const websocket = this[kWebSocket]; if (!websocket.isPaused) websocket._socket.resume(); } function receiverOnError(err2) { const websocket = this[kWebSocket]; if (websocket._socket[kWebSocket] !== void 0) { websocket._socket.removeListener("data", socketOnData); process.nextTick(resume, websocket._socket); websocket.close(err2[kStatusCode]); } if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit("error", err2); } } function receiverOnFinish() { this[kWebSocket].emitClose(); } function receiverOnMessage(data, isBinary) { this[kWebSocket].emit("message", data, isBinary); } function receiverOnPing(data) { const websocket = this[kWebSocket]; if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); websocket.emit("ping", data); } function receiverOnPong(data) { this[kWebSocket].emit("pong", data); } function resume(stream) { stream.resume(); } function senderOnError(err2) { const websocket = this[kWebSocket]; if (websocket.readyState === WebSocket2.CLOSED) return; if (websocket.readyState === WebSocket2.OPEN) { websocket._readyState = WebSocket2.CLOSING; setCloseTimer(websocket); } this._socket.end(); if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit("error", err2); } } function setCloseTimer(websocket) { websocket._closeTimer = setTimeout( websocket._socket.destroy.bind(websocket._socket), closeTimeout ); } function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener("close", socketOnClose); this.removeListener("data", socketOnData); this.removeListener("end", socketOnEnd); websocket._readyState = WebSocket2.CLOSING; let chunk; if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) { websocket._receiver.write(chunk); } websocket._receiver.end(); this[kWebSocket] = void 0; clearTimeout(websocket._closeTimer); if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { websocket.emitClose(); } else { websocket._receiver.on("error", receiverOnFinish); websocket._receiver.on("finish", receiverOnFinish); } } function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } function socketOnEnd() { const websocket = this[kWebSocket]; websocket._readyState = WebSocket2.CLOSING; websocket._receiver.end(); this.end(); } function socketOnError() { const websocket = this[kWebSocket]; this.removeListener("error", socketOnError); this.on("error", NOOP); if (websocket) { websocket._readyState = WebSocket2.CLOSING; this.destroy(); } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/stream.js var require_stream = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/stream.js"(exports2, module2) { "use strict"; var WebSocket2 = require_websocket(); var { Duplex } = require("stream"); function emitClose(stream) { stream.emit("close"); } function duplexOnEnd() { if (!this.destroyed && this._writableState.finished) { this.destroy(); } } function duplexOnError(err2) { this.removeListener("error", duplexOnError); this.destroy(); if (this.listenerCount("error") === 0) { this.emit("error", err2); } } function createWebSocketStream2(ws, options) { let terminateOnDestroy = true; const duplex = new Duplex({ ...options, autoDestroy: false, emitClose: false, objectMode: false, writableObjectMode: false }); ws.on("message", function message(msg, isBinary) { const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; if (!duplex.push(data)) ws.pause(); }); ws.once("error", function error2(err2) { if (duplex.destroyed) return; terminateOnDestroy = false; duplex.destroy(err2); }); ws.once("close", function close() { if (duplex.destroyed) return; duplex.push(null); }); duplex._destroy = function(err2, callback) { if (ws.readyState === ws.CLOSED) { callback(err2); process.nextTick(emitClose, duplex); return; } let called = false; ws.once("error", function error2(err3) { called = true; callback(err3); }); ws.once("close", function close() { if (!called) callback(err2); process.nextTick(emitClose, duplex); }); if (terminateOnDestroy) ws.terminate(); }; duplex._final = function(callback) { if (ws.readyState === ws.CONNECTING) { ws.once("open", function open() { duplex._final(callback); }); return; } if (ws._socket === null) return; if (ws._socket._writableState.finished) { callback(); if (duplex._readableState.endEmitted) duplex.destroy(); } else { ws._socket.once("finish", function finish() { callback(); }); ws.close(); } }; duplex._read = function() { if (ws.isPaused) ws.resume(); }; duplex._write = function(chunk, encoding, callback) { if (ws.readyState === ws.CONNECTING) { ws.once("open", function open() { duplex._write(chunk, encoding, callback); }); return; } ws.send(chunk, callback); }; duplex.on("end", duplexOnEnd); duplex.on("error", duplexOnError); return duplex; } module2.exports = createWebSocketStream2; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/subprotocol.js var require_subprotocol = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/subprotocol.js"(exports2, module2) { "use strict"; var { tokenChars } = require_validation(); function parse4(header) { const protocols = /* @__PURE__ */ new Set(); let start = -1; let end = -1; let i4 = 0; for (i4; i4 < header.length; i4++) { const code = header.charCodeAt(i4); if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i4; } else if (i4 !== 0 && (code === 32 || code === 9)) { if (end === -1 && start !== -1) end = i4; } else if (code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i4}`); } if (end === -1) end = i4; 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 ${i4}`); } } if (start === -1 || end !== -1) { throw new SyntaxError("Unexpected end of input"); } const protocol = header.slice(start, i4); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); return protocols; } module2.exports = { parse: parse4 }; } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket-server.js var require_websocket_server = __commonJS({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/lib/websocket-server.js"(exports2, module2) { "use strict"; var EventEmitter = require("events"); var http3 = require("http"); var { Duplex } = require("stream"); var { createHash: 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 index6 = req.url.indexOf("?"); const pathname = index6 !== -1 ? req.url.slice(0, index6) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on("error", socketOnError); const key = req.headers["sec-websocket-key"]; const upgrade = req.headers.upgrade; const version3 = +req.headers["sec-websocket-version"]; if (req.method !== "GET") { const message = "Invalid HTTP method"; abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); return; } if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { const message = "Invalid Upgrade header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (key === void 0 || !keyRegex.test(key)) { const message = "Missing or invalid Sec-WebSocket-Key header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (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, map2) { for (const event of Object.keys(map2)) server.on(event, map2[event]); return function removeListeners() { for (const event of Object.keys(map2)) { server.removeListener(event, map2[event]); } }; } function emitClose(server) { server._state = CLOSED; server.emit("close"); } function socketOnError() { this.destroy(); } function abortHandshake(socket, code, message, headers) { message = message || http3.STATUS_CODES[code]; headers = { Connection: "close", "Content-Type": "text/html", "Content-Length": Buffer.byteLength(message), ...headers }; socket.once("finish", socket.destroy); socket.end( `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r ` + Object.keys(headers).map((h4) => `${h4}: ${headers[h4]}`).join("\r\n") + "\r\n\r\n" + message ); } function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { if (server.listenerCount("wsClientError")) { const err2 = new Error(message); Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError); server.emit("wsClientError", err2, socket, req); } else { abortHandshake(socket, code, message); } } } }); // ../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default; var init_wrapper = __esm({ "../node_modules/.pnpm/ws@8.18.2/node_modules/ws/wrapper.mjs"() { 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@4.3.1/node_modules/@smithy/types/dist-cjs/index.js var require_dist_cjs = __commonJS({ "../node_modules/.pnpm/@smithy+types@4.3.1/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: () => HttpApiKeyAuthLocation2, HttpAuthLocation: () => HttpAuthLocation, IniSectionType: () => IniSectionType, RequestHandlerProtocol: () => RequestHandlerProtocol, SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY4, getDefaultClientConfiguration: () => getDefaultClientConfiguration, resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig3 }); module2.exports = __toCommonJS2(src_exports); var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { HttpAuthLocation2["HEADER"] = "header"; HttpAuthLocation2["QUERY"] = "query"; return HttpAuthLocation2; })(HttpAuthLocation || {}); var HttpApiKeyAuthLocation2 = /* @__PURE__ */ ((HttpApiKeyAuthLocation22) => { HttpApiKeyAuthLocation22["HEADER"] = "header"; HttpApiKeyAuthLocation22["QUERY"] = "query"; return HttpApiKeyAuthLocation22; })(HttpApiKeyAuthLocation2 || {}); 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 { addChecksumAlgorithm(algo) { checksumAlgorithms.push(algo); }, checksumAlgorithms() { return 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 resolveDefaultRuntimeConfig3 = /* @__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_KEY4 = "__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@5.1.2/node_modules/@smithy/protocol-http/dist-cjs/index.js var require_dist_cjs2 = __commonJS({ "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/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: () => HttpRequest10, HttpResponse: () => HttpResponse4, IHttpRequest: () => import_types5.HttpRequest, getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration3, isValidHostname: () => isValidHostname, resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig3 }); module2.exports = __toCommonJS2(src_exports); var getHttpHandlerExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => { return { setHttpHandler(handler) { runtimeConfig.httpHandler = handler; }, httpHandler() { return runtimeConfig.httpHandler; }, updateHttpClientConfig(key, value) { var _a6; (_a6 = runtimeConfig.httpHandler) == null ? void 0 : _a6.updateHttpClientConfig(key, value); }, httpHandlerConfigs() { return runtimeConfig.httpHandler.httpHandlerConfigs(); } }; }, "getHttpHandlerExtensionConfiguration"); var resolveHttpHandlerRuntimeConfig3 = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { return { httpHandler: httpHandlerExtensionConfiguration.httpHandler() }; }, "resolveHttpHandlerRuntimeConfig"); var import_types5 = require_dist_cjs(); var _a2; var Field = (_a2 = class { constructor({ name, kind = import_types5.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((v6) => v6 !== value); } /** * Get comma-delimited string. * * @returns String representation of {@link Field}. */ toString() { return this.values.map((v6) => v6.includes(",") || v6.includes(" ") ? `"${v6}"` : v6).join(", "); } /** * Get string values as a list * * @returns Values in {@link Field} as a list. */ get() { return this.values; } }, __name(_a2, "Field"), _a2); var _a3; var Fields = (_a3 = class { 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(_a3, "Fields"), _a3); var _a4; var HttpRequest10 = (_a4 = class { 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; } /** * Note: this does not deep-clone the body. */ static clone(request) { const cloned = new _a4({ ...request, headers: { ...request.headers } }); if (cloned.query) { cloned.query = cloneQuery(cloned.query); } return cloned; } /** * This method only actually asserts that request is the interface {@link IHttpRequest}, * and not necessarily this concrete class. Left in place for API stability. * * Do not call instance methods on the input of this function, and * do not assume it has the HttpRequest prototype. */ 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"; } /** * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call * this method because {@link HttpRequest.isInstance} incorrectly * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). */ clone() { return _a4.clone(this); } }, __name(_a4, "HttpRequest"), _a4); 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 _a5; var HttpResponse4 = (_a5 = class { constructor(options) { this.statusCode = options.statusCode; this.reason = options.reason; this.headers = options.headers || {}; this.body = options.body; } static isInstance(response) { if (!response) return false; const resp = response; return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } }, __name(_a5, "HttpResponse"), _a5); 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.804.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.804.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 index_exports = {}; __export2(index_exports, { getHostHeaderPlugin: () => getHostHeaderPlugin3, hostHeaderMiddleware: () => hostHeaderMiddleware, hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, resolveHostHeaderConfig: () => resolveHostHeaderConfig3 }); module2.exports = __toCommonJS2(index_exports); var import_protocol_http15 = require_dist_cjs2(); function resolveHostHeaderConfig3(input) { return input; } __name(resolveHostHeaderConfig3, "resolveHostHeaderConfig"); var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { if (!import_protocol_http15.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 getHostHeaderPlugin3 = /* @__PURE__ */ __name((options) => ({ applyToStack: /* @__PURE__ */ __name((clientStack) => { clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); }, "applyToStack") }), "getHostHeaderPlugin"); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js var require_dist_cjs4 = __commonJS({ "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.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 index_exports = {}; __export2(index_exports, { getLoggerPlugin: () => getLoggerPlugin3, loggerMiddleware: () => loggerMiddleware, loggerMiddlewareOptions: () => loggerMiddlewareOptions }); module2.exports = __toCommonJS2(index_exports); var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { var _a2, _b; try { const response = await next(args); const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context; const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; const { $metadata, ...outputWithoutMetadata } = response.output; (_a2 = logger3 == null ? void 0 : logger3.info) == null ? void 0 : _a2.call(logger3, { clientName, commandName, input: inputFilterSensitiveLog(args.input), output: outputFilterSensitiveLog(outputWithoutMetadata), metadata: $metadata }); return response; } catch (error2) { const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context; const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; (_b = logger3 == null ? void 0 : logger3.error) == null ? void 0 : _b.call(logger3, { 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 getLoggerPlugin3 = /* @__PURE__ */ __name((options) => ({ applyToStack: /* @__PURE__ */ __name((clientStack) => { clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); }, "applyToStack") }), "getLoggerPlugin"); } }); // ../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.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.804.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 index_exports = {}; __export2(index_exports, { addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions, getRecursionDetectionPlugin: () => getRecursionDetectionPlugin3, recursionDetectionMiddleware: () => recursionDetectionMiddleware }); module2.exports = __toCommonJS2(index_exports); var import_protocol_http15 = 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_http15.HttpRequest.isInstance(request) || options.runtime !== "node") { return next(args); } const traceIdHeader = Object.keys(request.headers ?? {}).find((h4) => h4.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; if (request.headers.hasOwnProperty(traceIdHeader)) { 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 getRecursionDetectionPlugin3 = /* @__PURE__ */ __name((options) => ({ applyToStack: /* @__PURE__ */ __name((clientStack) => { clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions); }, "applyToStack") }), "getRecursionDetectionPlugin"); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js var import_types, getSmithyContext; var init_getSmithyContext = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js"() { import_types = __toESM(require_dist_cjs()); getSmithyContext = (context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}); } }); // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-cjs/index.js var require_dist_cjs6 = __commonJS({ "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/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: () => getSmithyContext8, normalizeProvider: () => normalizeProvider4 }); module2.exports = __toCommonJS2(src_exports); var import_types5 = require_dist_cjs(); var getSmithyContext8 = /* @__PURE__ */ __name((context) => context[import_types5.SMITHY_CONTEXT_KEY] || (context[import_types5.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); var normalizeProvider4 = /* @__PURE__ */ __name((input) => { if (typeof input === "function") return input; const promisified = Promise.resolve(input); return () => promisified; }, "normalizeProvider"); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js var resolveAuthOptions; var init_resolveAuthOptions = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() { resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { if (!authSchemePreference || authSchemePreference.length === 0) { return candidateAuthOptions; } const preferredAuthOptions = []; for (const preferredSchemeName of authSchemePreference) { for (const candidateAuthOption of candidateAuthOptions) { const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; if (candidateAuthSchemeName === preferredSchemeName) { preferredAuthOptions.push(candidateAuthOption); } } } for (const candidateAuthOption of candidateAuthOptions) { if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { preferredAuthOptions.push(candidateAuthOption); } } return preferredAuthOptions; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js function convertHttpAuthSchemesToMap(httpAuthSchemes) { const map2 = /* @__PURE__ */ new Map(); for (const scheme of httpAuthSchemes) { map2.set(scheme.schemeId, scheme); } return map2; } var import_types2, import_util_middleware, httpAuthSchemeMiddleware; var init_httpAuthSchemeMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() { import_types2 = __toESM(require_dist_cjs()); import_util_middleware = __toESM(require_dist_cjs6()); init_resolveAuthOptions(); httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { var _a2; const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; const resolvedOptions = resolveAuthOptions(options, authSchemePreference); const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); const smithyContext = (0, import_util_middleware.getSmithyContext)(context); const failureReasons = []; for (const option of resolvedOptions) { const scheme = authSchemes.get(option.schemeId); if (!scheme) { failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); continue; } const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); if (!identityProvider) { failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); continue; } const { identityProperties = {}, signingProperties = {} } = ((_a2 = option.propertiesExtractor) == null ? void 0 : _a2.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); }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin; var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() { init_httpAuthSchemeMiddleware(); httpAuthSchemeEndpointRuleSetMiddlewareOptions = { step: "serialize", tags: ["HTTP_AUTH_SCHEME"], name: "httpAuthSchemeMiddleware", override: true, relation: "before", toMiddleware: "endpointV2Middleware" }; getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-cjs/index.js var require_dist_cjs7 = __commonJS({ "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/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: () => getSerdePlugin4, serializerMiddleware: () => serializerMiddleware, serializerMiddlewareOption: () => serializerMiddlewareOption2 }); module2.exports = __toCommonJS2(src_exports); var import_protocol_http15 = require_dist_cjs2(); var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { var _a2, _b, _c, _d; const { response } = await next(args); try { const parsed = await deserializer(response, options); return { response, output: parsed }; } catch (error2) { Object.defineProperty(error2, "$response", { value: response }); if (!("$metadata" in error2)) { const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; try { error2.message += "\n " + hint; } catch (e4) { if (!context.logger || ((_b = (_a2 = context.logger) == null ? void 0 : _a2.constructor) == null ? void 0 : _b.name) === "NoOpLogger") { console.warn(hint); } else { (_d = (_c = context.logger) == null ? void 0 : _c.warn) == null ? void 0 : _d.call(_c, hint); } } if (typeof error2.$responseBodyText !== "undefined") { if (error2.$response) { error2.$response.body = error2.$responseBodyText; } } try { if (import_protocol_http15.HttpResponse.isInstance(response)) { const { headers = {} } = response; const headerEntries = Object.entries(headers); error2.$metadata = { httpStatusCode: response.statusCode, requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) }; } } catch (e4) { } } throw error2; } }, "deserializerMiddleware"); var findHeader = /* @__PURE__ */ __name((pattern, headers) => { return (headers.find(([k3]) => { return k3.match(pattern); }) || [void 0, void 0])[1]; }, "findHeader"); var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { var _a2; const endpointConfig = options; const endpoint = ((_a2 = context.endpointV2) == null ? void 0 : _a2.url) && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.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 serializerMiddlewareOption2 = { name: "serializerMiddleware", step: "serialize", tags: ["SERIALIZER"], override: true }; function getSerdePlugin4(config, serializer, deserializer) { return { applyToStack: (commandStack) => { commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption2); } }; } __name(getSerdePlugin4, "getSerdePlugin"); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js var import_middleware_serde, httpAuthSchemeMiddlewareOptions, getHttpAuthSchemePlugin; var init_getHttpAuthSchemePlugin = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() { import_middleware_serde = __toESM(require_dist_cjs7()); init_httpAuthSchemeMiddleware(); httpAuthSchemeMiddlewareOptions = { step: "serialize", tags: ["HTTP_AUTH_SCHEME"], name: "httpAuthSchemeMiddleware", override: true, relation: "before", toMiddleware: import_middleware_serde.serializerMiddlewareOption.name }; getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }), httpAuthSchemeMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js var init_middleware_http_auth_scheme = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() { init_httpAuthSchemeMiddleware(); init_getHttpAuthSchemeEndpointRuleSetPlugin(); init_getHttpAuthSchemePlugin(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js var import_protocol_http, import_types3, import_util_middleware2, defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware; var init_httpSigningMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() { import_protocol_http = __toESM(require_dist_cjs2()); import_types3 = __toESM(require_dist_cjs()); import_util_middleware2 = __toESM(require_dist_cjs6()); defaultErrorHandler = (signingProperties) => (error2) => { throw error2; }; defaultSuccessHandler = (httpResponse, signingProperties) => { }; httpSigningMiddleware = (config) => (next, context) => async (args) => { if (!import_protocol_http.HttpRequest.isInstance(args.request)) { return next(args); } const smithyContext = (0, import_util_middleware2.getSmithyContext)(context); const scheme = smithyContext.selectedHttpAuthScheme; if (!scheme) { throw new Error(`No HttpAuthScheme was selected: unable to sign request`); } const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; const output = await next({ ...args, request: await signer.sign(args.request, identity, signingProperties) }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); return output; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js var httpSigningMiddlewareOptions, getHttpSigningPlugin; var init_getHttpSigningMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() { init_httpSigningMiddleware(); httpSigningMiddlewareOptions = { step: "finalizeRequest", tags: ["HTTP_SIGNING"], name: "httpSigningMiddleware", aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], override: true, relation: "after", toMiddleware: "retryMiddleware" }; getHttpSigningPlugin = (config) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); } }); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js var init_middleware_http_signing = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() { init_httpSigningMiddleware(); init_getHttpSigningMiddleware(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js var normalizeProvider; var init_normalizeProvider = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js"() { normalizeProvider = (input) => { if (typeof input === "function") return input; const promisified = Promise.resolve(input); return () => promisified; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { return async function* paginateOperation(config, input, ...additionalArguments) { const _input = input; let token = config.startingToken ?? _input[inputTokenName]; let hasNext = true; let page; while (hasNext) { _input[inputTokenName] = token; if (pageSizeTokenName) { _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; } if (config.client instanceof ClientCtor) { page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); } else { throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); } yield page; const prevToken = token; token = get(page, outputTokenName); hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return void 0; }; } var makePagedClientRequest, get; var init_createPaginator = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() { makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_3) => _3, ...args) => { let command = new CommandCtor(input); command = withCommand(command) ?? command; return await client.send(command, ...args); }; get = (fromObject, 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; }; } }); // ../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js var require_dist_cjs8 = __commonJS({ "../node_modules/.pnpm/@smithy+is-array-buffer@4.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@4.0.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js var require_dist_cjs9 = __commonJS({ "../node_modules/.pnpm/@smithy+util-buffer-from@4.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_cjs8(); 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@4.0.0/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js var require_fromBase64 = __commonJS({ "../node_modules/.pnpm/@smithy+util-base64@4.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_cjs9(); var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; var fromBase645 = (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 = fromBase645; } }); // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-cjs/index.js var require_dist_cjs10 = __commonJS({ "../node_modules/.pnpm/@smithy+util-utf8@4.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: () => fromUtf84, toUint8Array: () => toUint8Array, toUtf8: () => toUtf85 }); module2.exports = __toCommonJS2(src_exports); var import_util_buffer_from = require_dist_cjs9(); var fromUtf84 = /* @__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 fromUtf84(data); } if (ArrayBuffer.isView(data)) { return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } return new Uint8Array(data); }, "toUint8Array"); var toUtf85 = /* @__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@4.0.0/node_modules/@smithy/util-base64/dist-cjs/toBase64.js var require_toBase64 = __commonJS({ "../node_modules/.pnpm/@smithy+util-base64@4.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_cjs9(); var util_utf8_1 = require_dist_cjs10(); var toBase645 = (_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 = toBase645; } }); // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/index.js var require_dist_cjs11 = __commonJS({ "../node_modules/.pnpm/@smithy+util-base64@4.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@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js var require_ChecksumStream = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ChecksumStream = void 0; var util_base64_1 = require_dist_cjs11(); var stream_1 = require("stream"); var ChecksumStream2 = class extends stream_1.Duplex { constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) { var _a2, _b; super(); if (typeof source.pipe === "function") { this.source = source; } else { throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a2 = source === null || source === void 0 ? void 0 : source.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); } this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; this.expectedChecksum = expectedChecksum; this.checksum = checksum; this.checksumSourceLocation = checksumSourceLocation; this.source.pipe(this); } _read(size) { } _write(chunk, encoding, callback) { try { this.checksum.update(chunk); this.push(chunk); } catch (e4) { return callback(e4); } return callback(); } async _final(callback) { try { const digest = await this.checksum.digest(); const received = this.base64Encoder(digest); if (this.expectedChecksum !== received) { return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}" in response header "${this.checksumSourceLocation}".`)); } } catch (e4) { return callback(e4); } this.push(null); return callback(); } }; exports2.ChecksumStream = ChecksumStream2; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js var require_stream_type_check = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.isBlob = exports2.isReadableStream = void 0; var isReadableStream2 = (stream) => { var _a2; return typeof ReadableStream === "function" && (((_a2 = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) === ReadableStream.name || stream instanceof ReadableStream); }; exports2.isReadableStream = isReadableStream2; var isBlob3 = (blob) => { var _a2; return typeof Blob === "function" && (((_a2 = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) === Blob.name || blob instanceof Blob); }; exports2.isBlob = isBlob3; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js var require_ChecksumStream_browser = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ChecksumStream = void 0; var ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function() { }; var ChecksumStream2 = class extends ReadableStreamRef { }; exports2.ChecksumStream = ChecksumStream2; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js var require_createChecksumStream_browser = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createChecksumStream = void 0; var util_base64_1 = require_dist_cjs11(); var stream_type_check_1 = require_stream_type_check(); var ChecksumStream_browser_1 = require_ChecksumStream_browser(); var createChecksumStream2 = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) => { var _a2, _b; if (!(0, stream_type_check_1.isReadableStream)(source)) { throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a2 = source === null || source === void 0 ? void 0 : source.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); } const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; if (typeof TransformStream !== "function") { throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); } const transform = new TransformStream({ start() { }, async transform(chunk, controller) { checksum.update(chunk); controller.enqueue(chunk); }, async flush(controller) { const digest = await checksum.digest(); const received = encoder(digest); if (expectedChecksum !== received) { const error2 = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`); controller.error(error2); } else { controller.terminate(); } } }); source.pipeThrough(transform); const readable = transform.readable; Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); return readable; }; exports2.createChecksumStream = createChecksumStream2; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js var require_createChecksumStream = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createChecksumStream = createChecksumStream2; var stream_type_check_1 = require_stream_type_check(); var ChecksumStream_1 = require_ChecksumStream(); var createChecksumStream_browser_1 = require_createChecksumStream_browser(); function createChecksumStream2(init2) { if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init2.source)) { return (0, createChecksumStream_browser_1.createChecksumStream)(init2); } return new ChecksumStream_1.ChecksumStream(init2); } } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js var require_ByteArrayCollector = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ByteArrayCollector = void 0; var ByteArrayCollector = class { constructor(allocByteArray) { this.allocByteArray = allocByteArray; this.byteLength = 0; this.byteArrays = []; } push(byteArray) { this.byteArrays.push(byteArray); this.byteLength += byteArray.byteLength; } flush() { if (this.byteArrays.length === 1) { const bytes = this.byteArrays[0]; this.reset(); return bytes; } const aggregation = this.allocByteArray(this.byteLength); let cursor = 0; for (let i4 = 0; i4 < this.byteArrays.length; ++i4) { const bytes = this.byteArrays[i4]; aggregation.set(bytes, cursor); cursor += bytes.byteLength; } this.reset(); return aggregation; } reset() { this.byteArrays = []; this.byteLength = 0; } }; exports2.ByteArrayCollector = ByteArrayCollector; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js var require_createBufferedReadableStream = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createBufferedReadable = void 0; exports2.createBufferedReadableStream = createBufferedReadableStream; exports2.merge = merge; exports2.flush = flush; exports2.sizeOf = sizeOf; exports2.modeOf = modeOf; var ByteArrayCollector_1 = require_ByteArrayCollector(); function createBufferedReadableStream(upstream, size, logger3) { const reader = upstream.getReader(); let streamBufferingLoggedWarning = false; let bytesSeen = 0; const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2))]; let mode = -1; const pull2 = async (controller) => { const { value, done } = await reader.read(); const chunk = value; if (done) { if (mode !== -1) { const remainder = flush(buffers, mode); if (sizeOf(remainder) > 0) { controller.enqueue(remainder); } } controller.close(); } else { const chunkMode = modeOf(chunk, false); if (mode !== chunkMode) { if (mode >= 0) { controller.enqueue(flush(buffers, mode)); } mode = chunkMode; } if (mode === -1) { controller.enqueue(chunk); return; } const chunkSize = sizeOf(chunk); bytesSeen += chunkSize; const bufferSize = sizeOf(buffers[mode]); if (chunkSize >= size && bufferSize === 0) { controller.enqueue(chunk); } else { const newSize = merge(buffers, mode, chunk); if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { streamBufferingLoggedWarning = true; logger3 === null || logger3 === void 0 ? void 0 : logger3.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); } if (newSize >= size) { controller.enqueue(flush(buffers, mode)); } else { await pull2(controller); } } } }; return new ReadableStream({ pull: pull2 }); } exports2.createBufferedReadable = createBufferedReadableStream; function merge(buffers, mode, chunk) { switch (mode) { case 0: buffers[0] += chunk; return sizeOf(buffers[0]); case 1: case 2: buffers[mode].push(chunk); return sizeOf(buffers[mode]); } } function flush(buffers, mode) { switch (mode) { case 0: const s4 = buffers[0]; buffers[0] = ""; return s4; case 1: case 2: return buffers[mode].flush(); } throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); } function sizeOf(chunk) { var _a2, _b; return (_b = (_a2 = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a2 !== void 0 ? _a2 : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; } function modeOf(chunk, allowBuffer = true) { if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { return 2; } if (chunk instanceof Uint8Array) { return 1; } if (typeof chunk === "string") { return 0; } return -1; } } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js var require_createBufferedReadable = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createBufferedReadable = createBufferedReadable2; var node_stream_1 = require("node:stream"); var ByteArrayCollector_1 = require_ByteArrayCollector(); var createBufferedReadableStream_1 = require_createBufferedReadableStream(); var stream_type_check_1 = require_stream_type_check(); function createBufferedReadable2(upstream, size, logger3) { if ((0, stream_type_check_1.isReadableStream)(upstream)) { return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger3); } const downstream = new node_stream_1.Readable({ read() { } }); let streamBufferingLoggedWarning = false; let bytesSeen = 0; const buffers = [ "", new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2)), new ByteArrayCollector_1.ByteArrayCollector((size2) => Buffer.from(new Uint8Array(size2))) ]; let mode = -1; upstream.on("data", (chunk) => { const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); if (mode !== chunkMode) { if (mode >= 0) { downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); } mode = chunkMode; } if (mode === -1) { downstream.push(chunk); return; } const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); bytesSeen += chunkSize; const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); if (chunkSize >= size && bufferSize === 0) { downstream.push(chunk); } else { const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { streamBufferingLoggedWarning = true; logger3 === null || logger3 === void 0 ? void 0 : logger3.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); } if (newSize >= size) { downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); } } }); upstream.on("end", () => { if (mode !== -1) { const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { downstream.push(remainder); } } downstream.push(null); }); return downstream; } } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js var require_getAwsChunkedEncodingStream = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/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-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js var require_headStream_browser = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.headStream = headStream2; async function headStream2(stream, bytes) { var _a2; let byteLengthCounter = 0; const chunks = []; const reader = stream.getReader(); let isDone = false; while (!isDone) { const { done, value } = await reader.read(); if (value) { chunks.push(value); byteLengthCounter += (_a2 = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a2 !== void 0 ? _a2 : 0; } if (byteLengthCounter >= bytes) { break; } isDone = done; } reader.releaseLock(); const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); let offset = 0; for (const chunk of chunks) { if (chunk.byteLength > collected.byteLength - offset) { collected.set(chunk.subarray(0, collected.byteLength - offset), offset); break; } else { collected.set(chunk, offset); } offset += chunk.length; } return collected; } } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.js var require_headStream = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.headStream = void 0; var stream_1 = require("stream"); var headStream_browser_1 = require_headStream_browser(); var stream_type_check_1 = require_stream_type_check(); var headStream2 = (stream, bytes) => { if ((0, stream_type_check_1.isReadableStream)(stream)) { return (0, headStream_browser_1.headStream)(stream, bytes); } return new Promise((resolve2, reject) => { const collector = new Collector(); collector.limit = bytes; stream.pipe(collector); stream.on("error", (err2) => { collector.end(); reject(err2); }); collector.on("error", reject); collector.on("finish", function() { const bytes2 = new Uint8Array(Buffer.concat(this.buffers)); resolve2(bytes2); }); }); }; exports2.headStream = headStream2; var Collector = class extends stream_1.Writable { constructor() { super(...arguments); this.buffers = []; this.limit = Infinity; this.bytesBuffered = 0; } _write(chunk, encoding, callback) { var _a2; this.buffers.push(chunk); this.bytesBuffered += (_a2 = chunk.byteLength) !== null && _a2 !== void 0 ? _a2 : 0; if (this.bytesBuffered >= this.limit) { const excess = this.bytesBuffered - this.limit; const tailBuffer = this.buffers[this.buffers.length - 1]; this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); this.emit("finish"); } callback(); } }; } }); // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-cjs/index.js var require_dist_cjs12 = __commonJS({ "../node_modules/.pnpm/@smithy+util-uri-escape@4.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((c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); } }); // ../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-cjs/index.js var require_dist_cjs13 = __commonJS({ "../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/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_cjs12(); 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 i4 = 0, iLen = value.length; i4 < iLen; i4++) { parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i4])}`); } } 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@4.0.6/node_modules/@smithy/node-http-handler/dist-cjs/index.js var require_dist_cjs14 = __commonJS({ "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/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: () => streamCollector3 }); module2.exports = __toCommonJS2(src_exports); var import_protocol_http15 = require_dist_cjs2(); var import_querystring_builder = require_dist_cjs13(); 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 timing = { setTimeout: (cb, ms) => setTimeout(cb, ms), clearTimeout: (timeoutId) => clearTimeout(timeoutId) }; var DEFER_EVENT_LISTENER_TIME = 1e3; var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { if (!timeoutInMs) { return -1; } const registerTimeout = /* @__PURE__ */ __name((offset) => { const timeoutId = timing.setTimeout(() => { request.destroy(); reject( Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { name: "TimeoutError" }) ); }, timeoutInMs - offset); const doWithSocket = /* @__PURE__ */ __name((socket) => { if (socket == null ? void 0 : socket.connecting) { socket.on("connect", () => { timing.clearTimeout(timeoutId); }); } else { timing.clearTimeout(timeoutId); } }, "doWithSocket"); if (request.socket) { doWithSocket(request.socket); } else { request.on("socket", doWithSocket); } }, "registerTimeout"); if (timeoutInMs < 2e3) { registerTimeout(0); return 0; } return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); }, "setConnectionTimeout"); var DEFER_EVENT_LISTENER_TIME2 = 3e3; var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { if (keepAlive !== true) { return -1; } const registerListener = /* @__PURE__ */ __name(() => { if (request.socket) { request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); } else { request.on("socket", (socket) => { socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); }); } }, "registerListener"); if (deferTimeMs === 0) { registerListener(); return 0; } return timing.setTimeout(registerListener, deferTimeMs); }, "setSocketKeepAlive"); var DEFER_EVENT_LISTENER_TIME3 = 3e3; var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { const registerTimeout = /* @__PURE__ */ __name((offset) => { const timeout = timeoutInMs - offset; const onTimeout = /* @__PURE__ */ __name(() => { request.destroy(); reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); }, "onTimeout"); if (request.socket) { request.socket.setTimeout(timeout, onTimeout); request.on("close", () => { var _a7; return (_a7 = request.socket) == null ? void 0 : _a7.removeListener("timeout", onTimeout); }); } else { request.setTimeout(timeout, onTimeout); } }, "registerTimeout"); if (0 < timeoutInMs && timeoutInMs < 6e3) { registerTimeout(0); return 0; } return timing.setTimeout( registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), DEFER_EVENT_LISTENER_TIME3 ); }, "setSocketTimeout"); var import_stream3 = require("stream"); var MIN_WAIT_TIME = 6e3; async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { const headers = request.headers ?? {}; const expect = headers["Expect"] || headers["expect"]; let timeoutId = -1; let sendBody = true; if (expect === "100-continue") { sendBody = await Promise.race([ new Promise((resolve2) => { timeoutId = Number(timing.setTimeout(() => resolve2(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); }), new Promise((resolve2) => { httpRequest.on("continue", () => { timing.clearTimeout(timeoutId); resolve2(true); }); httpRequest.on("response", () => { timing.clearTimeout(timeoutId); resolve2(false); }); httpRequest.on("error", () => { timing.clearTimeout(timeoutId); resolve2(false); }); }) ]); } if (sendBody) { 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 _a2; var NodeHttpHandler = (_a2 = class { 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 _a2(instanceOrOptions); } /** * @internal * * @param agent - http(s) agent in use by the NodeHttpHandler instance. * @param socketWarningTimestamp - last socket usage check timestamp. * @param logger - channel for the warning. * @returns timestamp of last emitted warning. */ static checkSocketUsage(agent, socketWarningTimestamp, logger3 = console) { var _a7, _b, _c; 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 = ((_a7 = sockets[origin]) == null ? void 0 : _a7.length) ?? 0; const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0; if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { (_c = logger3 == null ? void 0 : logger3.warn) == null ? void 0 : _c.call( logger3, `@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, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; const keepAlive = true; const maxSockets = 50; return { connectionTimeout, requestTimeout: requestTimeout ?? socketTimeout, socketAcquisitionWarningTimeout, 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 }); })(), logger: console }; } destroy() { var _a7, _b, _c, _d; (_b = (_a7 = this.config) == null ? void 0 : _a7.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; } return new Promise((_resolve, _reject) => { let writeRequestBodyPromise = void 0; const timeouts = []; const resolve2 = /* @__PURE__ */ __name(async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _resolve(arg); }, "resolve"); const reject = /* @__PURE__ */ __name(async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _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; timeouts.push( timing.setTimeout( () => { this.socketWarningTimestamp = _a2.checkSocketUsage( agent, this.socketWarningTimestamp, this.config.logger ); }, 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}`; } let hostname = request.hostname ?? ""; if (hostname[0] === "[" && hostname.endsWith("]")) { hostname = request.hostname.slice(1, -1); } else { hostname = request.hostname; } const nodeHttpsOptions = { headers: request.headers, host: 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_http15.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); } }); if (abortSignal) { const onAbort = /* @__PURE__ */ __name(() => { req.destroy(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); }, "onAbort"); if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); req.once("close", () => signal.removeEventListener("abort", onAbort)); } else { abortSignal.onabort = onAbort; } } timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout)); const httpAgent = nodeHttpsOptions.agent; if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { timeouts.push( setSocketKeepAlive(req, { // @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((e4) => { timeouts.forEach(timing.clearTimeout); return _reject(e4); }); }); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { return { ...config, [key]: value }; }); } httpHandlerConfigs() { return this.config ?? {}; } }, __name(_a2, "NodeHttpHandler"), _a2); var import_http22 = require("http2"); var import_http23 = __toESM3(require("http2")); var _a3; var NodeHttp2ConnectionPool = (_a3 = class { 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((s4) => s4 !== 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(_a3, "NodeHttp2ConnectionPool"), _a3); var _a4; var NodeHttp2ConnectionManager = (_a4 = class { 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 _a7; const cacheKey2 = this.getUrlString(requestContext); (_a7 = this.sessionCache.get(cacheKey2)) == null ? void 0 : _a7.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 (maxConcurrentStreams && maxConcurrentStreams <= 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(_a4, "NodeHttp2ConnectionManager"), _a4); var _a5; var NodeHttp2Handler = (_a5 = class { 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 _a5(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 _a7; 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: (_a7 = this.config) == null ? void 0 : _a7.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_http15.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) { const onAbort = /* @__PURE__ */ __name(() => { req.close(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; rejectWithDestroy(abortError); }, "onAbort"); if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); req.once("close", () => signal.removeEventListener("abort", onAbort)); } else { abortSignal.onabort = onAbort; } } 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(_a5, "NodeHttp2Handler"), _a5); var _a6; var Collector = (_a6 = class extends import_stream3.Writable { constructor() { super(...arguments); this.bufferedBytes = []; } _write(chunk, encoding, callback) { this.bufferedBytes.push(chunk); callback(); } }, __name(_a6, "Collector"), _a6); var streamCollector3 = /* @__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@5.0.4/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js var require_dist_cjs15 = __commonJS({ "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/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: () => streamCollector3 }); module2.exports = __toCommonJS2(src_exports); var import_protocol_http15 = require_dist_cjs2(); var import_querystring_builder = require_dist_cjs13(); function createRequest(url, requestOptions) { return new Request(url, requestOptions); } __name(createRequest, "createRequest"); 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: void 0 }; var _a2; var FetchHttpHandler = (_a2 = class { /** * @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 _a2(instanceOrOptions); } constructor(options) { if (typeof options === "function") { this.configProvider = options().then((opts) => opts || {}); } else { this.config = options ?? {}; this.configProvider = Promise.resolve(this.config); } if (keepAliveSupport.supported === void 0) { keepAliveSupport.supported = Boolean( typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") ); } } destroy() { } async handle(request, { abortSignal } = {}) { var _a3; if (!this.config) { this.config = await this.configProvider; } const requestTimeoutInMs = this.config.requestTimeout; const keepAlive = this.config.keepAlive === true; const credentials2 = this.config.credentials; 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, credentials: credentials2 }; if ((_a3 = this.config) == null ? void 0 : _a3.cache) { requestOptions.cache = this.config.cache; } if (body) { requestOptions.duplex = "half"; } if (typeof AbortController !== "undefined") { requestOptions.signal = abortSignal; } if (keepAliveSupport.supported) { requestOptions.keepalive = keepAlive; } if (typeof this.config.requestInit === "function") { Object.assign(requestOptions, this.config.requestInit(request)); } let removeSignalEventListener = /* @__PURE__ */ __name(() => { }, "removeSignalEventListener"); const fetchRequest = createRequest(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_http15.HttpResponse({ headers: transformedHeaders, reason: response.statusText, statusCode: response.status, body: body2 }) })); } return { response: new import_protocol_http15.HttpResponse({ headers: transformedHeaders, reason: response.statusText, statusCode: response.status, body: response.body }) }; }), requestTimeout(requestTimeoutInMs) ]; if (abortSignal) { raceOfPromises.push( new Promise((resolve2, reject) => { const onAbort = /* @__PURE__ */ __name(() => { const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); }, "onAbort"); if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); } else { abortSignal.onabort = onAbort; } }) ); } return Promise.race(raceOfPromises).finally(removeSignalEventListener); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { config[key] = value; return config; }); } httpHandlerConfigs() { return this.config ?? {}; } }, __name(_a2, "FetchHttpHandler"), _a2); var import_util_base645 = require_dist_cjs11(); var streamCollector3 = /* @__PURE__ */ __name(async (stream) => { var _a3; if (typeof Blob === "function" && stream instanceof Blob || ((_a3 = stream.constructor) == null ? void 0 : _a3.name) === "Blob") { if (Blob.prototype.arrayBuffer !== void 0) { return new Uint8Array(await stream.arrayBuffer()); } return collectBlob(stream); } return collectStream(stream); }, "streamCollector"); async function collectBlob(blob) { const base64 = await readToBase64(blob); const arrayBuffer = (0, import_util_base645.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@4.0.0/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js var require_dist_cjs16 = __commonJS({ "../node_modules/.pnpm/@smithy+util-hex-encoding@4.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 i4 = 0; i4 < 256; i4++) { let encodedByte = i4.toString(16).toLowerCase(); if (encodedByte.length === 1) { encodedByte = `0${encodedByte}`; } SHORT_TO_HEX[i4] = encodedByte; HEX_TO_SHORT[encodedByte] = i4; } 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 i4 = 0; i4 < encoded.length; i4 += 2) { const encodedByte = encoded.slice(i4, i4 + 2).toLowerCase(); if (encodedByte in HEX_TO_SHORT) { out[i4 / 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 i4 = 0; i4 < bytes.byteLength; i4++) { out += SHORT_TO_HEX[bytes[i4]]; } return out; } __name(toHex, "toHex"); } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/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@4.2.2/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_cjs15(); var util_base64_1 = require_dist_cjs11(); var util_hex_encoding_1 = require_dist_cjs16(); var util_utf8_1 = require_dist_cjs10(); var stream_type_check_1 = require_stream_type_check(); var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; var sdkStreamMixin3 = (stream) => { var _a2, _b; if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { const name = ((_b = (_a2 = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a2 === void 0 ? void 0 : _a2.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 ((0, stream_type_check_1.isReadableStream)(stream)) { return stream; } else { throw new Error(`Cannot transform payload to web stream, got ${stream}`); } } }); }; exports2.sdkStreamMixin = sdkStreamMixin3; var isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js var require_sdk_stream_mixin = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/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_cjs14(); var util_buffer_from_1 = require_dist_cjs9(); var stream_1 = require("stream"); 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 sdkStreamMixin3 = (stream) => { var _a2, _b; if (!(stream instanceof stream_1.Readable)) { try { return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); } catch (e4) { const name = ((_b = (_a2 = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a2 === void 0 ? void 0 : _a2.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 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 ensure a polyfill is available."); } transformed = true; return stream_1.Readable.toWeb(stream); } }); }; exports2.sdkStreamMixin = sdkStreamMixin3; } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js var require_splitStream_browser = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.splitStream = splitStream2; async function splitStream2(stream) { if (typeof stream.stream === "function") { stream = stream.stream(); } const readableStream = stream; return readableStream.tee(); } } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.js var require_splitStream = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.splitStream = splitStream2; var stream_1 = require("stream"); var splitStream_browser_1 = require_splitStream_browser(); var stream_type_check_1 = require_stream_type_check(); async function splitStream2(stream) { if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { return (0, splitStream_browser_1.splitStream)(stream); } const stream1 = new stream_1.PassThrough(); const stream2 = new stream_1.PassThrough(); stream.pipe(stream1); stream.pipe(stream2); return [stream1, stream2]; } } }); // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/index.js var require_dist_cjs17 = __commonJS({ "../node_modules/.pnpm/@smithy+util-stream@4.2.2/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: () => Uint8ArrayBlobAdapter2 }); module2.exports = __toCommonJS2(src_exports); var import_util_base645 = require_dist_cjs11(); var import_util_utf85 = require_dist_cjs10(); function transformToString(payload, encoding = "utf-8") { if (encoding === "base64") { return (0, import_util_base645.toBase64)(payload); } return (0, import_util_utf85.toUtf8)(payload); } __name(transformToString, "transformToString"); function transformFromString(str, encoding) { if (encoding === "base64") { return Uint8ArrayBlobAdapter2.mutate((0, import_util_base645.fromBase64)(str)); } return Uint8ArrayBlobAdapter2.mutate((0, import_util_utf85.fromUtf8)(str)); } __name(transformFromString, "transformFromString"); var _a2; var Uint8ArrayBlobAdapter2 = (_a2 = class 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, _a2.prototype); return source; } /** * @param encoding - default 'utf-8'. * @returns the blob as string. */ transformToString(encoding = "utf-8") { return transformToString(this, encoding); } }, __name(_a2, "Uint8ArrayBlobAdapter"), _a2); __reExport(src_exports, require_ChecksumStream(), module2.exports); __reExport(src_exports, require_createChecksumStream(), module2.exports); __reExport(src_exports, require_createBufferedReadable(), module2.exports); __reExport(src_exports, require_getAwsChunkedEncodingStream(), module2.exports); __reExport(src_exports, require_headStream(), module2.exports); __reExport(src_exports, require_sdk_stream_mixin(), module2.exports); __reExport(src_exports, require_splitStream(), module2.exports); __reExport(src_exports, require_stream_type_check(), module2.exports); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js var import_util_stream, collectBody2; var init_collect_stream_body = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() { import_util_stream = __toESM(require_dist_cjs17()); collectBody2 = 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); }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js function extendedEncodeURIComponent2(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c3) { return "%" + c3.charCodeAt(0).toString(16).toUpperCase(); }); } var init_extended_encode_uri_component = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() { } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js var deref; var init_deref = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() { deref = (schemaRef) => { if (typeof schemaRef === "function") { return schemaRef(); } return schemaRef; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js var import_protocol_http2, import_util_middleware3; var init_schemaDeserializationMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() { import_protocol_http2 = __toESM(require_dist_cjs2()); import_util_middleware3 = __toESM(require_dist_cjs6()); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js var import_util_middleware4; var init_schemaSerializationMiddleware = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() { import_util_middleware4 = __toESM(require_dist_cjs6()); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js var init_getSchemaSerdePlugin = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() { init_schemaDeserializationMiddleware(); init_schemaSerializationMiddleware(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js var TypeRegistry; var init_TypeRegistry = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() { TypeRegistry = class _TypeRegistry { constructor(namespace, schemas = /* @__PURE__ */ new Map()) { this.namespace = namespace; this.schemas = schemas; } static for(namespace) { if (!_TypeRegistry.registries.has(namespace)) { _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); } return _TypeRegistry.registries.get(namespace); } register(shapeId, schema6) { const qualifiedName = this.normalizeShapeId(shapeId); const registry = _TypeRegistry.for(this.getNamespace(shapeId)); registry.schemas.set(qualifiedName, schema6); } getSchema(shapeId) { const id = this.normalizeShapeId(shapeId); if (!this.schemas.has(id)) { throw new Error(`@smithy/core/schema - schema not found for ${id}`); } return this.schemas.get(id); } getBaseException() { for (const [id, schema6] of this.schemas.entries()) { if (id.startsWith("smithyts.client.synthetic.") && id.endsWith("ServiceException")) { return schema6; } } return void 0; } find(predicate) { return [...this.schemas.values()].find(predicate); } destroy() { _TypeRegistry.registries.delete(this.namespace); this.schemas.clear(); } normalizeShapeId(shapeId) { if (shapeId.includes("#")) { return shapeId; } return this.namespace + "#" + shapeId; } getNamespace(shapeId) { return this.normalizeShapeId(shapeId).split("#")[0]; } }; TypeRegistry.registries = /* @__PURE__ */ new Map(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js var Schema; var init_Schema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() { Schema = class { constructor(name, traits) { this.name = name; this.traits = traits; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js var ListSchema; var init_ListSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() { init_TypeRegistry(); init_Schema(); ListSchema = class extends Schema { constructor(name, traits, valueSchema) { super(name, traits); this.name = name; this.traits = traits; this.valueSchema = valueSchema; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js var MapSchema; var init_MapSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() { init_TypeRegistry(); init_Schema(); MapSchema = class extends Schema { constructor(name, traits, keySchema, valueSchema) { super(name, traits); this.name = name; this.traits = traits; this.keySchema = keySchema; this.valueSchema = valueSchema; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js var init_OperationSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() { init_TypeRegistry(); init_Schema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js var StructureSchema; var init_StructureSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() { init_TypeRegistry(); init_Schema(); StructureSchema = class extends Schema { constructor(name, traits, memberNames, memberList) { super(name, traits); this.name = name; this.traits = traits; this.memberNames = memberNames; this.memberList = memberList; this.members = {}; for (let i4 = 0; i4 < memberNames.length; ++i4) { this.members[memberNames[i4]] = Array.isArray(memberList[i4]) ? memberList[i4] : [memberList[i4], 0]; } } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js var init_ErrorSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() { init_TypeRegistry(); init_StructureSchema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js var SCHEMA; var init_sentinels = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() { SCHEMA = { BLOB: 21, STREAMING_BLOB: 42, BOOLEAN: 2, STRING: 0, NUMERIC: 1, BIG_INTEGER: 17, BIG_DECIMAL: 19, DOCUMENT: 15, TIMESTAMP_DEFAULT: 4, TIMESTAMP_DATE_TIME: 5, TIMESTAMP_HTTP_DATE: 6, TIMESTAMP_EPOCH_SECONDS: 7, LIST_MODIFIER: 64, MAP_MODIFIER: 128 }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js var SimpleSchema; var init_SimpleSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() { init_TypeRegistry(); init_Schema(); SimpleSchema = class extends Schema { constructor(name, schemaRef, traits) { super(name, traits); this.name = name; this.schemaRef = schemaRef; this.traits = traits; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js var NormalizedSchema; var init_NormalizedSchema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() { init_deref(); init_ListSchema(); init_MapSchema(); init_sentinels(); init_SimpleSchema(); init_StructureSchema(); NormalizedSchema = class _NormalizedSchema { constructor(ref, memberName) { var _a2, _b; this.ref = ref; this.memberName = memberName; const traitStack = []; let _ref = ref; let schema6 = ref; this._isMemberSchema = false; while (Array.isArray(_ref)) { traitStack.push(_ref[1]); _ref = _ref[0]; schema6 = deref(_ref); this._isMemberSchema = true; } if (traitStack.length > 0) { this.memberTraits = {}; for (let i4 = traitStack.length - 1; i4 >= 0; --i4) { const traitSet = traitStack[i4]; Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); } } else { this.memberTraits = 0; } if (schema6 instanceof _NormalizedSchema) { this.name = schema6.name; this.traits = schema6.traits; this._isMemberSchema = schema6._isMemberSchema; this.schema = schema6.schema; this.memberTraits = Object.assign({}, schema6.getMemberTraits(), this.getMemberTraits()); this.normalizedTraits = void 0; this.ref = schema6.ref; this.memberName = memberName ?? schema6.memberName; return; } this.schema = deref(schema6); if (this.schema && typeof this.schema === "object") { this.traits = ((_a2 = this.schema) == null ? void 0 : _a2.traits) ?? {}; } else { this.traits = 0; } this.name = (typeof this.schema === "object" ? (_b = this.schema) == null ? void 0 : _b.name : void 0) ?? this.memberName ?? this.getSchemaName(); if (this._isMemberSchema && !memberName) { throw new Error(`@smithy/core/schema - NormalizedSchema member schema ${this.getName(true)} must initialize with memberName argument.`); } } static of(ref, memberName) { if (ref instanceof _NormalizedSchema) { return ref; } return new _NormalizedSchema(ref, memberName); } static translateTraits(indicator) { if (typeof indicator === "object") { return indicator; } indicator = indicator | 0; const traits = {}; if ((indicator & 1) === 1) { traits.httpLabel = 1; } if ((indicator >> 1 & 1) === 1) { traits.idempotent = 1; } if ((indicator >> 2 & 1) === 1) { traits.idempotencyToken = 1; } if ((indicator >> 3 & 1) === 1) { traits.sensitive = 1; } if ((indicator >> 4 & 1) === 1) { traits.httpPayload = 1; } if ((indicator >> 5 & 1) === 1) { traits.httpResponseCode = 1; } if ((indicator >> 6 & 1) === 1) { traits.httpQueryParams = 1; } return traits; } static memberFrom(memberSchema, memberName) { if (memberSchema instanceof _NormalizedSchema) { memberSchema.memberName = memberName; memberSchema._isMemberSchema = true; return memberSchema; } return new _NormalizedSchema(memberSchema, memberName); } getSchema() { if (this.schema instanceof _NormalizedSchema) { return this.schema = this.schema.getSchema(); } if (this.schema instanceof SimpleSchema) { return deref(this.schema.schemaRef); } return deref(this.schema); } getName(withNamespace = false) { if (!withNamespace) { if (this.name && this.name.includes("#")) { return this.name.split("#")[1]; } } return this.name || void 0; } getMemberName() { if (!this.isMemberSchema()) { throw new Error(`@smithy/core/schema - cannot get member name on non-member schema: ${this.getName(true)}`); } return this.memberName; } isMemberSchema() { return this._isMemberSchema; } isUnitSchema() { return this.getSchema() === "unit"; } isListSchema() { const inner = this.getSchema(); if (typeof inner === "number") { return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; } return inner instanceof ListSchema; } isMapSchema() { const inner = this.getSchema(); if (typeof inner === "number") { return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; } return inner instanceof MapSchema; } isDocumentSchema() { return this.getSchema() === SCHEMA.DOCUMENT; } isStructSchema() { const inner = this.getSchema(); return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; } isBlobSchema() { return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; } isTimestampSchema() { const schema6 = this.getSchema(); return typeof schema6 === "number" && schema6 >= SCHEMA.TIMESTAMP_DEFAULT && schema6 <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; } isStringSchema() { return this.getSchema() === SCHEMA.STRING; } isBooleanSchema() { return this.getSchema() === SCHEMA.BOOLEAN; } isNumericSchema() { return this.getSchema() === SCHEMA.NUMERIC; } isBigIntegerSchema() { return this.getSchema() === SCHEMA.BIG_INTEGER; } isBigDecimalSchema() { return this.getSchema() === SCHEMA.BIG_DECIMAL; } isStreaming() { const streaming = !!this.getMergedTraits().streaming; if (streaming) { return true; } return this.getSchema() === SCHEMA.STREAMING_BLOB; } getMergedTraits() { if (this.normalizedTraits) { return this.normalizedTraits; } this.normalizedTraits = { ...this.getOwnTraits(), ...this.getMemberTraits() }; return this.normalizedTraits; } getMemberTraits() { return _NormalizedSchema.translateTraits(this.memberTraits); } getOwnTraits() { return _NormalizedSchema.translateTraits(this.traits); } getKeySchema() { if (this.isDocumentSchema()) { return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "key"); } if (!this.isMapSchema()) { throw new Error(`@smithy/core/schema - cannot get key schema for non-map schema: ${this.getName(true)}`); } const schema6 = this.getSchema(); if (typeof schema6 === "number") { return _NormalizedSchema.memberFrom([63 & schema6, 0], "key"); } return _NormalizedSchema.memberFrom([schema6.keySchema, 0], "key"); } getValueSchema() { const schema6 = this.getSchema(); if (typeof schema6 === "number") { if (this.isMapSchema()) { return _NormalizedSchema.memberFrom([63 & schema6, 0], "value"); } else if (this.isListSchema()) { return _NormalizedSchema.memberFrom([63 & schema6, 0], "member"); } } if (schema6 && typeof schema6 === "object") { if (this.isStructSchema()) { throw new Error(`cannot call getValueSchema() with StructureSchema ${this.getName(true)}`); } const collection = schema6; if ("valueSchema" in collection) { if (this.isMapSchema()) { return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "value"); } else if (this.isListSchema()) { return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "member"); } } } if (this.isDocumentSchema()) { return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "value"); } throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a value member.`); } getMemberSchema(member) { if (this.isStructSchema()) { const struct = this.getSchema(); if (!(member in struct.members)) { throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a member with name=${member}.`); } return _NormalizedSchema.memberFrom(struct.members[member], member); } if (this.isDocumentSchema()) { return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], member); } throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have members.`); } getMemberSchemas() { const { schema: schema6 } = this; const struct = schema6; if (!struct || typeof struct !== "object") { return {}; } if ("members" in struct) { const buffer = {}; for (const member of struct.memberNames) { buffer[member] = this.getMemberSchema(member); } return buffer; } return {}; } *structIterator() { if (!this.isStructSchema()) { throw new Error("@smithy/core/schema - cannot acquire structIterator on non-struct schema."); } const struct = this.getSchema(); for (let i4 = 0; i4 < struct.memberNames.length; ++i4) { yield [struct.memberNames[i4], _NormalizedSchema.memberFrom([struct.memberList[i4], 0], struct.memberNames[i4])]; } } getSchemaName() { var _a2; const schema6 = this.getSchema(); if (typeof schema6 === "number") { const _schema = 63 & schema6; const container = 192 & schema6; const type = ((_a2 = Object.entries(SCHEMA).find(([, value]) => { return value === _schema; })) == null ? void 0 : _a2[0]) ?? "Unknown"; switch (container) { case SCHEMA.MAP_MODIFIER: return `${type}Map`; case SCHEMA.LIST_MODIFIER: return `${type}List`; case 0: return type; } } return "Unknown"; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js var init_schema = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() { init_deref(); init_getSchemaSerdePlugin(); init_ListSchema(); init_MapSchema(); init_OperationSchema(); init_ErrorSchema(); init_NormalizedSchema(); init_Schema(); init_SimpleSchema(); init_StructureSchema(); init_sentinels(); init_TypeRegistry(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js var copyDocumentWithTransform2; var init_copyDocumentWithTransform = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() { init_schema(); copyDocumentWithTransform2 = (source, schemaRef, transform = (_3) => _3) => { const ns = NormalizedSchema.of(schemaRef); switch (typeof source) { case "undefined": case "boolean": case "number": case "string": case "bigint": case "symbol": return transform(source, ns); case "function": case "object": if (source === null) { return transform(null, ns); } if (Array.isArray(source)) { const newArray = new Array(source.length); let i4 = 0; for (const item of source) { newArray[i4++] = copyDocumentWithTransform2(item, ns.getValueSchema(), transform); } return transform(newArray, ns); } if ("byteLength" in source) { const newBytes = new Uint8Array(source.byteLength); newBytes.set(source, 0); return transform(newBytes, ns); } if (source instanceof Date) { return transform(source, ns); } const newObject = {}; if (ns.isMapSchema()) { for (const key of Object.keys(source)) { newObject[key] = copyDocumentWithTransform2(source[key], ns.getValueSchema(), transform); } } else if (ns.isStructSchema()) { for (const [key, memberSchema] of ns.structIterator()) { newObject[key] = copyDocumentWithTransform2(source[key], memberSchema, transform); } } else if (ns.isDocumentSchema()) { for (const key of Object.keys(source)) { newObject[key] = copyDocumentWithTransform2(source[key], ns.getValueSchema(), transform); } } return transform(newObject, ns); default: return transform(source, ns); } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js var parseBoolean2, expectBoolean2, expectNumber2, MAX_FLOAT, expectFloat322, expectLong2, expectInt2, expectInt322, expectShort2, expectByte2, expectSizedInt, castInt, expectNonNull2, expectObject2, expectString2, expectUnion2, strictParseDouble2, strictParseFloat2, strictParseFloat322, NUMBER_REGEX, parseNumber, limitedParseDouble2, handleFloat2, limitedParseFloat2, limitedParseFloat322, parseFloatString, strictParseLong2, strictParseInt2, strictParseInt322, strictParseShort2, strictParseByte2, stackTraceWarning, logger2; var init_parse_utils = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() { parseBoolean2 = (value) => { switch (value) { case "true": return true; case "false": return false; default: throw new Error(`Unable to parse boolean value "${value}"`); } }; expectBoolean2 = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "number") { if (value === 0 || value === 1) { logger2.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") { logger2.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}`); }; expectNumber2 = (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)) { logger2.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); } return parsed; } } if (typeof value === "number") { return value; } throw new TypeError(`Expected number, got ${typeof value}: ${value}`); }; MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); expectFloat322 = (value) => { const expected = expectNumber2(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; }; expectLong2 = (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}`); }; expectInt2 = expectLong2; expectInt322 = (value) => expectSizedInt(value, 32); expectShort2 = (value) => expectSizedInt(value, 16); expectByte2 = (value) => expectSizedInt(value, 8); expectSizedInt = (value, size) => { const expected = expectLong2(value); if (expected !== void 0 && castInt(expected, size) !== expected) { throw new TypeError(`Expected ${size}-bit integer, got ${value}`); } return expected; }; castInt = (value, size) => { switch (size) { case 32: return Int32Array.of(value)[0]; case 16: return Int16Array.of(value)[0]; case 8: return Int8Array.of(value)[0]; } }; expectNonNull2 = (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; }; expectObject2 = (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}`); }; expectString2 = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "string") { return value; } if (["boolean", "number", "bigint"].includes(typeof value)) { logger2.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); return String(value); } throw new TypeError(`Expected string, got ${typeof value}: ${value}`); }; expectUnion2 = (value) => { if (value === null || value === void 0) { return void 0; } const asObject = expectObject2(value); const setKeys = Object.entries(asObject).filter(([, v6]) => v6 != null).map(([k3]) => k3); 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; }; strictParseDouble2 = (value) => { if (typeof value == "string") { return expectNumber2(parseNumber(value)); } return expectNumber2(value); }; strictParseFloat2 = strictParseDouble2; strictParseFloat322 = (value) => { if (typeof value == "string") { return expectFloat322(parseNumber(value)); } return expectFloat322(value); }; NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; parseNumber = (value) => { const matches = value.match(NUMBER_REGEX); if (matches === null || matches[0].length !== value.length) { throw new TypeError(`Expected real number, got implicit NaN`); } return parseFloat(value); }; limitedParseDouble2 = (value) => { if (typeof value == "string") { return parseFloatString(value); } return expectNumber2(value); }; handleFloat2 = limitedParseDouble2; limitedParseFloat2 = limitedParseDouble2; limitedParseFloat322 = (value) => { if (typeof value == "string") { return parseFloatString(value); } return expectFloat322(value); }; parseFloatString = (value) => { switch (value) { case "NaN": return NaN; case "Infinity": return Infinity; case "-Infinity": return -Infinity; default: throw new Error(`Unable to parse float value: ${value}`); } }; strictParseLong2 = (value) => { if (typeof value === "string") { return expectLong2(parseNumber(value)); } return expectLong2(value); }; strictParseInt2 = strictParseLong2; strictParseInt322 = (value) => { if (typeof value === "string") { return expectInt322(parseNumber(value)); } return expectInt322(value); }; strictParseShort2 = (value) => { if (typeof value === "string") { return expectShort2(parseNumber(value)); } return expectShort2(value); }; strictParseByte2 = (value) => { if (typeof value === "string") { return expectByte2(parseNumber(value)); } return expectByte2(value); }; stackTraceWarning = (message) => { return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s4) => !s4.includes("stackTraceWarning")).join("\n"); }; logger2 = { warn: console.warn }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js function dateToUtcString2(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`; } var DAYS, MONTHS, RFC3339, parseRfc3339DateTime2, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset2, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseRfc7231DateTime2, parseEpochTimestamp2, buildDate, parseTwoDigitYear, FIFTY_YEARS_IN_MILLIS, adjustRfc850Year, parseMonthByShortName, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes; var init_date_utils = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() { init_parse_utils(); DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); parseRfc3339DateTime2 = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match2 = RFC3339.exec(value); if (!match2) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2; const year = strictParseShort2(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); }; RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); parseRfc3339DateTimeWithOffset2 = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match2 = RFC3339_WITH_OFFSET.exec(value); if (!match2) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2; const year = strictParseShort2(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); if (offsetStr.toUpperCase() != "Z") { date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); } return date; }; IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); parseRfc7231DateTime2 = (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 [_3, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2; return buildDate(strictParseShort2(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } match2 = RFC_850_DATE.exec(value); if (match2) { const [_3, 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 [_3, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match2; return buildDate(strictParseShort2(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } throw new TypeError("Invalid RFC-7231 date-time value"); }; parseEpochTimestamp2 = (value) => { if (value === null || value === void 0) { return void 0; } let valueAsDouble; if (typeof value === "number") { valueAsDouble = value; } else if (typeof value === "string") { valueAsDouble = strictParseDouble2(value); } else if (typeof value === "object" && value.tag === 1) { valueAsDouble = value.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)); }; buildDate = (year, month, day, time) => { const adjustedMonth = month - 1; validateDayOfMonth(year, adjustedMonth, day); return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); }; parseTwoDigitYear = (value) => { const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort2(stripLeadingZeroes(value)); if (valueInThisCentury < thisYear) { return valueInThisCentury + 100; } return valueInThisCentury; }; FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; adjustRfc850Year = (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; }; parseMonthByShortName = (value) => { const monthIdx = MONTHS.indexOf(value); if (monthIdx < 0) { throw new TypeError(`Invalid month: ${value}`); } return monthIdx + 1; }; DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; validateDayOfMonth = (year, month, day) => { let maxDays = DAYS_IN_MONTH[month]; if (month === 1 && isLeapYear(year)) { maxDays = 29; } if (day > maxDays) { throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } }; isLeapYear = (year) => { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; parseDateValue = (value, type, lower2, upper) => { const dateVal = strictParseByte2(stripLeadingZeroes(value)); if (dateVal < lower2 || dateVal > upper) { throw new TypeError(`${type} must be between ${lower2} and ${upper}, inclusive`); } return dateVal; }; parseMilliseconds = (value) => { if (value === null || value === void 0) { return 0; } return strictParseFloat322("0." + value) * 1e3; }; parseOffsetToMilliseconds = (value) => { const directionStr = value[0]; let direction = 1; if (directionStr == "+") { direction = 1; } else if (directionStr == "-") { direction = -1; } else { throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); } const hour = Number(value.substring(1, 3)); const minute = Number(value.substring(4, 6)); return direction * (hour * 60 + minute) * 60 * 1e3; }; stripLeadingZeroes = (value) => { let idx = 0; while (idx < value.length - 1 && value.charAt(idx) === "0") { idx++; } if (idx === 0) { return value; } return value.slice(idx); }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js var LazyJsonString2; var init_lazy_json = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() { LazyJsonString2 = function LazyJsonString3(val2) { const str = Object.assign(new String(val2), { deserializeJSON() { return JSON.parse(String(val2)); }, toString() { return String(val2); }, toJSON() { return String(val2); } }); return str; }; LazyJsonString2.from = (object) => { if (object && typeof object === "object" && (object instanceof LazyJsonString2 || "deserializeJSON" in object)) { return object; } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { return LazyJsonString2(String(object)); } return LazyJsonString2(JSON.stringify(object)); }; LazyJsonString2.fromObject = LazyJsonString2.from; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js function quoteHeader2(part) { if (part.includes(",") || part.includes('"')) { part = `"${part.replace(/"/g, '\\"')}"`; } return part; } var init_quote_header = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() { } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js function splitEvery2(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 i4 = 0; i4 < segments.length; i4++) { if (currentSegment === "") { currentSegment = segments[i4]; } else { currentSegment += delimiter + segments[i4]; } if ((i4 + 1) % numDelimiters === 0) { compoundSegments.push(currentSegment); currentSegment = ""; } } if (currentSegment !== "") { compoundSegments.push(currentSegment); } return compoundSegments; } var init_split_every = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() { } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js var splitHeader2; var init_split_header = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() { splitHeader2 = (value) => { const z2 = value.length; const values = []; let withinQuotes = false; let prevChar = void 0; let anchor = 0; for (let i4 = 0; i4 < z2; ++i4) { const char = value[i4]; switch (char) { case `"`: if (prevChar !== "\\") { withinQuotes = !withinQuotes; } break; case ",": if (!withinQuotes) { values.push(value.slice(anchor, i4)); anchor = i4 + 1; } break; default: } prevChar = char; } values.push(value.slice(anchor)); return values.map((v6) => { v6 = v6.trim(); const z3 = v6.length; if (z3 < 2) { return v6; } if (v6[0] === `"` && v6[z3 - 1] === `"`) { v6 = v6.slice(1, z3 - 1); } return v6.replace(/\\"/g, '"'); }); }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js function nv2(string2) { return new NumericValue2(string2, "bigDecimal"); } var NumericValue2; var init_NumericValue = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() { NumericValue2 = class { constructor(string2, type) { this.string = string2; this.type = type; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js var serde_exports = {}; __export(serde_exports, { LazyJsonString: () => LazyJsonString2, NumericValue: () => NumericValue2, copyDocumentWithTransform: () => copyDocumentWithTransform2, dateToUtcString: () => dateToUtcString2, expectBoolean: () => expectBoolean2, expectByte: () => expectByte2, expectFloat32: () => expectFloat322, expectInt: () => expectInt2, expectInt32: () => expectInt322, expectLong: () => expectLong2, expectNonNull: () => expectNonNull2, expectNumber: () => expectNumber2, expectObject: () => expectObject2, expectShort: () => expectShort2, expectString: () => expectString2, expectUnion: () => expectUnion2, handleFloat: () => handleFloat2, limitedParseDouble: () => limitedParseDouble2, limitedParseFloat: () => limitedParseFloat2, limitedParseFloat32: () => limitedParseFloat322, logger: () => logger2, nv: () => nv2, parseBoolean: () => parseBoolean2, parseEpochTimestamp: () => parseEpochTimestamp2, parseRfc3339DateTime: () => parseRfc3339DateTime2, parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset2, parseRfc7231DateTime: () => parseRfc7231DateTime2, quoteHeader: () => quoteHeader2, splitEvery: () => splitEvery2, splitHeader: () => splitHeader2, strictParseByte: () => strictParseByte2, strictParseDouble: () => strictParseDouble2, strictParseFloat: () => strictParseFloat2, strictParseFloat32: () => strictParseFloat322, strictParseInt: () => strictParseInt2, strictParseInt32: () => strictParseInt322, strictParseLong: () => strictParseLong2, strictParseShort: () => strictParseShort2 }); var init_serde = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() { init_copyDocumentWithTransform(); init_date_utils(); init_lazy_json(); init_parse_utils(); init_quote_header(); init_split_every(); init_split_header(); init_NumericValue(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js var import_protocol_http3, import_util_stream2, HttpProtocol; var init_HttpProtocol = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() { init_schema(); init_serde(); import_protocol_http3 = __toESM(require_dist_cjs2()); import_util_stream2 = __toESM(require_dist_cjs17()); init_collect_stream_body(); HttpProtocol = class { constructor(options) { this.options = options; } getRequestType() { return import_protocol_http3.HttpRequest; } getResponseType() { return import_protocol_http3.HttpResponse; } setSerdeContext(serdeContext) { this.serdeContext = serdeContext; this.serializer.setSerdeContext(serdeContext); this.deserializer.setSerdeContext(serdeContext); if (this.getPayloadCodec()) { this.getPayloadCodec().setSerdeContext(serdeContext); } } updateServiceEndpoint(request, endpoint) { if ("url" in endpoint) { request.protocol = endpoint.url.protocol; request.hostname = endpoint.url.hostname; request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; request.path = endpoint.url.pathname; request.fragment = endpoint.url.hash || void 0; request.username = endpoint.url.username || void 0; request.password = endpoint.url.password || void 0; for (const [k3, v6] of endpoint.url.searchParams.entries()) { if (!request.query) { request.query = {}; } request.query[k3] = v6; } return request; } else { request.protocol = endpoint.protocol; request.hostname = endpoint.hostname; request.port = endpoint.port ? Number(endpoint.port) : void 0; request.path = endpoint.path; request.query = { ...endpoint.query }; return request; } } setHostPrefix(request, operationSchema, input) { var _a2; const operationNs = NormalizedSchema.of(operationSchema); const inputNs = NormalizedSchema.of(operationSchema.input); if (operationNs.getMergedTraits().endpoint) { let hostPrefix = (_a2 = operationNs.getMergedTraits().endpoint) == null ? void 0 : _a2[0]; if (typeof hostPrefix === "string") { const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel); for (const [name] of hostLabelInputs) { const replacement = input[name]; if (typeof replacement !== "string") { throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); } hostPrefix = hostPrefix.replace(`{${name}}`, replacement); } request.hostname = hostPrefix + request.hostname; } } } deserializeMetadata(output) { return { 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"] }; } async deserializeHttpMessage(schema6, context, response, headerBindings, dataObject) { const deserializer = this.deserializer; const ns = NormalizedSchema.of(schema6); const nonHttpBindingMembers = []; for (const [memberName, memberSchema] of ns.structIterator()) { const memberTraits = memberSchema.getMemberTraits(); if (memberTraits.httpPayload) { const isStreaming = memberSchema.isStreaming(); if (isStreaming) { const isEventStream = memberSchema.isStructSchema(); if (isEventStream) { const context2 = this.serdeContext; if (!context2.eventStreamMarshaller) { throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); } const memberSchemas = memberSchema.getMemberSchemas(); dataObject[memberName] = context2.eventStreamMarshaller.deserialize(response.body, async (event) => { const unionMember = Object.keys(event).find((key) => { return key !== "__type"; }) ?? ""; if (unionMember in memberSchemas) { const eventStreamSchema = memberSchemas[unionMember]; return { [unionMember]: await deserializer.read(eventStreamSchema, event[unionMember].body) }; } else { return { $unknown: event }; } }); } else { dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); } } else if (response.body) { const bytes = await collectBody2(response.body, context); if (bytes.byteLength > 0) { dataObject[memberName] = await deserializer.read(memberSchema, bytes); } } } else if (memberTraits.httpHeader) { const key = String(memberTraits.httpHeader).toLowerCase(); const value = response.headers[key]; if (null != value) { if (memberSchema.isListSchema()) { const headerListValueSchema = memberSchema.getValueSchema(); let sections; if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === SCHEMA.TIMESTAMP_DEFAULT) { sections = splitEvery2(value, ",", 2); } else { sections = splitHeader2(value); } const list = []; for (const section of sections) { list.push(await deserializer.read([headerListValueSchema, { httpHeader: key }], section.trim())); } dataObject[memberName] = list; } else { dataObject[memberName] = await deserializer.read(memberSchema, value); } } } else if (memberTraits.httpPrefixHeaders !== void 0) { dataObject[memberName] = {}; for (const [header, value] of Object.entries(response.headers)) { if (!headerBindings.has(header) && header.startsWith(memberTraits.httpPrefixHeaders)) { dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read([memberSchema.getValueSchema(), { httpHeader: header }], value); } } } else if (memberTraits.httpResponseCode) { dataObject[memberName] = response.statusCode; } else { nonHttpBindingMembers.push(memberName); } } return nonHttpBindingMembers; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js var import_protocol_http4, HttpBindingProtocol; var init_HttpBindingProtocol = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() { init_schema(); import_protocol_http4 = __toESM(require_dist_cjs2()); init_collect_stream_body(); init_extended_encode_uri_component(); init_HttpProtocol(); HttpBindingProtocol = class extends HttpProtocol { async serializeRequest(operationSchema, input, context) { const serializer = this.serializer; const query = {}; const headers = {}; const endpoint = await context.endpoint(); const ns = NormalizedSchema.of(operationSchema == null ? void 0 : operationSchema.input); const schema6 = ns.getSchema(); let hasNonHttpBindingMember = false; let payload; const request = new import_protocol_http4.HttpRequest({ protocol: "", hostname: "", port: void 0, path: "", fragment: void 0, query, headers, body: void 0 }); if (endpoint) { this.updateServiceEndpoint(request, endpoint); this.setHostPrefix(request, operationSchema, input); const opTraits = NormalizedSchema.translateTraits(operationSchema.traits); if (opTraits.http) { request.method = opTraits.http[0]; const [path4, search] = opTraits.http[1].split("?"); if (request.path == "/") { request.path = path4; } else { request.path += path4; } const traitSearchParams = new URLSearchParams(search ?? ""); Object.assign(query, Object.fromEntries(traitSearchParams)); } } const _input = { ...input }; for (const memberName of Object.keys(_input)) { const memberNs = ns.getMemberSchema(memberName); if (memberNs === void 0) { continue; } const memberTraits = memberNs.getMergedTraits(); const inputMember = _input[memberName]; if (memberTraits.httpPayload) { const isStreaming = memberNs.isStreaming(); if (isStreaming) { const isEventStream = memberNs.isStructSchema(); if (isEventStream) { throw new Error("serialization of event streams is not yet implemented"); } else { payload = inputMember; } } else { serializer.write(memberNs, inputMember); payload = serializer.flush(); } } else if (memberTraits.httpLabel) { serializer.write(memberNs, inputMember); const replacement = serializer.flush(); if (request.path.includes(`{${memberName}+}`)) { request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent2).join("/")); } else if (request.path.includes(`{${memberName}}`)) { request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent2(replacement)); } delete _input[memberName]; } else if (memberTraits.httpHeader) { serializer.write(memberNs, inputMember); headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); delete _input[memberName]; } else if (typeof memberTraits.httpPrefixHeaders === "string") { for (const [key, val2] of Object.entries(inputMember)) { const amalgam = memberTraits.httpPrefixHeaders + key; serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val2); headers[amalgam.toLowerCase()] = serializer.flush(); } delete _input[memberName]; } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { this.serializeQuery(memberNs, inputMember, query); delete _input[memberName]; } else { hasNonHttpBindingMember = true; } } if (hasNonHttpBindingMember && input) { serializer.write(schema6, _input); payload = serializer.flush(); } request.headers = headers; request.query = query; request.body = payload; return request; } serializeQuery(ns, data, query) { const serializer = this.serializer; const traits = ns.getMergedTraits(); if (traits.httpQueryParams) { for (const [key, val2] of Object.entries(data)) { if (!(key in query)) { this.serializeQuery(NormalizedSchema.of([ ns.getValueSchema(), { ...traits, httpQuery: key, httpQueryParams: void 0 } ]), val2, query); } } return; } if (ns.isListSchema()) { const sparse = !!ns.getMergedTraits().sparse; const buffer = []; for (const item of data) { serializer.write([ns.getValueSchema(), traits], item); const serializable = serializer.flush(); if (sparse || serializable !== void 0) { buffer.push(serializable); } } query[traits.httpQuery] = buffer; } else { serializer.write([ns, traits], data); query[traits.httpQuery] = serializer.flush(); } } async deserializeResponse(operationSchema, context, response) { const deserializer = this.deserializer; const ns = NormalizedSchema.of(operationSchema.output); const dataObject = {}; if (response.statusCode >= 300) { const bytes = await collectBody2(response.body, context); if (bytes.byteLength > 0) { Object.assign(dataObject, await deserializer.read(SCHEMA.DOCUMENT, bytes)); } await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); } for (const header in response.headers) { const value = response.headers[header]; delete response.headers[header]; response.headers[header.toLowerCase()] = value; } const headerBindings = new Set(Object.values(ns.getMemberSchemas()).map((schema6) => { return schema6.getMergedTraits().httpHeader; }).filter(Boolean)); const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, headerBindings, dataObject); if (nonHttpBindingMembers.length) { const bytes = await collectBody2(response.body, context); if (bytes.byteLength > 0) { const dataFromBody = await deserializer.read(ns, bytes); for (const member of nonHttpBindingMembers) { dataObject[member] = dataFromBody[member]; } } } const output = { $metadata: this.deserializeMetadata(response), ...dataObject }; return output; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js var import_protocol_http5, RpcProtocol; var init_RpcProtocol = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() { init_schema(); import_protocol_http5 = __toESM(require_dist_cjs2()); init_collect_stream_body(); init_HttpProtocol(); RpcProtocol = class extends HttpProtocol { async serializeRequest(operationSchema, input, context) { const serializer = this.serializer; const query = {}; const headers = {}; const endpoint = await context.endpoint(); const ns = NormalizedSchema.of(operationSchema == null ? void 0 : operationSchema.input); const schema6 = ns.getSchema(); let payload; const request = new import_protocol_http5.HttpRequest({ protocol: "", hostname: "", port: void 0, path: "/", fragment: void 0, query, headers, body: void 0 }); if (endpoint) { this.updateServiceEndpoint(request, endpoint); this.setHostPrefix(request, operationSchema, input); } const _input = { ...input }; if (input) { serializer.write(schema6, _input); payload = serializer.flush(); } request.headers = headers; request.query = query; request.body = payload; request.method = "POST"; return request; } async deserializeResponse(operationSchema, context, response) { const deserializer = this.deserializer; const ns = NormalizedSchema.of(operationSchema.output); const dataObject = {}; if (response.statusCode >= 300) { const bytes2 = await collectBody2(response.body, context); if (bytes2.byteLength > 0) { Object.assign(dataObject, await deserializer.read(SCHEMA.DOCUMENT, bytes2)); } await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); } for (const header in response.headers) { const value = response.headers[header]; delete response.headers[header]; response.headers[header.toLowerCase()] = value; } const bytes = await collectBody2(response.body, context); if (bytes.byteLength > 0) { Object.assign(dataObject, await deserializer.read(ns, bytes)); } const output = { $metadata: this.deserializeMetadata(response), ...dataObject }; return output; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js var resolvedPath2; var init_resolve_path = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() { init_extended_encode_uri_component(); resolvedPath2 = (resolvedPath3, 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 + "."); } resolvedPath3 = resolvedPath3.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent2(segment)).join("/") : extendedEncodeURIComponent2(labelValue)); } else { throw new Error("No value provided for input HTTP label: " + memberName + "."); } return resolvedPath3; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js function requestBuilder(input, context) { return new RequestBuilder(input, context); } var import_protocol_http6, RequestBuilder; var init_requestBuilder = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() { import_protocol_http6 = __toESM(require_dist_cjs2()); init_resolve_path(); RequestBuilder = class { constructor(input, context) { this.input = input; this.context = context; this.query = {}; this.method = ""; this.headers = {}; this.path = ""; this.body = null; this.hostname = ""; this.resolvePathStack = []; } async build() { const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); this.path = basePath; for (const resolvePath of this.resolvePathStack) { resolvePath(this.path); } return new import_protocol_http6.HttpRequest({ protocol, hostname: this.hostname || hostname, port, method: this.method, path: this.path, query: this.query, body: this.body, headers: this.headers }); } hn(hostname) { this.hostname = hostname; return this; } bp(uriLabel) { this.resolvePathStack.push((basePath) => { this.path = `${(basePath == null ? void 0 : basePath.endsWith("/")) ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; }); return this; } p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { this.resolvePathStack.push((path4) => { this.path = resolvedPath2(path4, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); }); return this; } h(headers) { this.headers = headers; return this; } q(query) { this.query = query; return this; } b(body) { this.body = body; return this; } m(method) { this.method = method; return this; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js function determineTimestampFormat(ns, settings) { if (settings.timestampFormat.useTrait) { if (ns.isTimestampSchema() && (ns.getSchema() === SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { return ns.getSchema(); } } const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; return bindingFormat ?? settings.timestampFormat.default; } var init_determineTimestampFormat = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() { init_schema(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js var import_util_base64, import_util_utf8, FromStringShapeDeserializer; var init_FromStringShapeDeserializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() { init_schema(); init_serde(); import_util_base64 = __toESM(require_dist_cjs11()); import_util_utf8 = __toESM(require_dist_cjs10()); init_determineTimestampFormat(); FromStringShapeDeserializer = class { constructor(settings) { this.settings = settings; } setSerdeContext(serdeContext) { this.serdeContext = serdeContext; } read(_schema, data) { var _a2; const ns = NormalizedSchema.of(_schema); if (ns.isListSchema()) { return splitHeader2(data).map((item) => this.read(ns.getValueSchema(), item)); } if (ns.isBlobSchema()) { return (((_a2 = this.serdeContext) == null ? void 0 : _a2.base64Decoder) ?? import_util_base64.fromBase64)(data); } if (ns.isTimestampSchema()) { const format = determineTimestampFormat(ns, this.settings); switch (format) { case SCHEMA.TIMESTAMP_DATE_TIME: return parseRfc3339DateTimeWithOffset2(data); case SCHEMA.TIMESTAMP_HTTP_DATE: return parseRfc7231DateTime2(data); case SCHEMA.TIMESTAMP_EPOCH_SECONDS: return parseEpochTimestamp2(data); default: console.warn("Missing timestamp format, parsing value with Date constructor:", data); return new Date(data); } } if (ns.isStringSchema()) { const mediaType = ns.getMergedTraits().mediaType; let intermediateValue = data; if (mediaType) { if (ns.getMergedTraits().httpHeader) { intermediateValue = this.base64ToUtf8(intermediateValue); } const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); if (isJson) { intermediateValue = LazyJsonString2.from(intermediateValue); } return intermediateValue; } } switch (true) { case ns.isNumericSchema(): return Number(data); case ns.isBigIntegerSchema(): return BigInt(data); case ns.isBigDecimalSchema(): return new NumericValue2(data, "bigDecimal"); case ns.isBooleanSchema(): return String(data).toLowerCase() === "true"; } return data; } base64ToUtf8(base64String) { var _a2, _b; return (((_a2 = this.serdeContext) == null ? void 0 : _a2.utf8Encoder) ?? import_util_utf8.toUtf8)((((_b = this.serdeContext) == null ? void 0 : _b.base64Decoder) ?? import_util_base64.fromBase64)(base64String)); } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js var import_util_utf82, HttpInterceptingShapeDeserializer; var init_HttpInterceptingShapeDeserializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() { init_schema(); import_util_utf82 = __toESM(require_dist_cjs10()); init_FromStringShapeDeserializer(); HttpInterceptingShapeDeserializer = class { constructor(codecDeserializer, codecSettings) { this.codecDeserializer = codecDeserializer; this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); } setSerdeContext(serdeContext) { this.stringDeserializer.setSerdeContext(serdeContext); this.codecDeserializer.setSerdeContext(serdeContext); this.serdeContext = serdeContext; } read(schema6, data) { var _a2, _b; const ns = NormalizedSchema.of(schema6); const traits = ns.getMergedTraits(); const toString = ((_a2 = this.serdeContext) == null ? void 0 : _a2.utf8Encoder) ?? import_util_utf82.toUtf8; if (traits.httpHeader || traits.httpResponseCode) { return this.stringDeserializer.read(ns, toString(data)); } if (traits.httpPayload) { if (ns.isBlobSchema()) { const toBytes = ((_b = this.serdeContext) == null ? void 0 : _b.utf8Decoder) ?? import_util_utf82.fromUtf8; if (typeof data === "string") { return toBytes(data); } return data; } else if (ns.isStringSchema()) { if ("byteLength" in data) { return toString(data); } return data; } } return this.codecDeserializer.read(ns, data); } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js var import_util_base642, ToStringShapeSerializer; var init_ToStringShapeSerializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() { init_schema(); init_serde(); import_util_base642 = __toESM(require_dist_cjs11()); init_determineTimestampFormat(); ToStringShapeSerializer = class { constructor(settings) { this.settings = settings; this.stringBuffer = ""; this.serdeContext = void 0; } setSerdeContext(serdeContext) { this.serdeContext = serdeContext; } write(schema6, value) { var _a2, _b; const ns = NormalizedSchema.of(schema6); switch (typeof value) { case "object": if (value === null) { this.stringBuffer = "null"; return; } if (ns.isTimestampSchema()) { if (!(value instanceof Date)) { throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); } const format = determineTimestampFormat(ns, this.settings); switch (format) { case SCHEMA.TIMESTAMP_DATE_TIME: this.stringBuffer = value.toISOString().replace(".000Z", "Z"); break; case SCHEMA.TIMESTAMP_HTTP_DATE: this.stringBuffer = dateToUtcString2(value); break; case SCHEMA.TIMESTAMP_EPOCH_SECONDS: this.stringBuffer = String(value.getTime() / 1e3); break; default: console.warn("Missing timestamp format, using epoch seconds", value); this.stringBuffer = String(value.getTime() / 1e3); } return; } if (ns.isBlobSchema() && "byteLength" in value) { this.stringBuffer = (((_a2 = this.serdeContext) == null ? void 0 : _a2.base64Encoder) ?? import_util_base642.toBase64)(value); return; } if (ns.isListSchema() && Array.isArray(value)) { let buffer = ""; for (const item of value) { this.write([ns.getValueSchema(), ns.getMergedTraits()], item); const headerItem = this.flush(); const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader2(headerItem); if (buffer !== "") { buffer += ", "; } buffer += serialized; } this.stringBuffer = buffer; return; } this.stringBuffer = JSON.stringify(value, null, 2); break; case "string": const mediaType = ns.getMergedTraits().mediaType; let intermediateValue = value; if (mediaType) { const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); if (isJson) { intermediateValue = LazyJsonString2.from(intermediateValue); } if (ns.getMergedTraits().httpHeader) { this.stringBuffer = (((_b = this.serdeContext) == null ? void 0 : _b.base64Encoder) ?? import_util_base642.toBase64)(intermediateValue.toString()); return; } } this.stringBuffer = value; break; default: this.stringBuffer = String(value); } } flush() { const buffer = this.stringBuffer; this.stringBuffer = ""; return buffer; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js var HttpInterceptingShapeSerializer; var init_HttpInterceptingShapeSerializer = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() { init_schema(); init_ToStringShapeSerializer(); HttpInterceptingShapeSerializer = class { constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { this.codecSerializer = codecSerializer; this.stringSerializer = stringSerializer; } setSerdeContext(serdeContext) { this.codecSerializer.setSerdeContext(serdeContext); this.stringSerializer.setSerdeContext(serdeContext); } write(schema6, value) { const ns = NormalizedSchema.of(schema6); const traits = ns.getMergedTraits(); if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { this.stringSerializer.write(ns, value); this.buffer = this.stringSerializer.flush(); return; } return this.codecSerializer.write(ns, value); } flush() { if (this.buffer !== void 0) { const buffer = this.buffer; this.buffer = void 0; return buffer; } return this.codecSerializer.flush(); } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js var protocols_exports = {}; __export(protocols_exports, { FromStringShapeDeserializer: () => FromStringShapeDeserializer, HttpBindingProtocol: () => HttpBindingProtocol, HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, RequestBuilder: () => RequestBuilder, RpcProtocol: () => RpcProtocol, ToStringShapeSerializer: () => ToStringShapeSerializer, collectBody: () => collectBody2, determineTimestampFormat: () => determineTimestampFormat, extendedEncodeURIComponent: () => extendedEncodeURIComponent2, requestBuilder: () => requestBuilder, resolvedPath: () => resolvedPath2 }); var init_protocols = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() { init_collect_stream_body(); init_extended_encode_uri_component(); init_HttpBindingProtocol(); init_RpcProtocol(); init_requestBuilder(); init_resolve_path(); init_FromStringShapeDeserializer(); init_HttpInterceptingShapeDeserializer(); init_HttpInterceptingShapeSerializer(); init_ToStringShapeSerializer(); init_determineTimestampFormat(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js var init_requestBuilder2 = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() { init_protocols(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js function setFeature(context, feature, value) { if (!context.__smithy_context) { context.__smithy_context = { features: {} }; } else if (!context.__smithy_context.features) { context.__smithy_context.features = {}; } context.__smithy_context.features[feature] = value; } var init_setFeature = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js"() { } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js var DefaultIdentityProviderConfig; var init_DefaultIdentityProviderConfig = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() { DefaultIdentityProviderConfig = class { constructor(config) { this.authSchemes = /* @__PURE__ */ new Map(); for (const [key, value] of Object.entries(config)) { if (value !== void 0) { this.authSchemes.set(key, value); } } } getIdentityProvider(schemeId) { return this.authSchemes.get(schemeId); } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js var import_protocol_http7, import_types4, HttpApiKeyAuthSigner; var init_httpApiKeyAuth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() { import_protocol_http7 = __toESM(require_dist_cjs2()); import_types4 = __toESM(require_dist_cjs()); HttpApiKeyAuthSigner = class { 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 = import_protocol_http7.HttpRequest.clone(httpRequest); if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.QUERY) { clonedRequest.query[signingProperties.name] = identity.apiKey; } else if (signingProperties.in === import_types4.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; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js var import_protocol_http8, HttpBearerAuthSigner; var init_httpBearerAuth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() { import_protocol_http8 = __toESM(require_dist_cjs2()); HttpBearerAuthSigner = class { async sign(httpRequest, identity, signingProperties) { const clonedRequest = import_protocol_http8.HttpRequest.clone(httpRequest); 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; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js var NoAuthSigner; var init_noAuth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() { NoAuthSigner = class { async sign(httpRequest, identity, signingProperties) { return httpRequest; } }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js var init_httpAuthSchemes = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() { init_httpApiKeyAuth(); init_httpBearerAuth(); init_noAuth(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider; var init_memoizeIdentityProvider = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() { createIsIdentityExpiredFunction = (expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; EXPIRATION_MS = 3e5; isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0; memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { if (provider === void 0) { return void 0; } const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; let resolved; let pending; let hasResult; let isConstant = false; const coalesceProvider = async (options) => { if (!pending) { pending = normalizedProvider(options); } try { resolved = await pending; hasResult = true; isConstant = false; } finally { pending = void 0; } return resolved; }; if (isExpired === void 0) { return async (options) => { if (!hasResult || (options == 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; }; }; } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js var init_util_identity_and_auth = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() { init_DefaultIdentityProviderConfig(); init_httpAuthSchemes(); init_memoizeIdentityProvider(); } }); // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js var dist_es_exports = {}; __export(dist_es_exports, { DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, EXPIRATION_MS: () => EXPIRATION_MS, HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, HttpBearerAuthSigner: () => HttpBearerAuthSigner, NoAuthSigner: () => NoAuthSigner, createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, createPaginator: () => createPaginator, doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, getHttpSigningPlugin: () => getHttpSigningPlugin, getSmithyContext: () => getSmithyContext, httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, httpSigningMiddleware: () => httpSigningMiddleware, httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, isIdentityExpired: () => isIdentityExpired, memoizeIdentityProvider: () => memoizeIdentityProvider, normalizeProvider: () => normalizeProvider, requestBuilder: () => requestBuilder, setFeature: () => setFeature }); var init_dist_es = __esm({ "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js"() { init_getSmithyContext(); init_middleware_http_auth_scheme(); init_middleware_http_signing(); init_normalizeProvider(); init_createPaginator(); init_requestBuilder2(); init_setFeature(); init_util_identity_and_auth(); } }); // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-cjs/index.js var require_dist_cjs18 = __commonJS({ "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/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, { EndpointCache: () => EndpointCache3, EndpointError: () => EndpointError2, customEndpointFunctions: () => customEndpointFunctions3, isIpAddress: () => isIpAddress2, isValidHostLabel: () => isValidHostLabel, resolveEndpoint: () => resolveEndpoint4 }); module2.exports = __toCommonJS2(src_exports); var _a2; var EndpointCache3 = (_a2 = class { /** * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed * before keys are dropped. * @param [params] - list of params to consider as part of the cache key. * * If the params list is not populated, no caching will happen. * This may be out of order depending on how the object is created and arrives to this class. */ constructor({ size, params }) { this.data = /* @__PURE__ */ new Map(); this.parameters = []; this.capacity = size ?? 50; if (params) { this.parameters = params; } } /** * @param endpointParams - query for endpoint. * @param resolver - provider of the value if not present. * @returns endpoint corresponding to the query. */ get(endpointParams, resolver) { const key = this.hash(endpointParams); if (key === false) { return resolver(); } if (!this.data.has(key)) { if (this.data.size > this.capacity + 10) { const keys = this.data.keys(); let i4 = 0; while (true) { const { value, done } = keys.next(); this.data.delete(value); if (done || ++i4 > 10) { break; } } } this.data.set(key, resolver()); } return this.data.get(key); } size() { return this.data.size; } /** * @returns cache key or false if not cachable. */ hash(endpointParams) { let buffer = ""; const { parameters } = this; if (parameters.length === 0) { return false; } for (const param of parameters) { const val2 = String(endpointParams[param] ?? ""); if (val2.includes("|;")) { return false; } buffer += val2 + "|;"; } return buffer; } }, __name(_a2, "EndpointCache"), _a2); 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 customEndpointFunctions3 = {}; 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 _a3; var EndpointError2 = (_a3 = class extends Error { constructor(message) { super(message); this.name = "EndpointError"; } }, __name(_a3, "EndpointError"), _a3); 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, index6) => { if (typeof acc !== "object") { throw new EndpointError2(`Index '${index6}' in '${path4}' not found in '${JSON.stringify(value)}'`); } else if (Array.isArray(acc)) { return acc[parseInt(index6)]; } return acc[index6]; }, value), "getAttr"); var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet"); var not = /* @__PURE__ */ __name((value) => !value, "not"); var import_types32 = require_dist_cjs(); var DEFAULT_PORTS = { [import_types32.EndpointURLScheme.HTTP]: 80, [import_types32.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(([k3, v6]) => `${k3}=${v6}`).join("&"); return url; } return new URL(value); } catch (error2) { return null; } })(); if (!whatwgURL) { console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); return null; } const urlString = whatwgURL.href; const { host, hostname, pathname, protocol, search } = whatwgURL; if (search) { return null; } const scheme = protocol.slice(0, -1); if (!Object.values(import_types32.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, (c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode"); var endpointFunctions = { booleanEquals, getAttr, isSet, 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 customEndpointFunctions3 && fnSegments[1] != null) { return customEndpointFunctions3[fnSegments[0]][fnSegments[1]](...evaluatedArgs); } return endpointFunctions[fn](...evaluatedArgs); }, "callFunction"); var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => { var _a4, _b; if (assign && assign in options.referenceRecord) { throw new EndpointError2(`'${assign}' is already defined in Reference Record.`); } const value = callFunction(fnArgs, options); (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${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 _a4, _b; const conditionsReferenceRecord = {}; for (const condition of conditions) { const { result, toAssign } = evaluateCondition(condition, { ...options, referenceRecord: { ...options.referenceRecord, ...conditionsReferenceRecord } }); if (!result) {