Preview: bin.cjs
Size: 2.99 MB
/var/www/gtechmarathon2026.bitkit.dk/httpdocs/node_modules/drizzle-kit/bin.cjs
#!/usr/bin/env node
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// ../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js
function assembleStyles() {
const codes = /* @__PURE__ */ new Map();
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\x1B[${style[0]}m`,
close: `\x1B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, "codes", {
value: codes,
enumerable: false
});
styles.color.close = "\x1B[39m";
styles.bgColor.close = "\x1B[49m";
styles.color.ansi = wrapAnsi16();
styles.color.ansi256 = wrapAnsi256();
styles.color.ansi16m = wrapAnsi16m();
styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
Object.defineProperties(styles, {
rgbToAnsi256: {
value(red, green, blue) {
if (red === green && green === blue) {
if (red < 8) {
return 16;
}
if (red > 248) {
return 231;
}
return Math.round((red - 8) / 247 * 24) + 232;
}
return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
},
enumerable: false
},
hexToRgb: {
value(hex) {
const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
if (!matches) {
return [0, 0, 0];
}
let [colorString] = matches;
if (colorString.length === 3) {
colorString = [...colorString].map((character) => character + character).join("");
}
const integer = Number.parseInt(colorString, 16);
return [
/* eslint-disable no-bitwise */
integer >> 16 & 255,
integer >> 8 & 255,
integer & 255
/* eslint-enable no-bitwise */
];
},
enumerable: false
},
hexToAnsi256: {
value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
enumerable: false
},
ansi256ToAnsi: {
value(code) {
if (code < 8) {
return 30 + code;
}
if (code < 16) {
return 90 + (code - 8);
}
let red;
let green;
let blue;
if (code >= 232) {
red = ((code - 232) * 10 + 8) / 255;
green = red;
blue = red;
} else {
code -= 16;
const remainder = code % 36;
red = Math.floor(code / 36) / 5;
green = Math.floor(remainder / 6) / 5;
blue = remainder % 6 / 5;
}
const value = Math.max(red, green, blue) * 2;
if (value === 0) {
return 30;
}
let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
if (value === 2) {
result += 60;
}
return result;
},
enumerable: false
},
rgbToAnsi: {
value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
enumerable: false
},
hexToAnsi: {
value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
enumerable: false
}
});
return styles;
}
var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
var init_ansi_styles = __esm({
"../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
ANSI_BACKGROUND_OFFSET = 10;
wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
gray: [90, 39],
// Alias of `blackBright`
grey: [90, 39],
// Alias of `blackBright`
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgGray: [100, 49],
// Alias of `bgBlackBright`
bgGrey: [100, 49],
// Alias of `bgBlackBright`
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
modifierNames = Object.keys(styles.modifier);
foregroundColorNames = Object.keys(styles.color);
backgroundColorNames = Object.keys(styles.bgColor);
colorNames = [...foregroundColorNames, ...backgroundColorNames];
ansiStyles = assembleStyles();
ansi_styles_default = ansiStyles;
}
});
// ../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix2 + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
function envForceColor() {
if ("FORCE_COLOR" in env) {
if (env.FORCE_COLOR === "true") {
return 1;
}
if (env.FORCE_COLOR === "false") {
return 0;
}
return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== void 0) {
flagForceColor = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
return 3;
}
if (hasFlag("color=256")) {
return 2;
}
}
if ("TF_BUILD" in env && "AGENT_NAME" in env) {
return 1;
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === "dumb") {
return min;
}
if (import_node_process.default.platform === "win32") {
const osRelease = import_node_os.default.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env) {
if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
return 3;
}
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === "truecolor") {
return 3;
}
if (env.TERM === "xterm-kitty") {
return 3;
}
if ("TERM_PROGRAM" in env) {
const version3 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env.TERM_PROGRAM) {
case "iTerm.app": {
return version3 >= 3 ? 3 : 2;
}
case "Apple_Terminal": {
return 2;
}
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ("COLORTERM" in env) {
return 1;
}
return min;
}
function createSupportsColor(stream, options = {}) {
const level = _supportsColor(stream, {
streamIsTTY: stream && stream.isTTY,
...options
});
return translateLevel(level);
}
var import_node_process, import_node_os, import_node_tty, env, flagForceColor, supportsColor, supports_color_default;
var init_supports_color = __esm({
"../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js"() {
import_node_process = __toESM(require("node:process"), 1);
import_node_os = __toESM(require("node:os"), 1);
import_node_tty = __toESM(require("node:tty"), 1);
({ env } = import_node_process.default);
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
flagForceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
flagForceColor = 1;
}
supportsColor = {
stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
};
supports_color_default = supportsColor;
}
});
// ../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js
function stringReplaceAll(string2, substring, replacer) {
let index5 = string2.indexOf(substring);
if (index5 === -1) {
return string2;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = "";
do {
returnValue += string2.slice(endIndex, index5) + substring + replacer;
endIndex = index5 + substringLength;
index5 = string2.indexOf(substring, endIndex);
} while (index5 !== -1);
returnValue += string2.slice(endIndex);
return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string2, prefix2, postfix, index5) {
let endIndex = 0;
let returnValue = "";
do {
const gotCR = string2[index5 - 1] === "\r";
returnValue += string2.slice(endIndex, gotCR ? index5 - 1 : index5) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix;
endIndex = index5 + 1;
index5 = string2.indexOf("\n", endIndex);
} while (index5 !== -1);
returnValue += string2.slice(endIndex);
return returnValue;
}
var init_utilities = __esm({
"../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js"() {
}
});
// ../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/index.js
function createChalk(options) {
return chalkFactory(options);
}
var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default;
var init_source = __esm({
"../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/index.js"() {
init_ansi_styles();
init_supports_color();
init_utilities();
({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
GENERATOR = Symbol("GENERATOR");
STYLER = Symbol("STYLER");
IS_EMPTY = Symbol("IS_EMPTY");
levelMapping = [
"ansi",
"ansi",
"ansi256",
"ansi16m"
];
styles2 = /* @__PURE__ */ Object.create(null);
applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error("The `level` option should be an integer from 0 to 3");
}
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === void 0 ? colorLevel : options.level;
};
chalkFactory = (options) => {
const chalk2 = (...strings) => strings.join(" ");
applyOptions(chalk2, options);
Object.setPrototypeOf(chalk2, createChalk.prototype);
return chalk2;
};
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansi_styles_default)) {
styles2[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
Object.defineProperty(this, styleName, { value: builder });
return builder;
}
};
}
styles2.visible = {
get() {
const builder = createBuilder(this, this[STYLER], true);
Object.defineProperty(this, "visible", { value: builder });
return builder;
}
};
getModelAnsi = (model, level, type, ...arguments_) => {
if (model === "rgb") {
if (level === "ansi16m") {
return ansi_styles_default[type].ansi16m(...arguments_);
}
if (level === "ansi256") {
return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
}
return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
}
if (model === "hex") {
return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
}
return ansi_styles_default[type][model](...arguments_);
};
usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
styles2[model] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
styles2[bgModel] = {
get() {
const { level } = this;
return function(...arguments_) {
const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
return createBuilder(this, styler, this[IS_EMPTY]);
};
}
};
}
proto = Object.defineProperties(() => {
}, {
...styles2,
level: {
enumerable: true,
get() {
return this[GENERATOR].level;
},
set(level) {
this[GENERATOR].level = level;
}
}
});
createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === void 0) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent
};
};
createBuilder = (self2, _styler, _isEmpty) => {
const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
Object.setPrototypeOf(builder, proto);
builder[GENERATOR] = self2;
builder[STYLER] = _styler;
builder[IS_EMPTY] = _isEmpty;
return builder;
};
applyStyle = (self2, string2) => {
if (self2.level <= 0 || !string2) {
return self2[IS_EMPTY] ? "" : string2;
}
let styler = self2[STYLER];
if (styler === void 0) {
return string2;
}
const { openAll, closeAll } = styler;
if (string2.includes("\x1B")) {
while (styler !== void 0) {
string2 = stringReplaceAll(string2, styler.close, styler.open);
styler = styler.parent;
}
}
const lfIndex = string2.indexOf("\n");
if (lfIndex !== -1) {
string2 = stringEncaseCRLFWithFirstIndex(string2, closeAll, openAll, lfIndex);
}
return openAll + string2 + closeAll;
};
Object.defineProperties(createChalk.prototype, styles2);
chalk = createChalk();
chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
source_default = chalk;
}
});
// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json
var require_package = __commonJS({
"../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json"(exports2, module2) {
module2.exports = {
name: "dotenv",
version: "16.4.5",
description: "Loads environment variables from .env file",
main: "lib/main.js",
types: "lib/main.d.ts",
exports: {
".": {
types: "./lib/main.d.ts",
require: "./lib/main.js",
default: "./lib/main.js"
},
"./config": "./config.js",
"./config.js": "./config.js",
"./lib/env-options": "./lib/env-options.js",
"./lib/env-options.js": "./lib/env-options.js",
"./lib/cli-options": "./lib/cli-options.js",
"./lib/cli-options.js": "./lib/cli-options.js",
"./package.json": "./package.json"
},
scripts: {
"dts-check": "tsc --project tests/types/tsconfig.json",
lint: "standard",
"lint-readme": "standard-markdown",
pretest: "npm run lint && npm run dts-check",
test: "tap tests/*.js --100 -Rspec",
"test:coverage": "tap --coverage-report=lcov",
prerelease: "npm test",
release: "standard-version"
},
repository: {
type: "git",
url: "git://github.com/motdotla/dotenv.git"
},
funding: "https://dotenvx.com",
keywords: [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
readmeFilename: "README.md",
license: "BSD-2-Clause",
devDependencies: {
"@definitelytyped/dtslint": "^0.0.133",
"@types/node": "^18.11.3",
decache: "^4.6.1",
sinon: "^14.0.1",
standard: "^17.0.0",
"standard-markdown": "^7.1.0",
"standard-version": "^9.5.0",
tap: "^16.3.0",
tar: "^6.1.11",
typescript: "^4.8.4"
},
engines: {
node: ">=12"
},
browser: {
fs: false
}
};
}
});
// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js
var require_main = __commonJS({
"../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js"(exports2, module2) {
var fs7 = require("fs");
var path4 = require("path");
var os3 = require("os");
var crypto7 = require("crypto");
var packageJson = require_package();
var version3 = packageJson.version;
var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
function parse5(src) {
const obj = {};
let lines = src.toString();
lines = lines.replace(/\r\n?/mg, "\n");
let match2;
while ((match2 = LINE.exec(lines)) != null) {
const key = match2[1];
let value = match2[2] || "";
value = value.trim();
const maybeQuote = value[0];
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
if (maybeQuote === '"') {
value = value.replace(/\\n/g, "\n");
value = value.replace(/\\r/g, "\r");
}
obj[key] = value;
}
return obj;
}
function _parseVault(options) {
const vaultPath = _vaultPath(options);
const result = DotenvModule.configDotenv({ path: vaultPath });
if (!result.parsed) {
const err2 = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
err2.code = "MISSING_DATA";
throw err2;
}
const keys = _dotenvKey(options).split(",");
const length = keys.length;
let decrypted;
for (let i2 = 0; i2 < length; i2++) {
try {
const key = keys[i2].trim();
const attrs = _instructions(result, key);
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
break;
} catch (error2) {
if (i2 + 1 >= length) {
throw error2;
}
}
}
return DotenvModule.parse(decrypted);
}
function _log(message) {
console.log(`[dotenv@${version3}][INFO] ${message}`);
}
function _warn(message) {
console.log(`[dotenv@${version3}][WARN] ${message}`);
}
function _debug(message) {
console.log(`[dotenv@${version3}][DEBUG] ${message}`);
}
function _dotenvKey(options) {
if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
return options.DOTENV_KEY;
}
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY;
}
return "";
}
function _instructions(result, dotenvKey) {
let uri;
try {
uri = new URL(dotenvKey);
} catch (error2) {
if (error2.code === "ERR_INVALID_URL") {
const err2 = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
}
throw error2;
}
const key = uri.password;
if (!key) {
const err2 = new Error("INVALID_DOTENV_KEY: Missing key part");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
}
const environment = uri.searchParams.get("environment");
if (!environment) {
const err2 = new Error("INVALID_DOTENV_KEY: Missing environment part");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
}
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
const ciphertext = result.parsed[environmentKey];
if (!ciphertext) {
const err2 = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
err2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
throw err2;
}
return { ciphertext, key };
}
function _vaultPath(options) {
let possibleVaultPath = null;
if (options && options.path && options.path.length > 0) {
if (Array.isArray(options.path)) {
for (const filepath of options.path) {
if (fs7.existsSync(filepath)) {
possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
}
}
} else {
possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
}
} else {
possibleVaultPath = path4.resolve(process.cwd(), ".env.vault");
}
if (fs7.existsSync(possibleVaultPath)) {
return possibleVaultPath;
}
return null;
}
function _resolveHome(envPath) {
return envPath[0] === "~" ? path4.join(os3.homedir(), envPath.slice(1)) : envPath;
}
function _configVault(options) {
_log("Loading env from encrypted .env.vault");
const parsed = DotenvModule._parseVault(options);
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
DotenvModule.populate(processEnv, parsed, options);
return { parsed };
}
function configDotenv(options) {
const dotenvPath = path4.resolve(process.cwd(), ".env");
let encoding = "utf8";
const debug = Boolean(options && options.debug);
if (options && options.encoding) {
encoding = options.encoding;
} else {
if (debug) {
_debug("No encoding is specified. UTF-8 is used by default");
}
}
let optionPaths = [dotenvPath];
if (options && options.path) {
if (!Array.isArray(options.path)) {
optionPaths = [_resolveHome(options.path)];
} else {
optionPaths = [];
for (const filepath of options.path) {
optionPaths.push(_resolveHome(filepath));
}
}
}
let lastError;
const parsedAll = {};
for (const path5 of optionPaths) {
try {
const parsed = DotenvModule.parse(fs7.readFileSync(path5, { encoding }));
DotenvModule.populate(parsedAll, parsed, options);
} catch (e2) {
if (debug) {
_debug(`Failed to load ${path5} ${e2.message}`);
}
lastError = e2;
}
}
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
DotenvModule.populate(processEnv, parsedAll, options);
if (lastError) {
return { parsed: parsedAll, error: lastError };
} else {
return { parsed: parsedAll };
}
}
function config(options) {
if (_dotenvKey(options).length === 0) {
return DotenvModule.configDotenv(options);
}
const vaultPath = _vaultPath(options);
if (!vaultPath) {
_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
return DotenvModule.configDotenv(options);
}
return DotenvModule._configVault(options);
}
function decrypt(encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), "hex");
let ciphertext = Buffer.from(encrypted, "base64");
const nonce = ciphertext.subarray(0, 12);
const authTag = ciphertext.subarray(-16);
ciphertext = ciphertext.subarray(12, -16);
try {
const aesgcm = crypto7.createDecipheriv("aes-256-gcm", key, nonce);
aesgcm.setAuthTag(authTag);
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
} catch (error2) {
const isRange = error2 instanceof RangeError;
const invalidKeyLength = error2.message === "Invalid key length";
const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
if (isRange || invalidKeyLength) {
const err2 = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
} else if (decryptionFailed) {
const err2 = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
err2.code = "DECRYPTION_FAILED";
throw err2;
} else {
throw error2;
}
}
}
function populate(processEnv, parsed, options = {}) {
const debug = Boolean(options && options.debug);
const override = Boolean(options && options.override);
if (typeof parsed !== "object") {
const err2 = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
err2.code = "OBJECT_REQUIRED";
throw err2;
}
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key];
}
if (debug) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`);
} else {
_debug(`"${key}" is already defined and was NOT overwritten`);
}
}
} else {
processEnv[key] = parsed[key];
}
}
}
var DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse: parse5,
populate
};
module2.exports.configDotenv = DotenvModule.configDotenv;
module2.exports._configVault = DotenvModule._configVault;
module2.exports._parseVault = DotenvModule._parseVault;
module2.exports.config = DotenvModule.config;
module2.exports.decrypt = DotenvModule.decrypt;
module2.exports.parse = DotenvModule.parse;
module2.exports.populate = DotenvModule.populate;
module2.exports = DotenvModule;
}
});
// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/env-options.js
var require_env_options = __commonJS({
"../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/env-options.js"(exports2, module2) {
var options = {};
if (process.env.DOTENV_CONFIG_ENCODING != null) {
options.encoding = process.env.DOTENV_CONFIG_ENCODING;
}
if (process.env.DOTENV_CONFIG_PATH != null) {
options.path = process.env.DOTENV_CONFIG_PATH;
}
if (process.env.DOTENV_CONFIG_DEBUG != null) {
options.debug = process.env.DOTENV_CONFIG_DEBUG;
}
if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
options.override = process.env.DOTENV_CONFIG_OVERRIDE;
}
if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
}
module2.exports = options;
}
});
// ../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/cli-options.js
var require_cli_options = __commonJS({
"../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/cli-options.js"(exports2, module2) {
var re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/;
module2.exports = function optionMatcher(args) {
return args.reduce(function(acc, cur) {
const matches = cur.match(re);
if (matches) {
acc[matches[1]] = matches[2];
}
return acc;
}, {});
};
}
});
// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js
var require_readline = __commonJS({
"../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.prepareReadLine = void 0;
var prepareReadLine = () => {
const stdin = process.stdin;
const stdout = process.stdout;
const readline = require("readline");
const rl = readline.createInterface({
input: stdin,
escapeCodeTimeout: 50
});
readline.emitKeypressEvents(stdin, rl);
return {
stdin,
stdout,
closable: rl
};
};
exports2.prepareReadLine = prepareReadLine;
}
});
// ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
var require_src = __commonJS({
"../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module2) {
"use strict";
var ESC = "\x1B";
var CSI = `${ESC}[`;
var beep = "\x07";
var cursor = {
to(x2, y) {
if (!y)
return `${CSI}${x2 + 1}G`;
return `${CSI}${y + 1};${x2 + 1}H`;
},
move(x2, y) {
let ret = "";
if (x2 < 0)
ret += `${CSI}${-x2}D`;
else if (x2 > 0)
ret += `${CSI}${x2}C`;
if (y < 0)
ret += `${CSI}${-y}A`;
else if (y > 0)
ret += `${CSI}${y}B`;
return ret;
},
up: (count = 1) => `${CSI}${count}A`,
down: (count = 1) => `${CSI}${count}B`,
forward: (count = 1) => `${CSI}${count}C`,
backward: (count = 1) => `${CSI}${count}D`,
nextLine: (count = 1) => `${CSI}E`.repeat(count),
prevLine: (count = 1) => `${CSI}F`.repeat(count),
left: `${CSI}G`,
hide: `${CSI}?25l`,
show: `${CSI}?25h`,
save: `${ESC}7`,
restore: `${ESC}8`
};
var scroll = {
up: (count = 1) => `${CSI}S`.repeat(count),
down: (count = 1) => `${CSI}T`.repeat(count)
};
var erase = {
screen: `${CSI}2J`,
up: (count = 1) => `${CSI}1J`.repeat(count),
down: (count = 1) => `${CSI}J`.repeat(count),
line: `${CSI}2K`,
lineEnd: `${CSI}K`,
lineStart: `${CSI}1K`,
lines(count) {
let clear = "";
for (let i2 = 0; i2 < count; i2++)
clear += this.line + (i2 < count - 1 ? cursor.up() : "");
if (count)
clear += cursor.left;
return clear;
}
};
module2.exports = { cursor, scroll, erase, beep };
}
});
// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js
var require_utils = __commonJS({
"../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.clear = void 0;
var sisteransi_1 = require_src();
var strip = (str) => {
const pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
].join("|");
const RGX = new RegExp(pattern, "g");
return typeof str === "string" ? str.replace(RGX, "") : str;
};
var stringWidth = (str) => [...strip(str)].length;
var clear = function(prompt, perLine) {
if (!perLine)
return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
let rows = 0;
const lines = prompt.split(/\r?\n/);
for (let line of lines) {
rows += 1 + Math.floor(Math.max(stringWidth(line) - 1, 0) / perLine);
}
return sisteransi_1.erase.lines(rows);
};
exports2.clear = clear;
}
});
// ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
var require_lodash = __commonJS({
"../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) {
var FUNC_ERROR_TEXT = "Expected a function";
var NAN = 0 / 0;
var symbolTag = "[object Symbol]";
var reTrim = /^\s+|\s+$/g;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal || freeSelf || Function("return this")();
var objectProto = Object.prototype;
var objectToString = objectProto.toString;
var nativeMax = Math.max;
var nativeMin = Math.min;
var now = function() {
return root.Date.now();
};
function debounce(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
if (typeof func != "function") {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = "maxWait" in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
lastArgs = lastThis = void 0;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
lastInvokeTime = time;
timerId = setTimeout(timerExpired, wait);
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = void 0;
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = void 0;
return result;
}
function cancel() {
if (timerId !== void 0) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = void 0;
}
function flush() {
return timerId === void 0 ? result : trailingEdge(now());
}
function debounced() {
var time = now(), isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === void 0) {
return leadingEdge(lastCallTime);
}
if (maxing) {
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === void 0) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
function throttle(func, wait, options) {
var leading = true, trailing = true;
if (typeof func != "function") {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = "leading" in options ? !!options.leading : leading;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
"leading": leading,
"maxWait": wait,
"trailing": trailing
});
}
function isObject(value) {
var type = typeof value;
return !!value && (type == "object" || type == "function");
}
function isObjectLike(value) {
return !!value && typeof value == "object";
}
function isSymbol2(value) {
return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
}
function toNumber(value) {
if (typeof value == "number") {
return value;
}
if (isSymbol2(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject(other) ? other + "" : other;
}
if (typeof value != "string") {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, "");
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
module2.exports = throttle;
}
});
// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
var require_hanji = __commonJS({
"../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports2) {
"use strict";
var __awaiter3 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve2) {
resolve2(value);
});
}
return new (P || (P = Promise))(function(resolve2, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e2) {
reject(e2);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e2) {
reject(e2);
}
}
function step(result) {
result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault3 = exports2 && exports2.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.onTerminate = exports2.renderWithTask = exports2.render = exports2.TaskTerminal = exports2.TaskView = exports2.Terminal = exports2.deferred = exports2.SelectState = exports2.Prompt = void 0;
var readline_1 = require_readline();
var sisteransi_1 = require_src();
var utils_1 = require_utils();
var lodash_throttle_1 = __importDefault3(require_lodash());
var Prompt3 = class {
constructor() {
this.attachCallbacks = [];
this.detachCallbacks = [];
this.inputCallbacks = [];
}
requestLayout() {
this.terminal.requestLayout();
}
on(type, callback) {
if (type === "attach") {
this.attachCallbacks.push(callback);
} else if (type === "detach") {
this.detachCallbacks.push(callback);
} else if (type === "input") {
this.inputCallbacks.push(callback);
}
}
attach(terminal) {
this.terminal = terminal;
this.attachCallbacks.forEach((it) => it(terminal));
}
detach(terminal) {
this.detachCallbacks.forEach((it) => it(terminal));
this.terminal = void 0;
}
input(str, key) {
this.inputCallbacks.forEach((it) => it(str, key));
}
};
exports2.Prompt = Prompt3;
var SelectState3 = class {
constructor(items) {
this.items = items;
this.selectedIdx = 0;
}
bind(prompt) {
prompt.on("input", (str, key) => {
const invalidate = this.consume(str, key);
if (invalidate)
prompt.requestLayout();
});
}
consume(str, key) {
if (!key)
return false;
if (key.name === "down") {
this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
return true;
}
if (key.name === "up") {
this.selectedIdx -= 1;
this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
return true;
}
return false;
}
};
exports2.SelectState = SelectState3;
var deferred = () => {
let resolve2;
let reject;
const promise = new Promise((res, rej) => {
resolve2 = res;
reject = rej;
});
return {
resolve: resolve2,
reject,
promise
};
};
exports2.deferred = deferred;
var Terminal = class {
constructor(view4, stdin, stdout, closable) {
this.view = view4;
this.stdin = stdin;
this.stdout = stdout;
this.closable = closable;
this.text = "";
this.status = "idle";
if (this.stdin.isTTY)
this.stdin.setRawMode(true);
const keypress = (str, key) => {
if (key.name === "c" && key.ctrl === true) {
this.requestLayout();
this.view.detach(this);
this.tearDown(keypress);
if (terminateHandler) {
terminateHandler(this.stdin, this.stdout);
return;
}
this.stdout.write(`
^C
`);
process.exit(1);
}
if (key.name === "escape") {
this.status = "aborted";
this.requestLayout();
this.view.detach(this);
this.tearDown(keypress);
this.resolve({ status: "aborted", data: void 0 });
return;
}
if (key.name === "return") {
this.status = "submitted";
this.requestLayout();
this.view.detach(this);
this.tearDown(keypress);
this.resolve({ status: "submitted", data: this.view.result() });
return;
}
view4.input(str, key);
};
this.stdin.on("keypress", keypress);
this.view.attach(this);
const { resolve: resolve2, promise } = (0, exports2.deferred)();
this.resolve = resolve2;
this.promise = promise;
this.renderFunc = (0, lodash_throttle_1.default)((str) => {
this.stdout.write(str);
});
}
tearDown(keypress) {
this.stdout.write(sisteransi_1.cursor.show);
this.stdin.removeListener("keypress", keypress);
if (this.stdin.isTTY)
this.stdin.setRawMode(false);
this.closable.close();
}
result() {
return this.promise;
}
toggleCursor(state) {
if (state === "hide") {
this.stdout.write(sisteransi_1.cursor.hide);
} else {
this.stdout.write(sisteransi_1.cursor.show);
}
}
requestLayout() {
const string2 = this.view.render(this.status);
const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
this.text = string2;
this.renderFunc(`${clearPrefix}${string2}`);
}
};
exports2.Terminal = Terminal;
var TaskView2 = class {
constructor() {
this.attachCallbacks = [];
this.detachCallbacks = [];
}
requestLayout() {
this.terminal.requestLayout();
}
attach(terminal) {
this.terminal = terminal;
this.attachCallbacks.forEach((it) => it(terminal));
}
detach(terminal) {
this.detachCallbacks.forEach((it) => it(terminal));
this.terminal = void 0;
}
on(type, callback) {
if (type === "attach") {
this.attachCallbacks.push(callback);
} else if (type === "detach") {
this.detachCallbacks.push(callback);
}
}
};
exports2.TaskView = TaskView2;
var TaskTerminal = class {
constructor(view4, stdout) {
this.view = view4;
this.stdout = stdout;
this.text = "";
this.view.attach(this);
}
requestLayout() {
const string2 = this.view.render("pending");
const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
this.text = string2;
this.stdout.write(`${clearPrefix}${string2}`);
}
clear() {
const string2 = this.view.render("done");
this.view.detach(this);
const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
this.stdout.write(`${clearPrefix}${string2}`);
}
};
exports2.TaskTerminal = TaskTerminal;
function render10(view4) {
const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
if (view4 instanceof Prompt3) {
const terminal = new Terminal(view4, stdin, stdout, closable);
terminal.requestLayout();
return terminal.result();
}
stdout.write(`${view4}
`);
closable.close();
return;
}
exports2.render = render10;
function renderWithTask7(view4, task) {
return __awaiter3(this, void 0, void 0, function* () {
const terminal = new TaskTerminal(view4, process.stdout);
terminal.requestLayout();
const result = yield task;
terminal.clear();
return result;
});
}
exports2.renderWithTask = renderWithTask7;
var terminateHandler;
function onTerminate(callback) {
terminateHandler = callback;
}
exports2.onTerminate = onTerminate;
}
});
// ../node_modules/.pnpm/zod@3.23.7/node_modules/zod/lib/index.mjs
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === errorMap ? void 0 : errorMap
// then global default map
].filter((x2) => !!x2)
});
ctx.common.issues.push(issue);
}
function __classPrivateFieldGet(receiver, state, kind, f3) {
if (kind === "a" && !f3)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f3) {
if (kind === "m")
throw new TypeError("Private method is not writable");
if (kind === "a" && !f3)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
var _a, _b;
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
};
return { errorMap: customMap, description };
}
function timeRegexSource(args) {
let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
if (args.precision) {
regex = `${regex}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
regex = `${regex}(\\.\\d+)?`;
}
return regex;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version3) {
if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
return true;
}
if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function floatSafeRemainder(val2, step) {
const valDecCount = (val2.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = parseInt(val2.toFixed(decCount).replace(".", ""));
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / Math.pow(10, decCount);
}
function deepPartialify(schema6) {
if (schema6 instanceof ZodObject) {
const newShape = {};
for (const key in schema6.shape) {
const fieldSchema = schema6.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema6._def,
shape: () => newShape
});
} else if (schema6 instanceof ZodArray) {
return new ZodArray({
...schema6._def,
type: deepPartialify(schema6.element)
});
} else if (schema6 instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema6.unwrap()));
} else if (schema6 instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema6.unwrap()));
} else if (schema6 instanceof ZodTuple) {
return ZodTuple.create(schema6.items.map((item) => deepPartialify(item)));
} else {
return schema6;
}
}
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index5 = 0; index5 < a.length; index5++) {
const itemA = a[index5];
const itemB = b[index5];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
function custom(check2, params = {}, fatal) {
if (check2)
return ZodAny.create().superRefine((data, ctx) => {
var _a, _b;
if (!check2(data)) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
const p2 = typeof p === "string" ? { message: p } : p;
ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
}
});
return ZodAny.create();
}
var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, quotelessJson, ZodError, errorMap, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv6Regex, base64Regex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER, z;
var init_lib = __esm({
"../node_modules/.pnpm/zod@3.23.7/node_modules/zod/lib/index.mjs"() {
(function(util2) {
util2.assertEqual = (val2) => val2;
function assertIs(_arg) {
}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e2) {
return obj[e2];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return void 0;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && isFinite(val2) && Math.floor(val2) === val2;
function joinValues(array2, separator = " | ") {
return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_2, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
// second overwrites first
};
};
})(objectUtil || (objectUtil = {}));
ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
getParsedType = (data) => {
const t2 = typeof data;
switch (t2) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
ZodError = class _ZodError extends Error {
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
get errors() {
return this.issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error2) => {
for (const issue of error2.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i2 = 0;
while (i2 < issue.path.length) {
const el = issue.path[i2];
const terminal = i2 === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i2++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof _ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error2 = new ZodError(issues);
return error2;
};
errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
overrideErrorMap = errorMap;
makeIssue = (params) => {
const { data, path: path4, errorMaps, issueData } = params;
const fullPath = [...path4, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0) {
return {
...issueData,
path: fullPath,
message: issueData.message
};
}
let errorMessage = "";
const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
EMPTY_PATH = [];
ParseStatus = class _ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s2 of results) {
if (s2.status === "aborted")
return INVALID;
if (s2.status === "dirty")
status.dirty();
arrayValue.push(s2.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return _ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
};
INVALID = Object.freeze({
status: "aborted"
});
DIRTY = (value) => ({ status: "dirty", value });
OK = (value) => ({ status: "valid", value });
isAborted = (x2) => x2.status === "aborted";
isDirty = (x2) => x2.status === "dirty";
isValid = (x2) => x2.status === "valid";
isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
ParseInputLazyPath = class {
constructor(parent, value, path4, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path4;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (this._key instanceof Array) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
};
handleResult = (ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error2 = new ZodError(ctx.common.issues);
this._error = error2;
return this._error;
}
};
}
};
ZodType = class {
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
}
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success)
return result.data;
throw result.error;
}
safeParse(data, params) {
var _a;
const ctx = {
common: {
issues: [],
async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success)
return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
async: true
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check2, message) {
const getIssueProperties = (val2) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val2);
} else {
return message;
}
};
return this._refinement((val2, ctx) => {
const result = check2(val2);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val2)
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check2, refinementData) {
return this._refinement((val2, ctx) => {
if (!check2(val2)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this, this._def);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
cuidRegex = /^c[^\s-]{8,}$/i;
cuid2Regex = /^[0-9a-z]+$/;
ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
nanoidRegex = /^[a-z0-9_-]{21}$/i;
durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
_emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
dateRegex = new RegExp(`^${dateRegexSource}$`);
ZodString = class _ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check2 of this._def.checks) {
if (check2.kind === "min") {
if (input.data.length < check2.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check2.value,
type: "string",
inclusive: true,
exact: false,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "max") {
if (input.data.length > check2.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check2.value,
type: "string",
inclusive: true,
exact: false,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "length") {
const tooBig = input.data.length > check2.value;
const tooSmall = input.data.length < check2.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check2.value,
type: "string",
inclusive: true,
exact: true,
message: check2.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check2.value,
type: "string",
inclusive: true,
exact: true,
message: check2.message
});
}
status.dirty();
}
} else if (check2.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "url") {
try {
new URL(input.data);
} catch (_a) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "regex") {
check2.regex.lastIndex = 0;
const testResult = check2.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "trim") {
input.data = input.data.trim();
} else if (check2.kind === "includes") {
if (!input.data.includes(check2.value, check2.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check2.value, position: check2.position },
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check2.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check2.kind === "startsWith") {
if (!input.data.startsWith(check2.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check2.value },
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "endsWith") {
if (!input.data.endsWith(check2.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check2.value },
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "datetime") {
const regex = datetimeRegex(check2);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "time") {
const regex = timeRegex(check2);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "ip") {
if (!isValidIP(input.data, check2.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check2.message
});
status.dirty();
}
} else {
util.assertNever(check2);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check2) {
return new _ZodString({
...this._def,
checks: [...this._def.checks, check2]
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
nanoid(message) {
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
base64(message) {
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
datetime(options) {
var _a, _b;
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck({
kind: "datetime",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options
});
}
return this._addCheck({
kind: "time",
precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
duration(message) {
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options === null || options === void 0 ? void 0 : options.position,
...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new _ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodString.create = (params) => {
var _a;
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
...processCreateParams(params)
});
};
ZodNumber = class _ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check2 of this._def.checks) {
if (check2.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "min") {
const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check2.value,
type: "number",
inclusive: check2.inclusive,
exact: false,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "max") {
const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check2.value,
type: "number",
inclusive: check2.inclusive,
exact: false,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check2.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check2.value,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check2.message
});
status.dirty();
}
} else {
util.assertNever(check2);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check2) {
return new _ZodNumber({
...this._def,
checks: [...this._def.checks, check2]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null, min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params)
});
};
ZodBigInt = class _ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
input.data = BigInt(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check2 of this._def.checks) {
if (check2.kind === "min") {
const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check2.value,
inclusive: check2.inclusive,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "max") {
const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check2.value,
inclusive: check2.inclusive,
message: check2.message
});
status.dirty();
}
} else if (check2.kind === "multipleOf") {
if (input.data % check2.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check2.value,
message: check2.message
});
status.dirty();
}
} else {
util.assertNever(check2);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
});
}
_addCheck(check2) {
return new _ZodBigInt({
...this._def,
checks: [...this._def.checks, check2]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
var _a;
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
...processCreateParams(params)
});
};
ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params)
});
};
ZodDate = class _ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check2 of this._def.checks) {
if (check2.kind === "min") {
if (input.data.getTime() < check2.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check2.message,
inclusive: true,
exact: false,
minimum: check2.value,
type: "date"
});
status.dirty();
}
} else if (check2.kind === "max") {
if (input.data.getTime() > check2.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check2.message,
inclusive: true,
exact: false,
maximum: check2.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check2);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check2) {
return new _ZodDate({
...this._def,
checks: [...this._def.checks, check2]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
ZodArray = class _ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i2) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
})).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i2) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new _ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) }
});
}
max(maxLength, message) {
return new _ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) }
});
}
length(len, message) {
return new _ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) }
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema6, params) => {
return new ZodArray({
type: schema6,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
ZodObject = class _ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
return this._cached = { shape, keys };
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip")
;
else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(
new ParseInputLazyPath(ctx, value, ctx.path, key)
//, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) {
return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new _ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? {
errorMap: (issue, ctx) => {
var _a, _b, _c, _d;
const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
};
return {
message: defaultError
};
}
} : {}
});
}
strip() {
return new _ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new _ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new _ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new _ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema6) {
return this.augment({ [key]: schema6 });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index5) {
return new _ZodObject({
...this._def,
catchall: index5
});
}
pick(mask) {
const shape = {};
util.objectKeys(mask).forEach((key) => {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
});
return new _ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
util.objectKeys(this.shape).forEach((key) => {
if (!mask[key]) {
shape[key] = this.shape[key];
}
});
return new _ZodObject({
...this._def,
shape: () => shape
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
});
return new _ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
});
return new _ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
} else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types3, params) => {
return new ZodUnion({
options: types3,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return util.objectValues(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [void 0];
} else if (type instanceof ZodNull) {
return [null];
} else if (type instanceof ZodOptional) {
return [void 0, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodNullable) {
return [null, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodBranded) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodReadonly) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodCatch) {
return getDiscriminator(type._def.innerType);
} else {
return [];
}
};
ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new _ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
};
ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
ZodTuple = class _ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema6 = this._def.items[itemIndex] || this._def.rest;
if (!schema6)
return null;
return schema6._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x2) => !!x2);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new _ZodTuple({
...this._def,
rest
});
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
ZodRecord = class _ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new _ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
}
return new _ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
};
ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index5) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index5, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index5, "value"]))
};
});
if (ctx.common.async) {
const finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
ZodSet = class _ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element of elements2) {
if (element.status === "aborted")
return INVALID;
if (element.status === "dirty")
status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new _ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new _ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
ZodFunction = class _ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error2) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x2) => !!x2),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error2
}
});
}
function makeReturnsIssue(returns, error2) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x2) => !!x2),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error2
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error2 = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => {
error2.addIssue(makeArgsIssue(args, e2));
throw error2;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
error2.addIssue(makeReturnsIssue(result, e2));
throw error2;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new _ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new _ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new _ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
};
ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
ZodEnum = class _ZodEnum extends ZodType {
constructor() {
super(...arguments);
_ZodEnum_cache.set(this, void 0);
}
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
}
if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val2 of this._def.values) {
enumValues[val2] = val2;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val2 of this._def.values) {
enumValues[val2] = val2;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val2 of this._def.values) {
enumValues[val2] = val2;
}
return enumValues;
}
extract(values, newDef = this._def) {
return _ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
};
_ZodEnum_cache = /* @__PURE__ */ new WeakMap();
ZodEnum.create = createZodEnum;
ZodNativeEnum = class extends ZodType {
constructor() {
super(...arguments);
_ZodNativeEnum_cache.set(this, void 0);
}
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
__classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
}
if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema6, params) => {
return new ZodPromise({
type: schema6,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then(async (processed2) => {
if (status.value === "aborted")
return INVALID;
const result = await this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
});
} else {
if (status.value === "aborted")
return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted")
return INVALID;
if (result.status === "dirty")
return DIRTY(result.value);
if (status.value === "dirty")
return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return base;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid(base))
return base;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
});
}
}
util.assertNever(effect);
}
};
ZodEffects.create = (schema6, effect, params) => {
return new ZodEffects({
schema: schema6,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema6, params) => {
return new ZodEffects({
schema: schema6,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
ZodOptional = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(void 0);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
ZodNullable = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
ZodNaN = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
BRAND = Symbol("zod_brand");
ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
ZodPipeline = class _ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a, b) {
return new _ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
ZodReadonly = class extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
late = {
object: ZodObject.lazycreate
};
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
stringType = ZodString.create;
numberType = ZodNumber.create;
nanType = ZodNaN.create;
bigIntType = ZodBigInt.create;
booleanType = ZodBoolean.create;
dateType = ZodDate.create;
symbolType = ZodSymbol.create;
undefinedType = ZodUndefined.create;
nullType = ZodNull.create;
anyType = ZodAny.create;
unknownType = ZodUnknown.create;
neverType = ZodNever.create;
voidType = ZodVoid.create;
arrayType = ZodArray.create;
objectType = ZodObject.create;
strictObjectType = ZodObject.strictCreate;
unionType = ZodUnion.create;
discriminatedUnionType = ZodDiscriminatedUnion.create;
intersectionType = ZodIntersection.create;
tupleType = ZodTuple.create;
recordType = ZodRecord.create;
mapType = ZodMap.create;
setType = ZodSet.create;
functionType = ZodFunction.create;
lazyType = ZodLazy.create;
literalType = ZodLiteral.create;
enumType = ZodEnum.create;
nativeEnumType = ZodNativeEnum.create;
promiseType = ZodPromise.create;
effectsType = ZodEffects.create;
optionalType = ZodOptional.create;
nullableType = ZodNullable.create;
preprocessType = ZodEffects.createWithPreprocess;
pipelineType = ZodPipeline.create;
ostring = () => stringType().optional();
onumber = () => numberType().optional();
oboolean = () => booleanType().optional();
coerce = {
string: (arg) => ZodString.create({ ...arg, coerce: true }),
number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
boolean: (arg) => ZodBoolean.create({
...arg,
coerce: true
}),
bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
date: (arg) => ZodDate.create({ ...arg, coerce: true })
};
NEVER = INVALID;
z = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap,
getErrorMap,
makeIssue,
EMPTY_PATH,
addIssueToContext,
ParseStatus,
INVALID,
DIRTY,
OK,
isAborted,
isDirty,
isValid,
isAsync,
get util() {
return util;
},
get objectUtil() {
return objectUtil;
},
ZodParsedType,
getParsedType,
ZodType,
datetimeRegex,
ZodString,
ZodNumber,
ZodBigInt,
ZodBoolean,
ZodDate,
ZodSymbol,
ZodUndefined,
ZodNull,
ZodAny,
ZodUnknown,
ZodNever,
ZodVoid,
ZodArray,
ZodObject,
ZodUnion,
ZodDiscriminatedUnion,
ZodIntersection,
ZodTuple,
ZodRecord,
ZodMap,
ZodSet,
ZodFunction,
ZodLazy,
ZodLiteral,
ZodEnum,
ZodNativeEnum,
ZodPromise,
ZodEffects,
ZodTransformer: ZodEffects,
ZodOptional,
ZodNullable,
ZodDefault,
ZodCatch,
ZodNaN,
BRAND,
ZodBranded,
ZodPipeline,
ZodReadonly,
custom,
Schema: ZodType,
ZodSchema: ZodType,
late,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind;
},
coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
"enum": enumType,
"function": functionType,
"instanceof": instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
"null": nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean,
onumber,
optional: optionalType,
ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
"undefined": undefinedType,
union: unionType,
unknown: unknownType,
"void": voidType,
NEVER,
ZodIssueCode,
quotelessJson,
ZodError
});
}
});
// src/global.ts
function assertUnreachable(x2) {
throw new Error("Didn't expect to get here");
}
function softAssertUnreachable(x2) {
return null;
}
var originUUID, snapshotVersion, mapValues, mapKeys, mapEntries, customMapEntries;
var init_global = __esm({
"src/global.ts"() {
"use strict";
originUUID = "00000000-0000-0000-0000-000000000000";
snapshotVersion = "7";
mapValues = (obj, map) => {
const result = Object.keys(obj).reduce(function(result2, key) {
result2[key] = map(obj[key]);
return result2;
}, {});
return result;
};
mapKeys = (obj, map) => {
const result = Object.fromEntries(
Object.entries(obj).map(([key, val2]) => {
const newKey = map(key, val2);
return [newKey, val2];
})
);
return result;
};
mapEntries = (obj, map) => {
const result = Object.fromEntries(
Object.entries(obj).map(([key, val2]) => {
const [newKey, newVal] = map(key, val2);
return [newKey, newVal];
})
);
return result;
};
customMapEntries = (obj, map) => {
const result = Object.fromEntries(
Object.entries(obj).map(([key, val2]) => {
const [newKey, newVal] = map(key, val2);
return [newKey, newVal];
})
);
return result;
};
}
});
// src/serializer/mysqlSchema.ts
var index, fk, column, tableV3, compositePK, uniqueConstraint, checkConstraint, tableV4, table, viewMeta, view, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
var init_mysqlSchema = __esm({
"src/serializer/mysqlSchema.ts"() {
"use strict";
init_lib();
init_global();
index = objectType({
name: stringType(),
columns: stringType().array(),
isUnique: booleanType(),
using: enumType(["btree", "hash"]).optional(),
algorithm: enumType(["default", "inplace", "copy"]).optional(),
lock: enumType(["default", "none", "shared", "exclusive"]).optional()
}).strict();
fk = objectType({
name: stringType(),
tableFrom: stringType(),
columnsFrom: stringType().array(),
tableTo: stringType(),
columnsTo: stringType().array(),
onUpdate: stringType().optional(),
onDelete: stringType().optional()
}).strict();
column = objectType({
name: stringType(),
type: stringType(),
primaryKey: booleanType(),
notNull: booleanType(),
autoincrement: booleanType().optional(),
default: anyType().optional(),
onUpdate: anyType().optional(),
generated: objectType({
type: enumType(["stored", "virtual"]),
as: stringType()
}).optional()
}).strict();
tableV3 = objectType({
name: stringType(),
columns: recordType(stringType(), column),
indexes: recordType(stringType(), index),
foreignKeys: recordType(stringType(), fk)
}).strict();
compositePK = objectType({
name: stringType(),
columns: stringType().array()
}).strict();
uniqueConstraint = objectType({
name: stringType(),
columns: stringType().array()
}).strict();
checkConstraint = objectType({
name: stringType(),
value: stringType()
}).strict();
tableV4 = objectType({
name: stringType(),
schema: stringType().optional(),
columns: recordType(stringType(), column),
indexes: recordType(stringType(), index),
foreignKeys: recordType(stringType(), fk)
}).strict();
table = objectType({
name: stringType(),
columns: recordType(stringType(), column),
indexes: recordType(stringType(), index),
foreignKeys: recordType(stringType(), fk),
compositePrimaryKeys: recordType(stringType(), compositePK),
uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
checkConstraint: recordType(stringType(), checkConstraint).default({})
}).strict();
viewMeta = objectType({
algorithm: enumType(["undefined", "merge", "temptable"]),
sqlSecurity: enumType(["definer", "invoker"]),
withCheckOption: enumType(["local", "cascaded"]).optional()
}).strict();
view = objectType({
name: stringType(),
columns: recordType(stringType(), column),
definition: stringType().optional(),
isExisting: booleanType()
}).strict().merge(viewMeta);
kitInternals = objectType({
tables: recordType(
stringType(),
objectType({
columns: recordType(
stringType(),
objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
)
}).optional()
).optional(),
indexes: recordType(
stringType(),
objectType({
columns: recordType(
stringType(),
objectType({ isExpression: booleanType().optional() }).optional()
)
}).optional()
).optional()
}).optional();
dialect = literalType("mysql");
schemaHash = objectType({
id: stringType(),
prevId: stringType()
});
schemaInternalV3 = objectType({
version: literalType("3"),
dialect,
tables: recordType(stringType(), tableV3)
}).strict();
schemaInternalV4 = objectType({
version: literalType("4"),
dialect,
tables: recordType(stringType(), tableV4),
schemas: recordType(stringType(), stringType())
}).strict();
schemaInternalV5 = objectType({
version: literalType("5"),
dialect,
tables: recordType(stringType(), table),
schemas: recordType(stringType(), stringType()),
_meta: objectType({
schemas: recordType(stringType(), stringType()),
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals
}).strict();
schemaInternal = objectType({
version: literalType("5"),
dialect,
tables: recordType(stringType(), table),
views: recordType(stringType(), view).default({}),
_meta: objectType({
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals
}).strict();
schemaV3 = schemaInternalV3.merge(schemaHash);
schemaV4 = schemaInternalV4.merge(schemaHash);
schemaV5 = schemaInternalV5.merge(schemaHash);
schema = schemaInternal.merge(schemaHash);
tableSquashedV4 = objectType({
name: stringType(),
schema: stringType().optional(),
columns: recordType(stringType(), column),
indexes: recordType(stringType(), stringType()),
foreignKeys: recordType(stringType(), stringType())
}).strict();
tableSquashed = objectType({
name: stringType(),
columns: recordType(stringType(), column),
indexes: recordType(stringType(), stringType()),
foreignKeys: recordType(stringType(), stringType()),
compositePrimaryKeys: recordType(stringType(), stringType()),
uniqueConstraints: recordType(stringType(), stringType()).default({}),
checkConstraints: recordType(stringType(), stringType()).default({})
}).strict();
viewSquashed = view.omit({
algorithm: true,
sqlSecurity: true,
withCheckOption: true
}).extend({ meta: stringType() });
schemaSquashed = objectType({
version: literalType("5"),
dialect,
tables: recordType(stringType(), tableSquashed),
views: recordType(stringType(), viewSquashed)
}).strict();
schemaSquashedV4 = objectType({
version: literalType("4"),
dialect,
tables: recordType(stringType(), tableSquashedV4),
schemas: recordType(stringType(), stringType())
}).strict();
MySqlSquasher = {
squashIdx: (idx) => {
index.parse(idx);
return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
},
unsquashIdx: (input) => {
const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
const destructed = {
name,
columns: columnsString.split(","),
isUnique: isUnique === "true",
using: using ? using : void 0,
algorithm: algorithm ? algorithm : void 0,
lock: lock ? lock : void 0
};
return index.parse(destructed);
},
squashPK: (pk) => {
return `${pk.name};${pk.columns.join(",")}`;
},
unsquashPK: (pk) => {
const splitted = pk.split(";");
return { name: splitted[0], columns: splitted[1].split(",") };
},
squashUnique: (unq) => {
return `${unq.name};${unq.columns.join(",")}`;
},
unsquashUnique: (unq) => {
const [name, columns] = unq.split(";");
return { name, columns: columns.split(",") };
},
squashFK: (fk4) => {
return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
},
unsquashFK: (input) => {
const [
name,
tableFrom,
columnsFromStr,
tableTo,
columnsToStr,
onUpdate,
onDelete
] = input.split(";");
const result = fk.parse({
name,
tableFrom,
columnsFrom: columnsFromStr.split(","),
tableTo,
columnsTo: columnsToStr.split(","),
onUpdate,
onDelete
});
return result;
},
squashCheck: (input) => {
return `${input.name};${input.value}`;
},
unsquashCheck: (input) => {
const [name, value] = input.split(";");
return { name, value };
},
squashView: (view4) => {
return `${view4.algorithm};${view4.sqlSecurity};${view4.withCheckOption}`;
},
unsquashView: (meta) => {
const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
const toReturn = {
algorithm,
sqlSecurity,
withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
};
return viewMeta.parse(toReturn);
}
};
squashMysqlScheme = (json) => {
const mappedTables = Object.fromEntries(
Object.entries(json.tables).map((it) => {
const squashedIndexes = mapValues(it[1].indexes, (index5) => {
return MySqlSquasher.squashIdx(index5);
});
const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
return MySqlSquasher.squashFK(fk4);
});
const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
return MySqlSquasher.squashPK(pk);
});
const squashedUniqueConstraints = mapValues(
it[1].uniqueConstraints,
(unq) => {
return MySqlSquasher.squashUnique(unq);
}
);
const squashedCheckConstraints = mapValues(it[1].checkConstraint, (check2) => {
return MySqlSquasher.squashCheck(check2);
});
return [
it[0],
{
name: it[1].name,
columns: it[1].columns,
indexes: squashedIndexes,
foreignKeys: squashedFKs,
compositePrimaryKeys: squashedPKs,
uniqueConstraints: squashedUniqueConstraints,
checkConstraints: squashedCheckConstraints
}
];
})
);
const mappedViews = Object.fromEntries(
Object.entries(json.views).map(([key, value]) => {
const meta = MySqlSquasher.squashView(value);
return [key, {
name: value.name,
isExisting: value.isExisting,
columns: value.columns,
definition: value.definition,
meta
}];
})
);
return {
version: "5",
dialect: json.dialect,
tables: mappedTables,
views: mappedViews
};
};
mysqlSchema = schema;
mysqlSchemaV5 = schemaV5;
mysqlSchemaSquashed = schemaSquashed;
backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
dryMySql = mysqlSchema.parse({
version: "5",
dialect: "mysql",
id: originUUID,
prevId: "",
tables: {},
schemas: {},
views: {},
_meta: {
schemas: {},
tables: {},
columns: {}
}
});
}
});
// src/serializer/pgSchema.ts
var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, roleSchema, sequenceSquashed, columnV7, column2, checkConstraint2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
var init_pgSchema = __esm({
"src/serializer/pgSchema.ts"() {
"use strict";
init_global();
init_lib();
indexV2 = objectType({
name: stringType(),
columns: recordType(
stringType(),
objectType({
name: stringType()
})
),
isUnique: booleanType()
}).strict();
columnV2 = objectType({
name: stringType(),
type: stringType(),
primaryKey: booleanType(),
notNull: booleanType(),
default: anyType().optional(),
references: stringType().optional()
}).strict();
tableV2 = objectType({
name: stringType(),
columns: recordType(stringType(), columnV2),
indexes: recordType(stringType(), indexV2)
}).strict();
enumSchemaV1 = objectType({
name: stringType(),
values: recordType(stringType(), stringType())
}).strict();
enumSchema = objectType({
name: stringType(),
schema: stringType(),
values: stringType().array()
}).strict();
pgSchemaV2 = objectType({
version: literalType("2"),
tables: recordType(stringType(), tableV2),
enums: recordType(stringType(), enumSchemaV1)
}).strict();
references = objectType({
foreignKeyName: stringType(),
table: stringType(),
column: stringType(),
onDelete: stringType().optional(),
onUpdate: stringType().optional()
}).strict();
columnV1 = objectType({
name: stringType(),
type: stringType(),
primaryKey: booleanType(),
notNull: booleanType(),
default: anyType().optional(),
references: references.optional()
}).strict();
tableV1 = objectType({
name: stringType(),
columns: recordType(stringType(), columnV1),
indexes: recordType(stringType(), indexV2)
}).strict();
pgSchemaV1 = objectType({
version: literalType("1"),
tables: recordType(stringType(), tableV1),
enums: recordType(stringType(), enumSchemaV1)
}).strict();
indexColumn = objectType({
expression: stringType(),
isExpression: booleanType(),
asc: booleanType(),
nulls: stringType().optional(),
opclass: stringType().optional()
});
index2 = objectType({
name: stringType(),
columns: indexColumn.array(),
isUnique: booleanType(),
with: recordType(stringType(), anyType()).optional(),
method: stringType().default("btree"),
where: stringType().optional(),
concurrently: booleanType().default(false)
}).strict();
indexV4 = objectType({
name: stringType(),
columns: stringType().array(),
isUnique: booleanType(),
with: recordType(stringType(), stringType()).optional(),
method: stringType().default("btree"),
where: stringType().optional(),
concurrently: booleanType().default(false)
}).strict();
indexV5 = objectType({
name: stringType(),
columns: stringType().array(),
isUnique: booleanType(),
with: recordType(stringType(), stringType()).optional(),
method: stringType().default("btree"),
where: stringType().optional(),
concurrently: booleanType().default(false)
}).strict();
indexV6 = objectType({
name: stringType(),
columns: stringType().array(),
isUnique: booleanType(),
with: recordType(stringType(), stringType()).optional(),
method: stringType().default("btree"),
where: stringType().optional(),
concurrently: booleanType().default(false)
}).strict();
fk2 = objectType({
name: stringType(),
tableFrom: stringType(),
columnsFrom: stringType().array(),
tableTo: stringType(),
schemaTo: stringType().optional(),
columnsTo: stringType().array(),
onUpdate: stringType().optional(),
onDelete: stringType().optional()
}).strict();
sequenceSchema = objectType({
name: stringType(),
increment: stringType().optional(),
minValue: stringType().optional(),
maxValue: stringType().optional(),
startWith: stringType().optional(),
cache: stringType().optional(),
cycle: booleanType().optional(),
schema: stringType()
}).strict();
roleSchema = objectType({
name: stringType(),
createDb: booleanType().optional(),
createRole: booleanType().optional(),
inherit: booleanType().optional()
}).strict();
sequenceSquashed = objectType({
name: stringType(),
schema: stringType(),
values: stringType()
}).strict();
columnV7 = objectType({
name: stringType(),
type: stringType(),
typeSchema: stringType().optional(),
primaryKey: booleanType(),
notNull: booleanType(),
default: anyType().optional(),
isUnique: anyType().optional(),
uniqueName: stringType().optional(),
nullsNotDistinct: booleanType().optional()
}).strict();
column2 = objectType({
name: stringType(),
type: stringType(),
typeSchema: stringType().optional(),
primaryKey: booleanType(),
notNull: booleanType(),
default: anyType().optional(),
isUnique: anyType().optional(),
uniqueName: stringType().optional(),
nullsNotDistinct: booleanType().optional(),
generated: objectType({
type: literalType("stored"),
as: stringType()
}).optional(),
identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
}).strict();
checkConstraint2 = objectType({
name: stringType(),
value: stringType()
}).strict();
columnSquashed = objectType({
name: stringType(),
type: stringType(),
typeSchema: stringType().optional(),
primaryKey: booleanType(),
notNull: booleanType(),
default: anyType().optional(),
isUnique: anyType().optional(),
uniqueName: stringType().optional(),
nullsNotDistinct: booleanType().optional(),
generated: objectType({
type: literalType("stored"),
as: stringType()
}).optional(),
identity: stringType().optional()
}).strict();
tableV32 = objectType({
name: stringType(),
columns: recordType(stringType(), column2),
indexes: recordType(stringType(), index2),
foreignKeys: recordType(stringType(), fk2)
}).strict();
compositePK2 = objectType({
name: stringType(),
columns: stringType().array()
}).strict();
uniqueConstraint2 = objectType({
name: stringType(),
columns: stringType().array(),
nullsNotDistinct: booleanType()
}).strict();
policy = objectType({
name: stringType(),
as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
to: stringType().array().optional(),
using: stringType().optional(),
withCheck: stringType().optional(),
on: stringType().optional(),
schema: stringType().optional()
}).strict();
policySquashed = objectType({
name: stringType(),
values: stringType()
}).strict();
viewWithOption = objectType({
checkOption: enumType(["local", "cascaded"]).optional(),
securityBarrier: booleanType().optional(),
securityInvoker: booleanType().optional()
}).strict();
matViewWithOption = objectType({
fillfactor: numberType().optional(),
toastTupleTarget: numberType().optional(),
parallelWorkers: numberType().optional(),
autovacuumEnabled: booleanType().optional(),
vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
vacuumTruncate: booleanType().optional(),
autovacuumVacuumThreshold: numberType().optional(),
autovacuumVacuumScaleFactor: numberType().optional(),
autovacuumVacuumCostDelay: numberType().optional(),
autovacuumVacuumCostLimit: numberType().optional(),
autovacuumFreezeMinAge: numberType().optional(),
autovacuumFreezeMaxAge: numberType().optional(),
autovacuumFreezeTableAge: numberType().optional(),
autovacuumMultixactFreezeMinAge: numberType().optional(),
autovacuumMultixactFreezeMaxAge: numberType().optional(),
autovacuumMultixactFreezeTableAge: numberType().optional(),
logAutovacuumMinDuration: numberType().optional(),
userCatalogTable: booleanType().optional()
}).strict();
mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
view2 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), column2),
definition: stringType().optional(),
materialized: booleanType(),
with: mergedViewWithOption.optional(),
isExisting: booleanType(),
withNoData: booleanType().optional(),
using: stringType().optional(),
tablespace: stringType().optional()
}).strict();
tableV42 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), column2),
indexes: recordType(stringType(), indexV4),
foreignKeys: recordType(stringType(), fk2)
}).strict();
tableV5 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), column2),
indexes: recordType(stringType(), indexV5),
foreignKeys: recordType(stringType(), fk2),
compositePrimaryKeys: recordType(stringType(), compositePK2),
uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
}).strict();
tableV6 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), column2),
indexes: recordType(stringType(), indexV6),
foreignKeys: recordType(stringType(), fk2),
compositePrimaryKeys: recordType(stringType(), compositePK2),
uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
}).strict();
tableV7 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), columnV7),
indexes: recordType(stringType(), index2),
foreignKeys: recordType(stringType(), fk2),
compositePrimaryKeys: recordType(stringType(), compositePK2),
uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
}).strict();
table2 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), column2),
indexes: recordType(stringType(), index2),
foreignKeys: recordType(stringType(), fk2),
compositePrimaryKeys: recordType(stringType(), compositePK2),
uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
policies: recordType(stringType(), policy).default({}),
checkConstraints: recordType(stringType(), checkConstraint2).default({}),
isRLSEnabled: booleanType().default(false)
}).strict();
schemaHash2 = objectType({
id: stringType(),
prevId: stringType()
});
kitInternals2 = objectType({
tables: recordType(
stringType(),
objectType({
columns: recordType(
stringType(),
objectType({
isArray: booleanType().optional(),
dimensions: numberType().optional(),
rawType: stringType().optional(),
isDefaultAnExpression: booleanType().optional()
}).optional()
)
}).optional()
)
}).optional();
pgSchemaInternalV3 = objectType({
version: literalType("3"),
dialect: literalType("pg"),
tables: recordType(stringType(), tableV32),
enums: recordType(stringType(), enumSchemaV1)
}).strict();
pgSchemaInternalV4 = objectType({
version: literalType("4"),
dialect: literalType("pg"),
tables: recordType(stringType(), tableV42),
enums: recordType(stringType(), enumSchemaV1),
schemas: recordType(stringType(), stringType())
}).strict();
pgSchemaInternalV5 = objectType({
version: literalType("5"),
dialect: literalType("pg"),
tables: recordType(stringType(), tableV5),
enums: recordType(stringType(), enumSchemaV1),
schemas: recordType(stringType(), stringType()),
_meta: objectType({
schemas: recordType(stringType(), stringType()),
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals2
}).strict();
pgSchemaInternalV6 = objectType({
version: literalType("6"),
dialect: literalType("postgresql"),
tables: recordType(stringType(), tableV6),
enums: recordType(stringType(), enumSchema),
schemas: recordType(stringType(), stringType()),
_meta: objectType({
schemas: recordType(stringType(), stringType()),
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals2
}).strict();
pgSchemaExternal = objectType({
version: literalType("5"),
dialect: literalType("pg"),
tables: arrayType(table2),
enums: arrayType(enumSchemaV1),
schemas: arrayType(objectType({ name: stringType() })),
_meta: objectType({
schemas: recordType(stringType(), stringType()),
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
})
}).strict();
pgSchemaInternalV7 = objectType({
version: literalType("7"),
dialect: literalType("postgresql"),
tables: recordType(stringType(), tableV7),
enums: recordType(stringType(), enumSchema),
schemas: recordType(stringType(), stringType()),
sequences: recordType(stringType(), sequenceSchema),
_meta: objectType({
schemas: recordType(stringType(), stringType()),
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals2
}).strict();
pgSchemaInternal = objectType({
version: literalType("7"),
dialect: literalType("postgresql"),
tables: recordType(stringType(), table2),
enums: recordType(stringType(), enumSchema),
schemas: recordType(stringType(), stringType()),
views: recordType(stringType(), view2).default({}),
sequences: recordType(stringType(), sequenceSchema).default({}),
roles: recordType(stringType(), roleSchema).default({}),
policies: recordType(stringType(), policy).default({}),
_meta: objectType({
schemas: recordType(stringType(), stringType()),
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals2
}).strict();
tableSquashed2 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), columnSquashed),
indexes: recordType(stringType(), stringType()),
foreignKeys: recordType(stringType(), stringType()),
compositePrimaryKeys: recordType(stringType(), stringType()),
uniqueConstraints: recordType(stringType(), stringType()),
policies: recordType(stringType(), stringType()),
checkConstraints: recordType(stringType(), stringType()),
isRLSEnabled: booleanType().default(false)
}).strict();
tableSquashedV42 = objectType({
name: stringType(),
schema: stringType(),
columns: recordType(stringType(), column2),
indexes: recordType(stringType(), stringType()),
foreignKeys: recordType(stringType(), stringType())
}).strict();
pgSchemaSquashedV4 = objectType({
version: literalType("4"),
dialect: literalType("pg"),
tables: recordType(stringType(), tableSquashedV42),
enums: recordType(stringType(), enumSchemaV1),
schemas: recordType(stringType(), stringType())
}).strict();
pgSchemaSquashedV6 = objectType({
version: literalType("6"),
dialect: literalType("postgresql"),
tables: recordType(stringType(), tableSquashed2),
enums: recordType(stringType(), enumSchema),
schemas: recordType(stringType(), stringType())
}).strict();
pgSchemaSquashed = objectType({
version: literalType("7"),
dialect: literalType("postgresql"),
tables: recordType(stringType(), tableSquashed2),
enums: recordType(stringType(), enumSchema),
schemas: recordType(stringType(), stringType()),
views: recordType(stringType(), view2),
sequences: recordType(stringType(), sequenceSquashed),
roles: recordType(stringType(), roleSchema).default({}),
policies: recordType(stringType(), policySquashed).default({})
}).strict();
pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash2);
pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash2);
pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash2);
pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash2);
pgSchema = pgSchemaInternal.merge(schemaHash2);
backwardCompatiblePgSchema = unionType([
pgSchemaV5,
pgSchemaV6,
pgSchema
]);
PgSquasher = {
squashIdx: (idx) => {
index2.parse(idx);
return `${idx.name};${idx.columns.map(
(c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass ? c.opclass : ""}`
).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
},
unsquashIdx: (input) => {
const [
name,
columnsString,
isUnique,
concurrently,
method,
where,
idxWith
] = input.split(";");
const columnString = columnsString.split(",,");
const columns = [];
for (const column9 of columnString) {
const [expression, isExpression, asc, nulls, opclass] = column9.split("--");
columns.push({
nulls,
isExpression: isExpression === "true",
asc: asc === "true",
expression,
opclass: opclass === "undefined" ? void 0 : opclass
});
}
const result = index2.parse({
name,
columns,
isUnique: isUnique === "true",
concurrently: concurrently === "true",
method,
where: where === "undefined" ? void 0 : where,
with: !idxWith || idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
});
return result;
},
squashIdxPush: (idx) => {
index2.parse(idx);
return `${idx.name};${idx.columns.map((c) => `${c.isExpression ? "" : c.expression}--${c.asc}--${c.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`;
},
unsquashIdxPush: (input) => {
const [name, columnsString, isUnique, method, idxWith] = input.split(";");
const columnString = columnsString.split("--");
const columns = [];
for (const column9 of columnString) {
const [expression, asc, nulls, opclass] = column9.split(",");
columns.push({
nulls,
isExpression: expression === "",
asc: asc === "true",
expression
});
}
const result = index2.parse({
name,
columns,
isUnique: isUnique === "true",
concurrently: false,
method,
with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
});
return result;
},
squashFK: (fk4) => {
return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""};${fk4.schemaTo || "public"}`;
},
squashPolicy: (policy4) => {
var _a;
return `${policy4.name}--${policy4.as}--${policy4.for}--${(_a = policy4.to) == null ? void 0 : _a.join(",")}--${policy4.using}--${policy4.withCheck}--${policy4.on}`;
},
unsquashPolicy: (policy4) => {
const splitted = policy4.split("--");
return {
name: splitted[0],
as: splitted[1],
for: splitted[2],
to: splitted[3].split(","),
using: splitted[4] !== "undefined" ? splitted[4] : void 0,
withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0,
on: splitted[6] !== "undefined" ? splitted[6] : void 0
};
},
squashPolicyPush: (policy4) => {
var _a;
return `${policy4.name}--${policy4.as}--${policy4.for}--${(_a = policy4.to) == null ? void 0 : _a.join(",")}--${policy4.on}`;
},
unsquashPolicyPush: (policy4) => {
const splitted = policy4.split("--");
return {
name: splitted[0],
as: splitted[1],
for: splitted[2],
to: splitted[3].split(","),
on: splitted[4] !== "undefined" ? splitted[4] : void 0
};
},
squashPK: (pk) => {
return `${pk.columns.join(",")};${pk.name}`;
},
unsquashPK: (pk) => {
const splitted = pk.split(";");
return { name: splitted[1], columns: splitted[0].split(",") };
},
squashUnique: (unq) => {
return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`;
},
unsquashUnique: (unq) => {
const [name, columns, nullsNotDistinct] = unq.split(";");
return {
name,
columns: columns.split(","),
nullsNotDistinct: nullsNotDistinct === "true"
};
},
unsquashFK: (input) => {
const [
name,
tableFrom,
columnsFromStr,
tableTo,
columnsToStr,
onUpdate,
onDelete,
schemaTo
] = input.split(";");
const result = fk2.parse({
name,
tableFrom,
columnsFrom: columnsFromStr.split(","),
schemaTo,
tableTo,
columnsTo: columnsToStr.split(","),
onUpdate,
onDelete
});
return result;
},
squashSequence: (seq) => {
return `${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
},
unsquashSequence: (seq) => {
const splitted = seq.split(";");
return {
minValue: splitted[0] !== "undefined" ? splitted[0] : void 0,
maxValue: splitted[1] !== "undefined" ? splitted[1] : void 0,
increment: splitted[2] !== "undefined" ? splitted[2] : void 0,
startWith: splitted[3] !== "undefined" ? splitted[3] : void 0,
cache: splitted[4] !== "undefined" ? splitted[4] : void 0,
cycle: splitted[5] === "true"
};
},
squashIdentity: (seq) => {
return `${seq.name};${seq.type};${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
},
unsquashIdentity: (seq) => {
const splitted = seq.split(";");
return {
name: splitted[0],
type: splitted[1],
minValue: splitted[2] !== "undefined" ? splitted[2] : void 0,
maxValue: splitted[3] !== "undefined" ? splitted[3] : void 0,
increment: splitted[4] !== "undefined" ? splitted[4] : void 0,
startWith: splitted[5] !== "undefined" ? splitted[5] : void 0,
cache: splitted[6] !== "undefined" ? splitted[6] : void 0,
cycle: splitted[7] === "true"
};
},
squashCheck: (check2) => {
return `${check2.name};${check2.value}`;
},
unsquashCheck: (input) => {
const [
name,
value
] = input.split(";");
return { name, value };
}
};
squashPgScheme = (json, action) => {
const mappedTables = Object.fromEntries(
Object.entries(json.tables).map((it) => {
const squashedIndexes = mapValues(it[1].indexes, (index5) => {
return action === "push" ? PgSquasher.squashIdxPush(index5) : PgSquasher.squashIdx(index5);
});
const squashedFKs = mapValues(it[1].foreignKeys, (fk4) => {
return PgSquasher.squashFK(fk4);
});
const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
return PgSquasher.squashPK(pk);
});
const mappedColumns = Object.fromEntries(
Object.entries(it[1].columns).map((it2) => {
const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0;
return [
it2[0],
{
...it2[1],
identity: mappedIdentity
}
];
})
);
const squashedUniqueConstraints = mapValues(
it[1].uniqueConstraints,
(unq) => {
return PgSquasher.squashUnique(unq);
}
);
const squashedPolicies = mapValues(it[1].policies, (policy4) => {
return action === "push" ? PgSquasher.squashPolicyPush(policy4) : PgSquasher.squashPolicy(policy4);
});
const squashedChecksContraints = mapValues(
it[1].checkConstraints,
(check2) => {
return PgSquasher.squashCheck(check2);
}
);
return [
it[0],
{
name: it[1].name,
schema: it[1].schema,
columns: mappedColumns,
indexes: squashedIndexes,
foreignKeys: squashedFKs,
compositePrimaryKeys: squashedPKs,
uniqueConstraints: squashedUniqueConstraints,
policies: squashedPolicies,
checkConstraints: squashedChecksContraints,
isRLSEnabled: it[1].isRLSEnabled ?? false
}
];
})
);
const mappedSequences = Object.fromEntries(
Object.entries(json.sequences).map((it) => {
return [
it[0],
{
name: it[1].name,
schema: it[1].schema,
values: PgSquasher.squashSequence(it[1])
}
];
})
);
const mappedPolicies = Object.fromEntries(
Object.entries(json.policies).map((it) => {
return [
it[0],
{
name: it[1].name,
values: action === "push" ? PgSquasher.squashPolicyPush(it[1]) : PgSquasher.squashPolicy(it[1])
}
];
})
);
return {
version: "7",
dialect: json.dialect,
tables: mappedTables,
enums: json.enums,
schemas: json.schemas,
views: json.views,
policies: mappedPolicies,
sequences: mappedSequences,
roles: json.roles
};
};
dryPg = pgSchema.parse({
version: snapshotVersion,
dialect: "postgresql",
id: originUUID,
prevId: "",
tables: {},
enums: {},
schemas: {},
policies: {},
roles: {},
sequences: {},
_meta: {
schemas: {},
tables: {},
columns: {}
}
});
}
});
// src/serializer/singlestoreSchema.ts
var index3, column3, compositePK3, uniqueConstraint3, table3, viewMeta2, kitInternals3, dialect2, schemaHash3, schemaInternal2, schema2, tableSquashed3, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore;
var init_singlestoreSchema = __esm({
"src/serializer/singlestoreSchema.ts"() {
"use strict";
init_lib();
init_global();
index3 = objectType({
name: stringType(),
columns: stringType().array(),
isUnique: booleanType(),
using: enumType(["btree", "hash"]).optional(),
algorithm: enumType(["default", "inplace", "copy"]).optional(),
lock: enumType(["default", "none", "shared", "exclusive"]).optional()
}).strict();
column3 = objectType({
name: stringType(),
type: stringType(),
primaryKey: booleanType(),
notNull: booleanType(),
autoincrement: booleanType().optional(),
default: anyType().optional(),
onUpdate: anyType().optional(),
generated: objectType({
type: enumType(["stored", "virtual"]),
as: stringType()
}).optional()
}).strict();
compositePK3 = objectType({
name: stringType(),
columns: stringType().array()
}).strict();
uniqueConstraint3 = objectType({
name: stringType(),
columns: stringType().array()
}).strict();
table3 = objectType({
name: stringType(),
columns: recordType(stringType(), column3),
indexes: recordType(stringType(), index3),
compositePrimaryKeys: recordType(stringType(), compositePK3),
uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
}).strict();
viewMeta2 = objectType({
algorithm: enumType(["undefined", "merge", "temptable"]),
sqlSecurity: enumType(["definer", "invoker"]),
withCheckOption: enumType(["local", "cascaded"]).optional()
}).strict();
kitInternals3 = objectType({
tables: recordType(
stringType(),
objectType({
columns: recordType(
stringType(),
objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
)
}).optional()
).optional(),
indexes: recordType(
stringType(),
objectType({
columns: recordType(
stringType(),
objectType({ isExpression: booleanType().optional() }).optional()
)
}).optional()
).optional()
}).optional();
dialect2 = literalType("singlestore");
schemaHash3 = objectType({
id: stringType(),
prevId: stringType()
});
schemaInternal2 = objectType({
version: literalType("1"),
dialect: dialect2,
tables: recordType(stringType(), table3),
/* views: record(string(), view).default({}), */
_meta: objectType({
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals3
}).strict();
schema2 = schemaInternal2.merge(schemaHash3);
tableSquashed3 = objectType({
name: stringType(),
columns: recordType(stringType(), column3),
indexes: recordType(stringType(), stringType()),
compositePrimaryKeys: recordType(stringType(), stringType()),
uniqueConstraints: recordType(stringType(), stringType()).default({})
}).strict();
schemaSquashed2 = objectType({
version: literalType("1"),
dialect: dialect2,
tables: recordType(stringType(), tableSquashed3)
/* views: record(string(), viewSquashed), */
}).strict();
SingleStoreSquasher = {
squashIdx: (idx) => {
index3.parse(idx);
return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
},
unsquashIdx: (input) => {
const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
const destructed = {
name,
columns: columnsString.split(","),
isUnique: isUnique === "true",
using: using ? using : void 0,
algorithm: algorithm ? algorithm : void 0,
lock: lock ? lock : void 0
};
return index3.parse(destructed);
},
squashPK: (pk) => {
return `${pk.name};${pk.columns.join(",")}`;
},
unsquashPK: (pk) => {
const splitted = pk.split(";");
return { name: splitted[0], columns: splitted[1].split(",") };
},
squashUnique: (unq) => {
return `${unq.name};${unq.columns.join(",")}`;
},
unsquashUnique: (unq) => {
const [name, columns] = unq.split(";");
return { name, columns: columns.split(",") };
}
/* squashView: (view: View): string => {
return `${view.algorithm};${view.sqlSecurity};${view.withCheckOption}`;
},
unsquashView: (meta: string): SquasherViewMeta => {
const [algorithm, sqlSecurity, withCheckOption] = meta.split(';');
const toReturn = {
algorithm: algorithm,
sqlSecurity: sqlSecurity,
withCheckOption: withCheckOption !== 'undefined' ? withCheckOption : undefined,
};
return viewMeta.parse(toReturn);
}, */
};
squashSingleStoreScheme = (json) => {
const mappedTables = Object.fromEntries(
Object.entries(json.tables).map((it) => {
const squashedIndexes = mapValues(it[1].indexes, (index5) => {
return SingleStoreSquasher.squashIdx(index5);
});
const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
return SingleStoreSquasher.squashPK(pk);
});
const squashedUniqueConstraints = mapValues(
it[1].uniqueConstraints,
(unq) => {
return SingleStoreSquasher.squashUnique(unq);
}
);
return [
it[0],
{
name: it[1].name,
columns: it[1].columns,
indexes: squashedIndexes,
compositePrimaryKeys: squashedPKs,
uniqueConstraints: squashedUniqueConstraints
}
];
})
);
return {
version: "1",
dialect: json.dialect,
tables: mappedTables
/* views: mappedViews, */
};
};
singlestoreSchema = schema2;
singlestoreSchemaSquashed = schemaSquashed2;
backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
drySingleStore = singlestoreSchema.parse({
version: "1",
dialect: "singlestore",
id: originUUID,
prevId: "",
tables: {},
schemas: {},
/* views: {}, */
_meta: {
schemas: {},
tables: {},
columns: {}
}
});
}
});
// src/serializer/sqliteSchema.ts
var index4, fk3, compositePK4, column4, tableV33, uniqueConstraint4, checkConstraint3, table4, view3, dialect3, schemaHash4, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals4, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed4, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
var init_sqliteSchema = __esm({
"src/serializer/sqliteSchema.ts"() {
"use strict";
init_lib();
init_global();
index4 = objectType({
name: stringType(),
columns: stringType().array(),
where: stringType().optional(),
isUnique: booleanType()
}).strict();
fk3 = objectType({
name: stringType(),
tableFrom: stringType(),
columnsFrom: stringType().array(),
tableTo: stringType(),
columnsTo: stringType().array(),
onUpdate: stringType().optional(),
onDelete: stringType().optional()
}).strict();
compositePK4 = objectType({
columns: stringType().array(),
name: stringType().optional()
}).strict();
column4 = objectType({
name: stringType(),
type: stringType(),
primaryKey: booleanType(),
notNull: booleanType(),
autoincrement: booleanType().optional(),
default: anyType().optional(),
generated: objectType({
type: enumType(["stored", "virtual"]),
as: stringType()
}).optional()
}).strict();
tableV33 = objectType({
name: stringType(),
columns: recordType(stringType(), column4),
indexes: recordType(stringType(), index4),
foreignKeys: recordType(stringType(), fk3)
}).strict();
uniqueConstraint4 = objectType({
name: stringType(),
columns: stringType().array()
}).strict();
checkConstraint3 = objectType({
name: stringType(),
value: stringType()
}).strict();
table4 = objectType({
name: stringType(),
columns: recordType(stringType(), column4),
indexes: recordType(stringType(), index4),
foreignKeys: recordType(stringType(), fk3),
compositePrimaryKeys: recordType(stringType(), compositePK4),
uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({}),
checkConstraints: recordType(stringType(), checkConstraint3).default({})
}).strict();
view3 = objectType({
name: stringType(),
columns: recordType(stringType(), column4),
definition: stringType().optional(),
isExisting: booleanType()
}).strict();
dialect3 = enumType(["sqlite"]);
schemaHash4 = objectType({
id: stringType(),
prevId: stringType()
}).strict();
schemaInternalV32 = objectType({
version: literalType("3"),
dialect: dialect3,
tables: recordType(stringType(), tableV33),
enums: objectType({})
}).strict();
schemaInternalV42 = objectType({
version: literalType("4"),
dialect: dialect3,
tables: recordType(stringType(), table4),
views: recordType(stringType(), view3).default({}),
enums: objectType({})
}).strict();
schemaInternalV52 = objectType({
version: literalType("5"),
dialect: dialect3,
tables: recordType(stringType(), table4),
enums: objectType({}),
_meta: objectType({
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
})
}).strict();
kitInternals4 = objectType({
indexes: recordType(
stringType(),
objectType({
columns: recordType(
stringType(),
objectType({ isExpression: booleanType().optional() }).optional()
)
}).optional()
).optional()
}).optional();
latestVersion = literalType("6");
schemaInternal3 = objectType({
version: latestVersion,
dialect: dialect3,
tables: recordType(stringType(), table4),
views: recordType(stringType(), view3).default({}),
enums: objectType({}),
_meta: objectType({
tables: recordType(stringType(), stringType()),
columns: recordType(stringType(), stringType())
}),
internal: kitInternals4
}).strict();
schemaV32 = schemaInternalV32.merge(schemaHash4).strict();
schemaV42 = schemaInternalV42.merge(schemaHash4).strict();
schemaV52 = schemaInternalV52.merge(schemaHash4).strict();
schema3 = schemaInternal3.merge(schemaHash4).strict();
tableSquashed4 = objectType({
name: stringType(),
columns: recordType(stringType(), column4),
indexes: recordType(stringType(), stringType()),
foreignKeys: recordType(stringType(), stringType()),
compositePrimaryKeys: recordType(stringType(), stringType()),
uniqueConstraints: recordType(stringType(), stringType()).default({}),
checkConstraints: recordType(stringType(), stringType()).default({})
}).strict();
schemaSquashed3 = objectType({
version: latestVersion,
dialect: dialect3,
tables: recordType(stringType(), tableSquashed4),
views: recordType(stringType(), view3),
enums: anyType()
}).strict();
SQLiteSquasher = {
squashIdx: (idx) => {
index4.parse(idx);
return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
},
unsquashIdx: (input) => {
const [name, columnsString, isUnique, where] = input.split(";");
const result = index4.parse({
name,
columns: columnsString.split(","),
isUnique: isUnique === "true",
where: where ?? void 0
});
return result;
},
squashUnique: (unq) => {
return `${unq.name};${unq.columns.join(",")}`;
},
unsquashUnique: (unq) => {
const [name, columns] = unq.split(";");
return { name, columns: columns.split(",") };
},
squashFK: (fk4) => {
return `${fk4.name};${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
},
unsquashFK: (input) => {
const [
name,
tableFrom,
columnsFromStr,
tableTo,
columnsToStr,
onUpdate,
onDelete
] = input.split(";");
const result = fk3.parse({
name,
tableFrom,
columnsFrom: columnsFromStr.split(","),
tableTo,
columnsTo: columnsToStr.split(","),
onUpdate,
onDelete
});
return result;
},
squashPushFK: (fk4) => {
return `${fk4.tableFrom};${fk4.columnsFrom.join(",")};${fk4.tableTo};${fk4.columnsTo.join(",")};${fk4.onUpdate ?? ""};${fk4.onDelete ?? ""}`;
},
unsquashPushFK: (input) => {
const [
tableFrom,
columnsFromStr,
tableTo,
columnsToStr,
onUpdate,
onDelete
] = input.split(";");
const result = fk3.parse({
name: "",
tableFrom,
columnsFrom: columnsFromStr.split(","),
tableTo,
columnsTo: columnsToStr.split(","),
onUpdate,
onDelete
});
return result;
},
squashPK: (pk) => {
return pk.columns.join(",");
},
unsquashPK: (pk) => {
return pk.split(",");
},
squashCheck: (check2) => {
return `${check2.name};${check2.value}`;
},
unsquashCheck: (input) => {
const [
name,
value
] = input.split(";");
return { name, value };
}
};
squashSqliteScheme = (json, action) => {
const mappedTables = Object.fromEntries(
Object.entries(json.tables).map((it) => {
const squashedIndexes = mapValues(it[1].indexes, (index5) => {
return SQLiteSquasher.squashIdx(index5);
});
const squashedFKs = customMapEntries(
it[1].foreignKeys,
(key, value) => {
return action === "push" ? [
SQLiteSquasher.squashPushFK(value),
SQLiteSquasher.squashPushFK(value)
] : [key, SQLiteSquasher.squashFK(value)];
}
);
const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
return SQLiteSquasher.squashPK(pk);
});
const squashedUniqueConstraints = mapValues(
it[1].uniqueConstraints,
(unq) => {
return SQLiteSquasher.squashUnique(unq);
}
);
const squashedCheckConstraints = mapValues(
it[1].checkConstraints,
(check2) => {
return SQLiteSquasher.squashCheck(check2);
}
);
return [
it[0],
{
name: it[1].name,
columns: it[1].columns,
indexes: squashedIndexes,
foreignKeys: squashedFKs,
compositePrimaryKeys: squashedPKs,
uniqueConstraints: squashedUniqueConstraints,
checkConstraints: squashedCheckConstraints
}
];
})
);
return {
version: "6",
dialect: json.dialect,
tables: mappedTables,
views: json.views,
enums: json.enums
};
};
drySQLite = schema3.parse({
version: "6",
dialect: "sqlite",
id: originUUID,
prevId: "",
tables: {},
views: {},
enums: {},
_meta: {
tables: {},
columns: {}
}
});
sqliteSchemaV5 = schemaV52;
sqliteSchema = schema3;
SQLiteSchemaSquashed = schemaSquashed3;
backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
}
});
// src/schemaValidator.ts
var dialects, dialect4, commonSquashedSchema, commonSchema;
var init_schemaValidator = __esm({
"src/schemaValidator.ts"() {
"use strict";
init_lib();
init_mysqlSchema();
init_pgSchema();
init_singlestoreSchema();
init_sqliteSchema();
dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore"];
dialect4 = enumType(dialects);
commonSquashedSchema = unionType([
pgSchemaSquashed,
mysqlSchemaSquashed,
SQLiteSchemaSquashed,
singlestoreSchemaSquashed
]);
commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]);
}
});
// ../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
function camelCase(input, options) {
if (!(typeof input === "string" || Array.isArray(input))) {
throw new TypeError("Expected the input to be `string | string[]`");
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map((x2) => x2.trim()).filter((x2) => x2.length).join("-");
} else {
input = input.trim();
}
if (input.length === 0) {
return "";
}
const toLowerCase = options.locale === false ? (string2) => string2.toLowerCase() : (string2) => string2.toLocaleLowerCase(options.locale);
const toUpperCase = options.locale === false ? (string2) => string2.toUpperCase() : (string2) => string2.toLocaleUpperCase(options.locale);
if (input.length === 1) {
if (SEPARATORS.test(input)) {
return "";
}
return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
}
const hasUpperCase = input !== toLowerCase(input);
if (hasUpperCase) {
input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
}
input = input.replace(LEADING_SEPARATORS, "");
input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
if (options.pascalCase) {
input = toUpperCase(input.charAt(0)) + input.slice(1);
}
return postProcess(input, toUpperCase);
}
var UPPERCASE, LOWERCASE, LEADING_CAPITAL, IDENTIFIER, SEPARATORS, LEADING_SEPARATORS, SEPARATORS_AND_IDENTIFIER, NUMBERS_AND_IDENTIFIER, preserveCamelCase, preserveConsecutiveUppercase, postProcess;
var init_camelcase = __esm({
"../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js"() {
UPPERCASE = /[\p{Lu}]/u;
LOWERCASE = /[\p{Ll}]/u;
LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
SEPARATORS = /[_.\- ]+/;
LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
preserveCamelCase = (string2, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
let isLastLastCharPreserved = false;
for (let index5 = 0; index5 < string2.length; index5++) {
const character = string2[index5];
isLastLastCharPreserved = index5 > 2 ? string2[index5 - 3] === "-" : true;
if (isLastCharLower && UPPERCASE.test(character)) {
string2 = string2.slice(0, index5) + "-" + string2.slice(index5);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
index5++;
} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
string2 = string2.slice(0, index5 - 1) + "-" + string2.slice(index5 - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
}
}
return string2;
};
preserveConsecutiveUppercase = (input, toLowerCase) => {
LEADING_CAPITAL.lastIndex = 0;
return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
};
postProcess = (input, toUpperCase) => {
SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
NUMBERS_AND_IDENTIFIER.lastIndex = 0;
return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m2) => toUpperCase(m2));
};
}
});
// src/@types/utils.ts
var init_utils = __esm({
"src/@types/utils.ts"() {
"use strict";
init_camelcase();
String.prototype.trimChar = function(char) {
let start = 0;
let end = this.length;
while (start < end && this[start] === char)
++start;
while (end > start && this[end - 1] === char)
--end;
return start > 0 || end < this.length ? this.substring(start, end) : this.toString();
};
String.prototype.squashSpaces = function() {
return this.replace(/ +/g, " ").trim();
};
String.prototype.camelCase = function() {
return camelCase(String(this));
};
String.prototype.capitalise = function() {
return this && this.length > 0 ? `${this[0].toUpperCase()}${this.slice(1)}` : String(this);
};
String.prototype.concatIf = function(it, condition) {
return condition ? `${this}${it}` : String(this);
};
String.prototype.snake_case = function() {
return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
};
Array.prototype.random = function() {
return this[~~(Math.random() * this.length)];
};
}
});
// src/cli/views.ts
var import_hanji, warning, err, info, grey, error, schema4, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, IntrospectProgress, MigrateProgress, ProgressView, DropMigrationView, trimmedRange;
var init_views = __esm({
"src/cli/views.ts"() {
"use strict";
init_source();
import_hanji = __toESM(require_hanji());
init_utils2();
warning = (msg) => {
(0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
};
err = (msg) => {
(0, import_hanji.render)(`${source_default.bold.red("Error")} ${msg}`);
};
info = (msg, greyMsg = "") => {
return `${source_default.blue.bold("Info:")} ${msg} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
};
grey = (msg) => {
return source_default.grey(msg);
};
error = (error2, greyMsg = "") => {
return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
};
schema4 = (schema6) => {
const tables = Object.values(schema6.tables);
let msg = source_default.bold(`${tables.length} tables
`);
msg += tables.map((t2) => {
const columnsCount = Object.values(t2.columns).length;
const indexesCount = Object.values(t2.indexes).length;
let foreignKeys = 0;
if (schema6.dialect !== "singlestore") {
foreignKeys = Object.values(t2.foreignKeys).length;
}
return `${source_default.bold.blue(t2.name)} ${source_default.gray(
`${columnsCount} columns ${indexesCount} indexes ${foreignKeys} fks`
)}`;
}).join("\n");
msg += "\n";
const enums = objectValues(
"enums" in schema6 ? "values" in schema6["enums"] ? schema6["enums"] : {} : {}
);
if (enums.length > 0) {
msg += "\n";
msg += source_default.bold(`${enums.length} enums
`);
msg += enums.map((it) => {
return `${source_default.bold.blue(it.name)} ${source_default.gray(
`[${Object.values(it.values).join(", ")}]`
)}`;
}).join("\n");
msg += "\n";
}
return msg;
};
isRenamePromptItem = (item) => {
return "from" in item && "to" in item;
};
ResolveColumnSelect = class extends import_hanji.Prompt {
constructor(tableName, base, data) {
super();
this.tableName = tableName;
this.base = base;
this.on("attach", (terminal) => terminal.toggleCursor("hide"));
this.data = new import_hanji.SelectState(data);
this.data.bind(this);
}
render(status) {
if (status === "submitted" || status === "aborted") {
return "\n";
}
let text = `
Is ${source_default.bold.blue(
this.base.name
)} column in ${source_default.bold.blue(
this.tableName
)} table created or renamed from another column?
`;
const isSelectedRenamed = isRenamePromptItem(
this.data.items[this.data.selectedIdx]
);
const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
const labelLength = this.data.items.filter((it) => isRenamePromptItem(it)).map((it) => {
return this.base.name.length + 3 + it["from"].name.length;
}).reduce((a, b) => {
if (a > b) {
return a;
}
return b;
}, 0);
this.data.items.forEach((it, idx) => {
const isSelected = idx === this.data.selectedIdx;
const isRenamed = isRenamePromptItem(it);
const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`;
text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
text += idx != this.data.items.length - 1 ? "\n" : "";
});
return text;
}
result() {
return this.data.items[this.data.selectedIdx];
}
};
tableKey = (it) => {
return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`;
};
ResolveSelectNamed = class extends import_hanji.Prompt {
constructor(base, data, entityType) {
super();
this.base = base;
this.entityType = entityType;
this.on("attach", (terminal) => terminal.toggleCursor("hide"));
this.state = new import_hanji.SelectState(data);
this.state.bind(this);
this.base = base;
}
render(status) {
if (status === "submitted" || status === "aborted") {
return "";
}
const key = this.base.name;
let text = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
const isSelectedRenamed = isRenamePromptItem(
this.state.items[this.state.selectedIdx]
);
const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_2) => {
const it = _2;
const keyFrom = it.from.name;
return key.length + 3 + keyFrom.length;
}).reduce((a, b) => {
if (a > b) {
return a;
}
return b;
}, 0);
const entityType = this.entityType;
this.state.items.forEach((it, idx) => {
const isSelected = idx === this.state.selectedIdx;
const isRenamed = isRenamePromptItem(it);
const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
text += idx != this.state.items.length - 1 ? "\n" : "";
});
return text;
}
result() {
return this.state.items[this.state.selectedIdx];
}
};
ResolveSelect = class extends import_hanji.Prompt {
constructor(base, data, entityType) {
super();
this.base = base;
this.entityType = entityType;
this.on("attach", (terminal) => terminal.toggleCursor("hide"));
this.state = new import_hanji.SelectState(data);
this.state.bind(this);
this.base = base;
}
render(status) {
if (status === "submitted" || status === "aborted") {
return "";
}
const key = tableKey(this.base);
let text = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
const isSelectedRenamed = isRenamePromptItem(
this.state.items[this.state.selectedIdx]
);
const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_2) => {
const it = _2;
const keyFrom = tableKey(it.from);
return key.length + 3 + keyFrom.length;
}).reduce((a, b) => {
if (a > b) {
return a;
}
return b;
}, 0);
const entityType = this.entityType;
this.state.items.forEach((it, idx) => {
const isSelected = idx === this.state.selectedIdx;
const isRenamed = isRenamePromptItem(it);
const title = isRenamed ? `${tableKey(it.from)} \u203A ${tableKey(it.to)}`.padEnd(labelLength, " ") : tableKey(it).padEnd(labelLength, " ");
const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
text += idx != this.state.items.length - 1 ? "\n" : "";
});
return text;
}
result() {
return this.state.items[this.state.selectedIdx];
}
};
ResolveSchemasSelect = class extends import_hanji.Prompt {
constructor(base, data) {
super();
this.base = base;
this.on("attach", (terminal) => terminal.toggleCursor("hide"));
this.state = new import_hanji.SelectState(data);
this.state.bind(this);
this.base = base;
}
render(status) {
if (status === "submitted" || status === "aborted") {
return "";
}
let text = `
Is ${source_default.bold.blue(
this.base.name
)} schema created or renamed from another schema?
`;
const isSelectedRenamed = isRenamePromptItem(
this.state.items[this.state.selectedIdx]
);
const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((it) => {
return this.base.name.length + 3 + it["from"].name.length;
}).reduce((a, b) => {
if (a > b) {
return a;
}
return b;
}, 0);
this.state.items.forEach((it, idx) => {
const isSelected = idx === this.state.selectedIdx;
const isRenamed = isRenamePromptItem(it);
const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename schema")}` : `${source_default.green("+")} ${title} ${source_default.gray("create schema")}`;
text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
text += idx != this.state.items.length - 1 ? "\n" : "";
});
return text;
}
result() {
return this.state.items[this.state.selectedIdx];
}
};
Spinner = class {
constructor(frames) {
this.frames = frames;
this.offset = 0;
this.tick = () => {
this.iterator();
};
this.value = () => {
return this.frames[this.offset];
};
this.iterator = () => {
this.offset += 1;
this.offset %= frames.length - 1;
};
}
};
IntrospectProgress = class extends import_hanji.TaskView {
constructor(hasEnums = false) {
super();
this.hasEnums = hasEnums;
this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
this.state = {
tables: {
count: 0,
name: "tables",
status: "fetching"
},
columns: {
count: 0,
name: "columns",
status: "fetching"
},
enums: {
count: 0,
name: "enums",
status: "fetching"
},
indexes: {
count: 0,
name: "indexes",
status: "fetching"
},
fks: {
count: 0,
name: "foreign keys",
status: "fetching"
},
policies: {
count: 0,
name: "policies",
status: "fetching"
},
checks: {
count: 0,
name: "check constraints",
status: "fetching"
},
views: {
count: 0,
name: "views",
status: "fetching"
}
};
this.formatCount = (count) => {
const width = Math.max.apply(
null,
Object.values(this.state).map((it) => it.count.toFixed(0).length)
);
return count.toFixed(0).padEnd(width, " ");
};
this.statusText = (spinner, stage) => {
const { name, count } = stage;
const isDone = stage.status === "done";
const prefix2 = isDone ? `[${source_default.green("\u2713")}]` : `[${spinner}]`;
const formattedCount = this.formatCount(count);
const suffix = isDone ? `${formattedCount} ${name} fetched` : `${formattedCount} ${name} fetching`;
return `${prefix2} ${suffix}
`;
};
this.timeout = setInterval(() => {
this.spinner.tick();
this.requestLayout();
}, 128);
this.on("detach", () => clearInterval(this.timeout));
}
update(stage, count, status) {
this.state[stage].count = count;
this.state[stage].status = status;
this.requestLayout();
}
render() {
let info2 = "";
const spin = this.spinner.value();
info2 += this.statusText(spin, this.state.tables);
info2 += this.statusText(spin, this.state.columns);
info2 += this.hasEnums ? this.statusText(spin, this.state.enums) : "";
info2 += this.statusText(spin, this.state.indexes);
info2 += this.statusText(spin, this.state.fks);
info2 += this.statusText(spin, this.state.policies);
info2 += this.statusText(spin, this.state.checks);
info2 += this.statusText(spin, this.state.views);
return info2;
}
};
MigrateProgress = class extends import_hanji.TaskView {
constructor() {
super();
this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
this.timeout = setInterval(() => {
this.spinner.tick();
this.requestLayout();
}, 128);
this.on("detach", () => clearInterval(this.timeout));
}
render(status) {
if (status === "pending") {
const spin = this.spinner.value();
return `[${spin}] applying migrations...`;
}
return `[${source_default.green("\u2713")}] migrations applied successfully!`;
}
};
ProgressView = class extends import_hanji.TaskView {
constructor(progressText, successText) {
super();
this.progressText = progressText;
this.successText = successText;
this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
this.timeout = setInterval(() => {
this.spinner.tick();
this.requestLayout();
}, 128);
this.on("detach", () => clearInterval(this.timeout));
}
render(status) {
if (status === "pending") {
const spin = this.spinner.value();
return `[${spin}] ${this.progressText}
`;
}
return `[${source_default.green("\u2713")}] ${this.successText}
`;
}
};
DropMigrationView = class extends import_hanji.Prompt {
constructor(data) {
super();
this.on("attach", (terminal) => terminal.toggleCursor("hide"));
this.data = new import_hanji.SelectState(data);
this.data.selectedIdx = data.length - 1;
this.data.bind(this);
}
render(status) {
if (status === "submitted" || status === "aborted") {
return "\n";
}
let text = source_default.bold("Please select migration to drop:\n");
const selectedPrefix = source_default.yellow("\u276F ");
const data = trimmedRange(this.data.items, this.data.selectedIdx, 9);
const labelLength = data.trimmed.map((it) => it.tag.length).reduce((a, b) => {
if (a > b) {
return a;
}
return b;
}, 0);
text += data.startTrimmed ? " ...\n" : "";
data.trimmed.forEach((it, idx) => {
const isSelected = idx === this.data.selectedIdx - data.offset;
let title = it.tag.padEnd(labelLength, " ");
title = isSelected ? source_default.yellow(title) : title;
text += isSelected ? `${selectedPrefix}${title}` : ` ${title}`;
text += idx != this.data.items.length - 1 ? "\n" : "";
});
text += data.endTrimmed ? " ...\n" : "";
return text;
}
result() {
return this.data.items[this.data.selectedIdx];
}
};
trimmedRange = (arr, index5, limitLines) => {
const limit = limitLines - 2;
const sideLimit = Math.round(limit / 2);
const endTrimmed = arr.length - sideLimit > index5;
const startTrimmed = index5 > sideLimit - 1;
const paddingStart = Math.max(index5 + sideLimit - arr.length, 0);
const paddingEnd = Math.min(index5 - sideLimit + 1, 0);
const d1 = endTrimmed ? 1 : 0;
const d2 = startTrimmed ? 0 : 1;
const start = Math.max(0, index5 - sideLimit + d1 - paddingStart);
const end = Math.min(arr.length, index5 + sideLimit + d2 - paddingEnd);
return {
trimmed: arr.slice(start, end),
offset: start,
startTrimmed,
endTrimmed
};
};
}
});
// src/utils.ts
function isPgArrayType(sqlType) {
return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
}
function findAddedAndRemoved(columnNames1, columnNames2) {
const set1 = new Set(columnNames1);
const set2 = new Set(columnNames2);
const addedColumns = columnNames2.filter((it) => !set1.has(it));
const removedColumns = columnNames1.filter((it) => !set2.has(it));
return { addedColumns, removedColumns };
}
function escapeSingleQuotes(str) {
return str.replace(/'/g, "''");
}
function unescapeSingleQuotes(str, ignoreFirstAndLastChar) {
const regex = ignoreFirstAndLastChar ? /(?<!^)'(?!$)/g : /'/g;
return str.replace(/''/g, "'").replace(regex, "\\'");
}
var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl;
var init_utils2 = __esm({
"src/utils.ts"() {
"use strict";
init_source();
import_fs = require("fs");
import_path = require("path");
import_url = require("url");
init_views();
init_global();
init_mysqlSchema();
init_pgSchema();
init_singlestoreSchema();
init_sqliteSchema();
copy = (it) => {
return JSON.parse(JSON.stringify(it));
};
objectValues = (obj) => {
return Object.values(obj);
};
assertV1OutFolder = (out) => {
if (!(0, import_fs.existsSync)(out))
return;
const oldMigrationFolders = (0, import_fs.readdirSync)(out).filter(
(it) => it.length === 14 && /^\d+$/.test(it)
);
if (oldMigrationFolders.length > 0) {
console.log(
`Your migrations folder format is outdated, please run ${source_default.green.bold(
`drizzle-kit up`
)}`
);
process.exit(1);
}
};
dryJournal = (dialect6) => {
return {
version: snapshotVersion,
dialect: dialect6,
entries: []
};
};
prepareOutFolder = (out, dialect6) => {
const meta = (0, import_path.join)(out, "meta");
const journalPath = (0, import_path.join)(meta, "_journal.json");
if (!(0, import_fs.existsSync)((0, import_path.join)(out, "meta"))) {
(0, import_fs.mkdirSync)(meta, { recursive: true });
(0, import_fs.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect6)));
}
const journal = JSON.parse((0, import_fs.readFileSync)(journalPath).toString());
const snapshots = (0, import_fs.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path.join)(meta, it));
snapshots.sort();
return { meta, snapshots, journal };
};
validatorForDialect = (dialect6) => {
switch (dialect6) {
case "postgresql":
return { validator: backwardCompatiblePgSchema, version: 7 };
case "sqlite":
return { validator: backwardCompatibleSqliteSchema, version: 6 };
case "turso":
return { validator: backwardCompatibleSqliteSchema, version: 6 };
case "mysql":
return { validator: backwardCompatibleMysqlSchema, version: 5 };
case "singlestore":
return { validator: backwardCompatibleSingleStoreSchema, version: 1 };
}
};
validateWithReport = (snapshots, dialect6) => {
const { validator: validator2, version: version3 } = validatorForDialect(dialect6);
const result = snapshots.reduce(
(accum, it) => {
const raw2 = JSON.parse((0, import_fs.readFileSync)(`./${it}`).toString());
accum.rawMap[it] = raw2;
if (raw2["version"] && Number(raw2["version"]) > version3) {
console.log(
info(
`${it} snapshot is of unsupported version, please update drizzle-kit`
)
);
process.exit(0);
}
const result2 = validator2.safeParse(raw2);
if (!result2.success) {
accum.malformed.push(it);
return accum;
}
const snapshot = result2.data;
if (snapshot.version !== String(version3)) {
accum.nonLatest.push(it);
return accum;
}
const idEntry = accum.idsMap[snapshot["prevId"]] ?? {
parent: it,
snapshots: []
};
idEntry.snapshots.push(it);
accum.idsMap[snapshot["prevId"]] = idEntry;
return accum;
},
{
malformed: [],
nonLatest: [],
idToNameMap: {},
idsMap: {},
rawMap: {}
}
);
return result;
};
prepareMigrationFolder = (outFolder = "drizzle", dialect6) => {
const { snapshots, journal } = prepareOutFolder(outFolder, dialect6);
const report = validateWithReport(snapshots, dialect6);
if (report.nonLatest.length > 0) {
console.log(
report.nonLatest.map((it) => {
return `${it}/snapshot.json is not of the latest version`;
}).concat(`Run ${source_default.green.bold(`drizzle-kit up`)}`).join("\n")
);
process.exit(0);
}
if (report.malformed.length) {
const message2 = report.malformed.map((it) => {
return `${it} data is malformed`;
}).join("\n");
console.log(message2);
}
const collisionEntries = Object.entries(report.idsMap).filter(
(it) => it[1].snapshots.length > 1
);
const message = collisionEntries.map((it) => {
const data = it[1];
return `[${data.snapshots.join(
", "
)}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
}).join("\n").trim();
if (message) {
console.log(source_default.red.bold("Error:"), message);
}
const abort = report.malformed.length || collisionEntries.length > 0;
if (abort) {
process.exit(0);
}
return { snapshots, journal };
};
prepareMigrationMeta = (schemas, tables, columns) => {
const _meta = {
schemas: {},
tables: {},
columns: {}
};
schemas.forEach((it) => {
const from = schemaRenameKey(it.from);
const to = schemaRenameKey(it.to);
_meta.schemas[from] = to;
});
tables.forEach((it) => {
const from = tableRenameKey(it.from);
const to = tableRenameKey(it.to);
_meta.tables[from] = to;
});
columns.forEach((it) => {
const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
_meta.columns[from] = to;
});
return _meta;
};
schemaRenameKey = (it) => {
return it;
};
tableRenameKey = (it) => {
const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
return out;
};
columnRenameKey = (table5, schema6, column9) => {
const out = schema6 ? `"${schema6}"."${table5}"."${column9}"` : `"${table5}"."${column9}"`;
return out;
};
normaliseSQLiteUrl = (it, type) => {
if (type === "libsql") {
if (it.startsWith("file:")) {
return it;
}
try {
const url = (0, import_url.parse)(it);
if (url.protocol === null) {
return `file:${it}`;
}
return it;
} catch (e2) {
return `file:${it}`;
}
}
if (type === "better-sqlite") {
if (it.startsWith("file:")) {
return it.substring(5);
}
return it;
}
assertUnreachable(type);
};
normalisePGliteUrl = (it) => {
if (it.startsWith("file:")) {
return it.substring(5);
}
return it;
};
}
});
// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js
var require_old = __commonJS({
"../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js"(exports2) {
var pathModule = require("path");
var isWindows = process.platform === "win32";
var fs7 = require("fs");
var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
function rethrow() {
var callback;
if (DEBUG) {
var backtrace = new Error();
callback = debugCallback;
} else
callback = missingCallback;
return callback;
function debugCallback(err2) {
if (err2) {
backtrace.message = err2.message;
err2 = backtrace;
missingCallback(err2);
}
}
function missingCallback(err2) {
if (err2) {
if (process.throwDeprecation)
throw err2;
else if (!process.noDeprecation) {
var msg = "fs: missing callback " + (err2.stack || err2.message);
if (process.traceDeprecation)
console.trace(msg);
else
console.error(msg);
}
}
}
}
function maybeCallback(cb) {
return typeof cb === "function" ? cb : rethrow();
}
var normalize = pathModule.normalize;
if (isWindows) {
nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
} else {
nextPartRe = /(.*?)(?:[\/]+|$)/g;
}
var nextPartRe;
if (isWindows) {
splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
} else {
splitRootRe = /^[\/]*/;
}
var splitRootRe;
exports2.realpathSync = function realpathSync(p, cache) {
p = pathModule.resolve(p);
if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
return cache[p];
}
var original = p, seenLinks = {}, knownHard = {};
var pos;
var current;
var base;
var previous;
start();
function start() {
var m2 = splitRootRe.exec(p);
pos = m2[0].length;
current = m2[0];
base = m2[0];
previous = "";
if (isWindows && !knownHard[base]) {
fs7.lstatSync(base);
knownHard[base] = true;
}
}
while (pos < p.length) {
nextPartRe.lastIndex = pos;
var result = nextPartRe.exec(p);
previous = current;
current += result[0];
base = previous + result[1];
pos = nextPartRe.lastIndex;
if (knownHard[base] || cache && cache[base] === base) {
continue;
}
var resolvedLink;
if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
resolvedLink = cache[base];
} else {
var stat2 = fs7.lstatSync(base);
if (!stat2.isSymbolicLink()) {
knownHard[base] = true;
if (cache)
cache[base] = base;
continue;
}
var linkTarget = null;
if (!isWindows) {
var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
if (seenLinks.hasOwnProperty(id)) {
linkTarget = seenLinks[id];
}
}
if (linkTarget === null) {
fs7.statSync(base);
linkTarget = fs7.readlinkSync(base);
}
resolvedLink = pathModule.resolve(previous, linkTarget);
if (cache)
cache[base] = resolvedLink;
if (!isWindows)
seenLinks[id] = linkTarget;
}
p = pathModule.resolve(resolvedLink, p.slice(pos));
start();
}
if (cache)
cache[original] = p;
return p;
};
exports2.realpath = function realpath(p, cache, cb) {
if (typeof cb !== "function") {
cb = maybeCallback(cache);
cache = null;
}
p = pathModule.resolve(p);
if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
return process.nextTick(cb.bind(null, null, cache[p]));
}
var original = p, seenLinks = {}, knownHard = {};
var pos;
var current;
var base;
var previous;
start();
function start() {
var m2 = splitRootRe.exec(p);
pos = m2[0].length;
current = m2[0];
base = m2[0];
previous = "";
if (isWindows && !knownHard[base]) {
fs7.lstat(base, function(err2) {
if (err2)
return cb(err2);
knownHard[base] = true;
LOOP();
});
} else {
process.nextTick(LOOP);
}
}
function LOOP() {
if (pos >= p.length) {
if (cache)
cache[original] = p;
return cb(null, p);
}
nextPartRe.lastIndex = pos;
var result = nextPartRe.exec(p);
previous = current;
current += result[0];
base = previous + result[1];
pos = nextPartRe.lastIndex;
if (knownHard[base] || cache && cache[base] === base) {
return process.nextTick(LOOP);
}
if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
return gotResolvedLink(cache[base]);
}
return fs7.lstat(base, gotStat);
}
function gotStat(err2, stat2) {
if (err2)
return cb(err2);
if (!stat2.isSymbolicLink()) {
knownHard[base] = true;
if (cache)
cache[base] = base;
return process.nextTick(LOOP);
}
if (!isWindows) {
var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
if (seenLinks.hasOwnProperty(id)) {
return gotTarget(null, seenLinks[id], base);
}
}
fs7.stat(base, function(err3) {
if (err3)
return cb(err3);
fs7.readlink(base, function(err4, target) {
if (!isWindows)
seenLinks[id] = target;
gotTarget(err4, target);
});
});
}
function gotTarget(err2, target, base2) {
if (err2)
return cb(err2);
var resolvedLink = pathModule.resolve(previous, target);
if (cache)
cache[base2] = resolvedLink;
gotResolvedLink(resolvedLink);
}
function gotResolvedLink(resolvedLink) {
p = pathModule.resolve(resolvedLink, p.slice(pos));
start();
}
};
}
});
// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js
var require_fs = __commonJS({
"../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js"(exports2, module2) {
module2.exports = realpath;
realpath.realpath = realpath;
realpath.sync = realpathSync;
realpath.realpathSync = realpathSync;
realpath.monkeypatch = monkeypatch;
realpath.unmonkeypatch = unmonkeypatch;
var fs7 = require("fs");
var origRealpath = fs7.realpath;
var origRealpathSync = fs7.realpathSync;
var version3 = process.version;
var ok = /^v[0-5]\./.test(version3);
var old = require_old();
function newError(er) {
return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
}
function realpath(p, cache, cb) {
if (ok) {
return origRealpath(p, cache, cb);
}
if (typeof cache === "function") {
cb = cache;
cache = null;
}
origRealpath(p, cache, function(er, result) {
if (newError(er)) {
old.realpath(p, cache, cb);
} else {
cb(er, result);
}
});
}
function realpathSync(p, cache) {
if (ok) {
return origRealpathSync(p, cache);
}
try {
return origRealpathSync(p, cache);
} catch (er) {
if (newError(er)) {
return old.realpathSync(p, cache);
} else {
throw er;
}
}
}
function monkeypatch() {
fs7.realpath = realpath;
fs7.realpathSync = realpathSync;
}
function unmonkeypatch() {
fs7.realpath = origRealpath;
fs7.realpathSync = origRealpathSync;
}
}
});
// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js
var require_path = __commonJS({
"../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports2, module2) {
var isWindows = typeof process === "object" && process && process.platform === "win32";
module2.exports = isWindows ? { sep: "\\" } : { sep: "/" };
}
});
// ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
"../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports2, module2) {
"use strict";
module2.exports = balanced;
function balanced(a, b, str) {
if (a instanceof RegExp)
a = maybeMatch(a, str);
if (b instanceof RegExp)
b = maybeMatch(b, str);
var r2 = range(a, b, str);
return r2 && {
start: r2[0],
end: r2[1],
pre: str.slice(0, r2[0]),
body: str.slice(r2[0] + a.length, r2[1]),
post: str.slice(r2[1] + b.length)
};
}
function maybeMatch(reg, str) {
var m2 = str.match(reg);
return m2 ? m2[0] : null;
}
balanced.range = range;
function range(a, b, str) {
var begs, beg, left, right, result;
var ai = str.indexOf(a);
var bi = str.indexOf(b, ai + 1);
var i2 = ai;
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i2 >= 0 && !result) {
if (i2 == ai) {
begs.push(i2);
ai = str.indexOf(a, i2 + 1);
} else if (begs.length == 1) {
result = [begs.pop(), bi];
} else {
beg = begs.pop();
if (beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i2 + 1);
}
i2 = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [left, right];
}
}
return result;
}
}
});
// ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
"../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports2, module2) {
var balanced = require_balanced_match();
module2.exports = expandTop;
var escSlash = "\0SLASH" + Math.random() + "\0";
var escOpen = "\0OPEN" + Math.random() + "\0";
var escClose = "\0CLOSE" + Math.random() + "\0";
var escComma = "\0COMMA" + Math.random() + "\0";
var escPeriod = "\0PERIOD" + Math.random() + "\0";
function numeric(str) {
return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
}
function parseCommaParts(str) {
if (!str)
return [""];
var parts = [];
var m2 = balanced("{", "}", str);
if (!m2)
return str.split(",");
var pre = m2.pre;
var body = m2.body;
var post = m2.post;
var p = pre.split(",");
p[p.length - 1] += "{" + body + "}";
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length - 1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
if (str.substr(0, 2) === "{}") {
str = "\\{\\}" + str.substr(2);
}
return expand2(escapeBraces(str), true).map(unescapeBraces);
}
function embrace(str) {
return "{" + str + "}";
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i2, y) {
return i2 <= y;
}
function gte(i2, y) {
return i2 >= y;
}
function expand2(str, isTop) {
var expansions = [];
var m2 = balanced("{", "}", str);
if (!m2)
return [str];
var pre = m2.pre;
var post = m2.post.length ? expand2(m2.post, false) : [""];
if (/\$$/.test(m2.pre)) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + "{" + m2.body + "}" + post[k];
expansions.push(expansion);
}
} else {
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m2.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m2.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m2.body.indexOf(",") >= 0;
if (!isSequence && !isOptions) {
if (m2.post.match(/,.*\}/)) {
str = m2.pre + "{" + m2.body + escClose + m2.post;
return expand2(str);
}
return [str];
}
var n;
if (isSequence) {
n = m2.body.split(/\.\./);
} else {
n = parseCommaParts(m2.body);
if (n.length === 1) {
n = expand2(n[0], false).map(embrace);
if (n.length === 1) {
return post.map(function(p) {
return m2.pre + n[0] + p;
});
}
}
}
var N;
if (isSequence) {
var x2 = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length);
var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
var test = lte;
var reverse = y < x2;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i2 = x2; test(i2, y); i2 += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i2);
if (c === "\\")
c = "";
} else {
c = String(i2);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z2 = new Array(need + 1).join("0");
if (i2 < 0)
c = "-" + z2 + c.slice(1);
else
c = z2 + c;
}
}
}
N.push(c);
}
} else {
N = [];
for (var j = 0; j < n.length; j++) {
N.push.apply(N, expand2(n[j], false));
}
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
}
return expansions;
}
}
});
// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js
var require_minimatch = __commonJS({
"../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports2, module2) {
var minimatch2 = module2.exports = (p, pattern, options = {}) => {
assertValidPattern2(pattern);
if (!options.nocomment && pattern.charAt(0) === "#") {
return false;
}
return new Minimatch2(pattern, options).match(p);
};
module2.exports = minimatch2;
var path4 = require_path();
minimatch2.sep = path4.sep;
var GLOBSTAR2 = Symbol("globstar **");
minimatch2.GLOBSTAR = GLOBSTAR2;
var expand2 = require_brace_expansion();
var plTypes2 = {
"!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
"?": { open: "(?:", close: ")?" },
"+": { open: "(?:", close: ")+" },
"*": { open: "(?:", close: ")*" },
"@": { open: "(?:", close: ")" }
};
var qmark2 = "[^/]";
var star2 = qmark2 + "*?";
var twoStarDot2 = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
var twoStarNoDot2 = "(?:(?!(?:\\/|^)\\.).)*?";
var charSet2 = (s2) => s2.split("").reduce((set, c) => {
set[c] = true;
return set;
}, {});
var reSpecials2 = charSet2("().*{}+?[]^$\\!");
var addPatternStartSet2 = charSet2("[.(");
var slashSplit = /\/+/;
minimatch2.filter = (pattern, options = {}) => (p, i2, list) => minimatch2(p, pattern, options);
var ext2 = (a, b = {}) => {
const t2 = {};
Object.keys(a).forEach((k) => t2[k] = a[k]);
Object.keys(b).forEach((k) => t2[k] = b[k]);
return t2;
};
minimatch2.defaults = (def) => {
if (!def || typeof def !== "object" || !Object.keys(def).length) {
return minimatch2;
}
const orig = minimatch2;
const m2 = (p, pattern, options) => orig(p, pattern, ext2(def, options));
m2.Minimatch = class Minimatch extends orig.Minimatch {
constructor(pattern, options) {
super(pattern, ext2(def, options));
}
};
m2.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
m2.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
m2.defaults = (options) => orig.defaults(ext2(def, options));
m2.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
m2.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
m2.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
return m2;
};
minimatch2.braceExpand = (pattern, options) => braceExpand2(pattern, options);
var braceExpand2 = (pattern, options = {}) => {
assertValidPattern2(pattern);
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
return [pattern];
}
return expand2(pattern);
};
var MAX_PATTERN_LENGTH2 = 1024 * 64;
var assertValidPattern2 = (pattern) => {
if (typeof pattern !== "string") {
throw new TypeError("invalid pattern");
}
if (pattern.length > MAX_PATTERN_LENGTH2) {
throw new TypeError("pattern is too long");
}
};
var SUBPARSE = Symbol("subparse");
minimatch2.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
minimatch2.match = (list, pattern, options = {}) => {
const mm = new Minimatch2(pattern, options);
list = list.filter((f3) => mm.match(f3));
if (mm.options.nonull && !list.length) {
list.push(pattern);
}
return list;
};
var globUnescape2 = (s2) => s2.replace(/\\(.)/g, "$1");
var charUnescape = (s2) => s2.replace(/\\([^-\]])/g, "$1");
var regExpEscape2 = (s2) => s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var braExpEscape = (s2) => s2.replace(/[[\]\\]/g, "\\$&");
var Minimatch2 = class {
constructor(pattern, options) {
assertValidPattern2(pattern);
if (!options)
options = {};
this.options = options;
this.set = [];
this.pattern = pattern;
this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
if (this.windowsPathsNoEscape) {
this.pattern = this.pattern.replace(/\\/g, "/");
}
this.regexp = null;
this.negate = false;
this.comment = false;
this.empty = false;
this.partial = !!options.partial;
this.make();
}
debug() {
}
make() {
const pattern = this.pattern;
const options = this.options;
if (!options.nocomment && pattern.charAt(0) === "#") {
this.comment = true;
return;
}
if (!pattern) {
this.empty = true;
return;
}
this.parseNegate();
let set = this.globSet = this.braceExpand();
if (options.debug)
this.debug = (...args) => console.error(...args);
this.debug(this.pattern, set);
set = this.globParts = set.map((s2) => s2.split(slashSplit));
this.debug(this.pattern, set);
set = set.map((s2, si, set2) => s2.map(this.parse, this));
this.debug(this.pattern, set);
set = set.filter((s2) => s2.indexOf(false) === -1);
this.debug(this.pattern, set);
this.set = set;
}
parseNegate() {
if (this.options.nonegate)
return;
const pattern = this.pattern;
let negate = false;
let negateOffset = 0;
for (let i2 = 0; i2 < pattern.length && pattern.charAt(i2) === "!"; i2++) {
negate = !negate;
negateOffset++;
}
if (negateOffset)
this.pattern = pattern.slice(negateOffset);
this.negate = negate;
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
matchOne(file, pattern, partial) {
var options = this.options;
this.debug(
"matchOne",
{ "this": this, file, pattern }
);
this.debug("matchOne", file.length, pattern.length);
for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
this.debug("matchOne loop");
var p = pattern[pi];
var f3 = file[fi];
this.debug(pattern, p, f3);
if (p === false)
return false;
if (p === GLOBSTAR2) {
this.debug("GLOBSTAR", [pattern, p, f3]);
var fr = fi;
var pr = pi + 1;
if (pr === pl) {
this.debug("** at the end");
for (; fi < fl; fi++) {
if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
return false;
}
return true;
}
while (fr < fl) {
var swallowee = file[fr];
this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug("globstar found match!", fr, fl, swallowee);
return true;
} else {
if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
this.debug("dot detected!", file, fr, pattern, pr);
break;
}
this.debug("globstar swallow a segment, and continue");
fr++;
}
}
if (partial) {
this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
if (fr === fl)
return true;
}
return false;
}
var hit;
if (typeof p === "string") {
hit = f3 === p;
this.debug("string match", p, f3, hit);
} else {
hit = f3.match(p);
this.debug("pattern match", p, f3, hit);
}
if (!hit)
return false;
}
if (fi === fl && pi === pl) {
return true;
} else if (fi === fl) {
return partial;
} else if (pi === pl) {
return fi === fl - 1 && file[fi] === "";
}
throw new Error("wtf?");
}
braceExpand() {
return braceExpand2(this.pattern, this.options);
}
parse(pattern, isSub) {
assertValidPattern2(pattern);
const options = this.options;
if (pattern === "**") {
if (!options.noglobstar)
return GLOBSTAR2;
else
pattern = "*";
}
if (pattern === "")
return "";
let re = "";
let hasMagic = false;
let escaping = false;
const patternListStack = [];
const negativeLists = [];
let stateChar;
let inClass = false;
let reClassStart = -1;
let classStart = -1;
let cs;
let pl;
let sp;
let dotTravAllowed = pattern.charAt(0) === ".";
let dotFileAllowed = options.dot || dotTravAllowed;
const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
const subPatternStart = (p) => p.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
const clearStateChar = () => {
if (stateChar) {
switch (stateChar) {
case "*":
re += star2;
hasMagic = true;
break;
case "?":
re += qmark2;
hasMagic = true;
break;
default:
re += "\\" + stateChar;
break;
}
this.debug("clearStateChar %j %j", stateChar, re);
stateChar = false;
}
};
for (let i2 = 0, c; i2 < pattern.length && (c = pattern.charAt(i2)); i2++) {
this.debug("%s %s %s %j", pattern, i2, re, c);
if (escaping) {
if (c === "/") {
return false;
}
if (reSpecials2[c]) {
re += "\\";
}
re += c;
escaping = false;
continue;
}
switch (c) {
case "/": {
return false;
}
case "\\":
if (inClass && pattern.charAt(i2 + 1) === "-") {
re += c;
continue;
}
clearStateChar();
escaping = true;
continue;
case "?":
case "*":
case "+":
case "@":
case "!":
this.debug("%s %s %s %j <-- stateChar", pattern, i2, re, c);
if (inClass) {
this.debug(" in class");
if (c === "!" && i2 === classStart + 1)
c = "^";
re += c;
continue;
}
this.debug("call clearStateChar %j", stateChar);
clearStateChar();
stateChar = c;
if (options.noext)
clearStateChar();
continue;
case "(": {
if (inClass) {
re += "(";
continue;
}
if (!stateChar) {
re += "\\(";
continue;
}
const plEntry = {
type: stateChar,
start: i2 - 1,
reStart: re.length,
open: plTypes2[stateChar].open,
close: plTypes2[stateChar].close
};
this.debug(this.pattern, " ", plEntry);
patternListStack.push(plEntry);
re += plEntry.open;
if (plEntry.start === 0 && plEntry.type !== "!") {
dotTravAllowed = true;
re += subPatternStart(pattern.slice(i2 + 1));
}
this.debug("plType %j %j", stateChar, re);
stateChar = false;
continue;
}
case ")": {
const plEntry = patternListStack[patternListStack.length - 1];
if (inClass || !plEntry) {
re += "\\)";
continue;
}
patternListStack.pop();
clearStateChar();
hasMagic = true;
pl = plEntry;
re += pl.close;
if (pl.type === "!") {
negativeLists.push(Object.assign(pl, { reEnd: re.length }));
}
continue;
}
case "|": {
const plEntry = patternListStack[patternListStack.length - 1];
if (inClass || !plEntry) {
re += "\\|";
continue;
}
clearStateChar();
re += "|";
if (plEntry.start === 0 && plEntry.type !== "!") {
dotTravAllowed = true;
re += subPatternStart(pattern.slice(i2 + 1));
}
continue;
}
case "[":
clearStateChar();
if (inClass) {
re += "\\" + c;
continue;
}
inClass = true;
classStart = i2;
reClassStart = re.length;
re += c;
continue;
case "]":
if (i2 === classStart + 1 || !inClass) {
re += "\\" + c;
continue;
}
cs = pattern.substring(classStart + 1, i2);
try {
RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
re += c;
} catch (er) {
re = re.substring(0, reClassStart) + "(?:$.)";
}
hasMagic = true;
inClass = false;
continue;
default:
clearStateChar();
if (reSpecials2[c] && !(c === "^" && inClass)) {
re += "\\";
}
re += c;
break;
}
}
if (inClass) {
cs = pattern.slice(classStart + 1);
sp = this.parse(cs, SUBPARSE);
re = re.substring(0, reClassStart) + "\\[" + sp[0];
hasMagic = hasMagic || sp[1];
}
for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
let tail;
tail = re.slice(pl.reStart + pl.open.length);
this.debug("setting tail", re, pl);
tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_2, $1, $2) => {
if (!$2) {
$2 = "\\";
}
return $1 + $1 + $2 + "|";
});
this.debug("tail=%j\n %s", tail, tail, pl, re);
const t2 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
hasMagic = true;
re = re.slice(0, pl.reStart) + t2 + "\\(" + tail;
}
clearStateChar();
if (escaping) {
re += "\\\\";
}
const addPatternStart = addPatternStartSet2[re.charAt(0)];
for (let n = negativeLists.length - 1; n > -1; n--) {
const nl = negativeLists[n];
const nlBefore = re.slice(0, nl.reStart);
const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
let nlAfter = re.slice(nl.reEnd);
const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
const closeParensBefore = nlBefore.split(")").length;
const openParensBefore = nlBefore.split("(").length - closeParensBefore;
let cleanAfter = nlAfter;
for (let i2 = 0; i2 < openParensBefore; i2++) {
cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
}
nlAfter = cleanAfter;
const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
}
if (re !== "" && hasMagic) {
re = "(?=.)" + re;
}
if (addPatternStart) {
re = patternStart() + re;
}
if (isSub === SUBPARSE) {
return [re, hasMagic];
}
if (options.nocase && !hasMagic) {
hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
}
if (!hasMagic) {
return globUnescape2(pattern);
}
const flags = options.nocase ? "i" : "";
try {
return Object.assign(new RegExp("^" + re + "$", flags), {
_glob: pattern,
_src: re
});
} catch (er) {
return new RegExp("$.");
}
}
makeRe() {
if (this.regexp || this.regexp === false)
return this.regexp;
const set = this.set;
if (!set.length) {
this.regexp = false;
return this.regexp;
}
const options = this.options;
const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot2 : twoStarNoDot2;
const flags = options.nocase ? "i" : "";
let re = set.map((pattern) => {
pattern = pattern.map(
(p) => typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR2 ? GLOBSTAR2 : p._src
).reduce((set2, p) => {
if (!(set2[set2.length - 1] === GLOBSTAR2 && p === GLOBSTAR2)) {
set2.push(p);
}
return set2;
}, []);
pattern.forEach((p, i2) => {
if (p !== GLOBSTAR2 || pattern[i2 - 1] === GLOBSTAR2) {
return;
}
if (i2 === 0) {
if (pattern.length > 1) {
pattern[i2 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i2 + 1];
} else {
pattern[i2] = twoStar;
}
} else if (i2 === pattern.length - 1) {
pattern[i2 - 1] += "(?:\\/|" + twoStar + ")?";
} else {
pattern[i2 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i2 + 1];
pattern[i2 + 1] = GLOBSTAR2;
}
});
return pattern.filter((p) => p !== GLOBSTAR2).join("/");
}).join("|");
re = "^(?:" + re + ")$";
if (this.negate)
re = "^(?!" + re + ").*$";
try {
this.regexp = new RegExp(re, flags);
} catch (ex) {
this.regexp = false;
}
return this.regexp;
}
match(f3, partial = this.partial) {
this.debug("match", f3, this.pattern);
if (this.comment)
return false;
if (this.empty)
return f3 === "";
if (f3 === "/" && partial)
return true;
const options = this.options;
if (path4.sep !== "/") {
f3 = f3.split(path4.sep).join("/");
}
f3 = f3.split(slashSplit);
this.debug(this.pattern, "split", f3);
const set = this.set;
this.debug(this.pattern, "set", set);
let filename;
for (let i2 = f3.length - 1; i2 >= 0; i2--) {
filename = f3[i2];
if (filename)
break;
}
for (let i2 = 0; i2 < set.length; i2++) {
const pattern = set[i2];
let file = f3;
if (options.matchBase && pattern.length === 1) {
file = [filename];
}
const hit = this.matchOne(file, pattern, partial);
if (hit) {
if (options.flipNegate)
return true;
return !this.negate;
}
}
if (options.flipNegate)
return false;
return this.negate;
}
static defaults(def) {
return minimatch2.defaults(def).Minimatch;
}
};
minimatch2.Minimatch = Minimatch2;
}
});
// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js
var require_inherits_browser = __commonJS({
"../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports2, module2) {
if (typeof Object.create === "function") {
module2.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
};
} else {
module2.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor;
var TempCtor = function() {
};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
};
}
}
});
// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js
var require_inherits = __commonJS({
"../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports2, module2) {
try {
util2 = require("util");
if (typeof util2.inherits !== "function")
throw "";
module2.exports = util2.inherits;
} catch (e2) {
module2.exports = require_inherits_browser();
}
var util2;
}
});
// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js
var require_common = __commonJS({
"../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js"(exports2) {
exports2.setopts = setopts;
exports2.ownProp = ownProp;
exports2.makeAbs = makeAbs;
exports2.finish = finish;
exports2.mark = mark;
exports2.isIgnored = isIgnored;
exports2.childrenIgnored = childrenIgnored;
function ownProp(obj, field) {
return Object.prototype.hasOwnProperty.call(obj, field);
}
var fs7 = require("fs");
var path4 = require("path");
var minimatch2 = require_minimatch();
var isAbsolute = require("path").isAbsolute;
var Minimatch2 = minimatch2.Minimatch;
function alphasort(a, b) {
return a.localeCompare(b, "en");
}
function setupIgnores(self2, options) {
self2.ignore = options.ignore || [];
if (!Array.isArray(self2.ignore))
self2.ignore = [self2.ignore];
if (self2.ignore.length) {
self2.ignore = self2.ignore.map(ignoreMap);
}
}
function ignoreMap(pattern) {
var gmatcher = null;
if (pattern.slice(-3) === "/**") {
var gpattern = pattern.replace(/(\/\*\*)+$/, "");
gmatcher = new Minimatch2(gpattern, { dot: true });
}
return {
matcher: new Minimatch2(pattern, { dot: true }),
gmatcher
};
}
function setopts(self2, pattern, options) {
if (!options)
options = {};
if (options.matchBase && -1 === pattern.indexOf("/")) {
if (options.noglobstar) {
throw new Error("base matching requires globstar");
}
pattern = "**/" + pattern;
}
self2.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
if (self2.windowsPathsNoEscape) {
pattern = pattern.replace(/\\/g, "/");
}
self2.silent = !!options.silent;
self2.pattern = pattern;
self2.strict = options.strict !== false;
self2.realpath = !!options.realpath;
self2.realpathCache = options.realpathCache || /* @__PURE__ */ Object.create(null);
self2.follow = !!options.follow;
self2.dot = !!options.dot;
self2.mark = !!options.mark;
self2.nodir = !!options.nodir;
if (self2.nodir)
self2.mark = true;
self2.sync = !!options.sync;
self2.nounique = !!options.nounique;
self2.nonull = !!options.nonull;
self2.nosort = !!options.nosort;
self2.nocase = !!options.nocase;
self2.stat = !!options.stat;
self2.noprocess = !!options.noprocess;
self2.absolute = !!options.absolute;
self2.fs = options.fs || fs7;
self2.maxLength = options.maxLength || Infinity;
self2.cache = options.cache || /* @__PURE__ */ Object.create(null);
self2.statCache = options.statCache || /* @__PURE__ */ Object.create(null);
self2.symlinks = options.symlinks || /* @__PURE__ */ Object.create(null);
setupIgnores(self2, options);
self2.changedCwd = false;
var cwd = process.cwd();
if (!ownProp(options, "cwd"))
self2.cwd = path4.resolve(cwd);
else {
self2.cwd = path4.resolve(options.cwd);
self2.changedCwd = self2.cwd !== cwd;
}
self2.root = options.root || path4.resolve(self2.cwd, "/");
self2.root = path4.resolve(self2.root);
self2.cwdAbs = isAbsolute(self2.cwd) ? self2.cwd : makeAbs(self2, self2.cwd);
self2.nomount = !!options.nomount;
if (process.platform === "win32") {
self2.root = self2.root.replace(/\\/g, "/");
self2.cwd = self2.cwd.replace(/\\/g, "/");
self2.cwdAbs = self2.cwdAbs.replace(/\\/g, "/");
}
options.nonegate = true;
options.nocomment = true;
self2.minimatch = new Minimatch2(pattern, options);
self2.options = self2.minimatch.options;
}
function finish(self2) {
var nou = self2.nounique;
var all = nou ? [] : /* @__PURE__ */ Object.create(null);
for (var i2 = 0, l = self2.matches.length; i2 < l; i2++) {
var matches = self2.matches[i2];
if (!matches || Object.keys(matches).length === 0) {
if (self2.nonull) {
var literal = self2.minimatch.globSet[i2];
if (nou)
all.push(literal);
else
all[literal] = true;
}
} else {
var m2 = Object.keys(matches);
if (nou)
all.push.apply(all, m2);
else
m2.forEach(function(m3) {
all[m3] = true;
});
}
}
if (!nou)
all = Object.keys(all);
if (!self2.nosort)
all = all.sort(alphasort);
if (self2.mark) {
for (var i2 = 0; i2 < all.length; i2++) {
all[i2] = self2._mark(all[i2]);
}
if (self2.nodir) {
all = all.filter(function(e2) {
var notDir = !/\/$/.test(e2);
var c = self2.cache[e2] || self2.cache[makeAbs(self2, e2)];
if (notDir && c)
notDir = c !== "DIR" && !Array.isArray(c);
return notDir;
});
}
}
if (self2.ignore.length)
all = all.filter(function(m3) {
return !isIgnored(self2, m3);
});
self2.found = all;
}
function mark(self2, p) {
var abs = makeAbs(self2, p);
var c = self2.cache[abs];
var m2 = p;
if (c) {
var isDir = c === "DIR" || Array.isArray(c);
var slash = p.slice(-1) === "/";
if (isDir && !slash)
m2 += "/";
else if (!isDir && slash)
m2 = m2.slice(0, -1);
if (m2 !== p) {
var mabs = makeAbs(self2, m2);
self2.statCache[mabs] = self2.statCache[abs];
self2.cache[mabs] = self2.cache[abs];
}
}
return m2;
}
function makeAbs(self2, f3) {
var abs = f3;
if (f3.charAt(0) === "/") {
abs = path4.join(self2.root, f3);
} else if (isAbsolute(f3) || f3 === "") {
abs = f3;
} else if (self2.changedCwd) {
abs = path4.resolve(self2.cwd, f3);
} else {
abs = path4.resolve(f3);
}
if (process.platform === "win32")
abs = abs.replace(/\\/g, "/");
return abs;
}
function isIgnored(self2, path5) {
if (!self2.ignore.length)
return false;
return self2.ignore.some(function(item) {
return item.matcher.match(path5) || !!(item.gmatcher && item.gmatcher.match(path5));
});
}
function childrenIgnored(self2, path5) {
if (!self2.ignore.length)
return false;
return self2.ignore.some(function(item) {
return !!(item.gmatcher && item.gmatcher.match(path5));
});
}
}
});
// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js
var require_sync = __commonJS({
"../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js"(exports2, module2) {
module2.exports = globSync;
globSync.GlobSync = GlobSync;
var rp = require_fs();
var minimatch2 = require_minimatch();
var Minimatch2 = minimatch2.Minimatch;
var Glob = require_glob().Glob;
var util2 = require("util");
var path4 = require("path");
var assert = require("assert");
var isAbsolute = require("path").isAbsolute;
var common = require_common();
var setopts = common.setopts;
var ownProp = common.ownProp;
var childrenIgnored = common.childrenIgnored;
var isIgnored = common.isIgnored;
function globSync(pattern, options) {
if (typeof options === "function" || arguments.length === 3)
throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
return new GlobSync(pattern, options).found;
}
function GlobSync(pattern, options) {
if (!pattern)
throw new Error("must provide pattern");
if (typeof options === "function" || arguments.length === 3)
throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
if (!(this instanceof GlobSync))
return new GlobSync(pattern, options);
setopts(this, pattern, options);
if (this.noprocess)
return this;
var n = this.minimatch.set.length;
this.matches = new Array(n);
for (var i2 = 0; i2 < n; i2++) {
this._process(this.minimatch.set[i2], i2, false);
}
this._finish();
}
GlobSync.prototype._finish = function() {
assert.ok(this instanceof GlobSync);
if (this.realpath) {
var self2 = this;
this.matches.forEach(function(matchset, index5) {
var set = self2.matches[index5] = /* @__PURE__ */ Object.create(null);
for (var p in matchset) {
try {
p = self2._makeAbs(p);
var real = rp.realpathSync(p, self2.realpathCache);
set[real] = true;
} catch (er) {
if (er.syscall === "stat")
set[self2._makeAbs(p)] = true;
else
throw er;
}
}
});
}
common.finish(this);
};
GlobSync.prototype._process = function(pattern, index5, inGlobStar) {
assert.ok(this instanceof GlobSync);
var n = 0;
while (typeof pattern[n] === "string") {
n++;
}
var prefix2;
switch (n) {
case pattern.length:
this._processSimple(pattern.join("/"), index5);
return;
case 0:
prefix2 = null;
break;
default:
prefix2 = pattern.slice(0, n).join("/");
break;
}
var remain = pattern.slice(n);
var read;
if (prefix2 === null)
read = ".";
else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
return typeof p === "string" ? p : "[*]";
}).join("/"))) {
if (!prefix2 || !isAbsolute(prefix2))
prefix2 = "/" + prefix2;
read = prefix2;
} else
read = prefix2;
var abs = this._makeAbs(read);
if (childrenIgnored(this, read))
return;
var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
if (isGlobStar)
this._processGlobStar(prefix2, read, abs, remain, index5, inGlobStar);
else
this._processReaddir(prefix2, read, abs, remain, index5, inGlobStar);
};
GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index5, inGlobStar) {
var entries = this._readdir(abs, inGlobStar);
if (!entries)
return;
var pn = remain[0];
var negate = !!this.minimatch.negate;
var rawGlob = pn._glob;
var dotOk = this.dot || rawGlob.charAt(0) === ".";
var matchedEntries = [];
for (var i2 = 0; i2 < entries.length; i2++) {
var e2 = entries[i2];
if (e2.charAt(0) !== "." || dotOk) {
var m2;
if (negate && !prefix2) {
m2 = !e2.match(pn);
} else {
m2 = e2.match(pn);
}
if (m2)
matchedEntries.push(e2);
}
}
var len = matchedEntries.length;
if (len === 0)
return;
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index5])
this.matches[index5] = /* @__PURE__ */ Object.create(null);
for (var i2 = 0; i2 < len; i2++) {
var e2 = matchedEntries[i2];
if (prefix2) {
if (prefix2.slice(-1) !== "/")
e2 = prefix2 + "/" + e2;
else
e2 = prefix2 + e2;
}
if (e2.charAt(0) === "/" && !this.nomount) {
e2 = path4.join(this.root, e2);
}
this._emitMatch(index5, e2);
}
return;
}
remain.shift();
for (var i2 = 0; i2 < len; i2++) {
var e2 = matchedEntries[i2];
var newPattern;
if (prefix2)
newPattern = [prefix2, e2];
else
newPattern = [e2];
this._process(newPattern.concat(remain), index5, inGlobStar);
}
};
GlobSync.prototype._emitMatch = function(index5, e2) {
if (isIgnored(this, e2))
return;
var abs = this._makeAbs(e2);
if (this.mark)
e2 = this._mark(e2);
if (this.absolute) {
e2 = abs;
}
if (this.matches[index5][e2])
return;
if (this.nodir) {
var c = this.cache[abs];
if (c === "DIR" || Array.isArray(c))
return;
}
this.matches[index5][e2] = true;
if (this.stat)
this._stat(e2);
};
GlobSync.prototype._readdirInGlobStar = function(abs) {
if (this.follow)
return this._readdir(abs, false);
var entries;
var lstat;
var stat2;
try {
lstat = this.fs.lstatSync(abs);
} catch (er) {
if (er.code === "ENOENT") {
return null;
}
}
var isSym = lstat && lstat.isSymbolicLink();
this.symlinks[abs] = isSym;
if (!isSym && lstat && !lstat.isDirectory())
this.cache[abs] = "FILE";
else
entries = this._readdir(abs, false);
return entries;
};
GlobSync.prototype._readdir = function(abs, inGlobStar) {
var entries;
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs);
if (ownProp(this.cache, abs)) {
var c = this.cache[abs];
if (!c || c === "FILE")
return null;
if (Array.isArray(c))
return c;
}
try {
return this._readdirEntries(abs, this.fs.readdirSync(abs));
} catch (er) {
this._readdirError(abs, er);
return null;
}
};
GlobSync.prototype._readdirEntries = function(abs, entries) {
if (!this.mark && !this.stat) {
for (var i2 = 0; i2 < entries.length; i2++) {
var e2 = entries[i2];
if (abs === "/")
e2 = abs + e2;
else
e2 = abs + "/" + e2;
this.cache[e2] = true;
}
}
this.cache[abs] = entries;
return entries;
};
GlobSync.prototype._readdirError = function(f3, er) {
switch (er.code) {
case "ENOTSUP":
case "ENOTDIR":
var abs = this._makeAbs(f3);
this.cache[abs] = "FILE";
if (abs === this.cwdAbs) {
var error2 = new Error(er.code + " invalid cwd " + this.cwd);
error2.path = this.cwd;
error2.code = er.code;
throw error2;
}
break;
case "ENOENT":
case "ELOOP":
case "ENAMETOOLONG":
case "UNKNOWN":
this.cache[this._makeAbs(f3)] = false;
break;
default:
this.cache[this._makeAbs(f3)] = false;
if (this.strict)
throw er;
if (!this.silent)
console.error("glob error", er);
break;
}
};
GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index5, inGlobStar) {
var entries = this._readdir(abs, inGlobStar);
if (!entries)
return;
var remainWithoutGlobStar = remain.slice(1);
var gspref = prefix2 ? [prefix2] : [];
var noGlobStar = gspref.concat(remainWithoutGlobStar);
this._process(noGlobStar, index5, false);
var len = entries.length;
var isSym = this.symlinks[abs];
if (isSym && inGlobStar)
return;
for (var i2 = 0; i2 < len; i2++) {
var e2 = entries[i2];
if (e2.charAt(0) === "." && !this.dot)
continue;
var instead = gspref.concat(entries[i2], remainWithoutGlobStar);
this._process(instead, index5, true);
var below = gspref.concat(entries[i2], remain);
this._process(below, index5, true);
}
};
GlobSync.prototype._processSimple = function(prefix2, index5) {
var exists = this._stat(prefix2);
if (!this.matches[index5])
this.matches[index5] = /* @__PURE__ */ Object.create(null);
if (!exists)
return;
if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix2);
if (prefix2.charAt(0) === "/") {
prefix2 = path4.join(this.root, prefix2);
} else {
prefix2 = path4.resolve(this.root, prefix2);
if (trail)
prefix2 += "/";
}
}
if (process.platform === "win32")
prefix2 = prefix2.replace(/\\/g, "/");
this._emitMatch(index5, prefix2);
};
GlobSync.prototype._stat = function(f3) {
var abs = this._makeAbs(f3);
var needDir = f3.slice(-1) === "/";
if (f3.length > this.maxLength)
return false;
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs];
if (Array.isArray(c))
c = "DIR";
if (!needDir || c === "DIR")
return c;
if (needDir && c === "FILE")
return false;
}
var exists;
var stat2 = this.statCache[abs];
if (!stat2) {
var lstat;
try {
lstat = this.fs.lstatSync(abs);
} catch (er) {
if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
this.statCache[abs] = false;
return false;
}
}
if (lstat && lstat.isSymbolicLink()) {
try {
stat2 = this.fs.statSync(abs);
} catch (er) {
stat2 = lstat;
}
} else {
stat2 = lstat;
}
}
this.statCache[abs] = stat2;
var c = true;
if (stat2)
c = stat2.isDirectory() ? "DIR" : "FILE";
this.cache[abs] = this.cache[abs] || c;
if (needDir && c === "FILE")
return false;
return c;
};
GlobSync.prototype._mark = function(p) {
return common.mark(this, p);
};
GlobSync.prototype._makeAbs = function(f3) {
return common.makeAbs(this, f3);
};
}
});
// ../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
"../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports2, module2) {
module2.exports = wrappy;
function wrappy(fn, cb) {
if (fn && cb)
return wrappy(fn)(cb);
if (typeof fn !== "function")
throw new TypeError("need wrapper function");
Object.keys(fn).forEach(function(k) {
wrapper[k] = fn[k];
});
return wrapper;
function wrapper() {
var args = new Array(arguments.length);
for (var i2 = 0; i2 < args.length; i2++) {
args[i2] = arguments[i2];
}
var ret = fn.apply(this, args);
var cb2 = args[args.length - 1];
if (typeof ret === "function" && ret !== cb2) {
Object.keys(cb2).forEach(function(k) {
ret[k] = cb2[k];
});
}
return ret;
}
}
}
});
// ../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
var require_once = __commonJS({
"../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports2, module2) {
var wrappy = require_wrappy();
module2.exports = wrappy(once);
module2.exports.strict = wrappy(onceStrict);
once.proto = once(function() {
Object.defineProperty(Function.prototype, "once", {
value: function() {
return once(this);
},
configurable: true
});
Object.defineProperty(Function.prototype, "onceStrict", {
value: function() {
return onceStrict(this);
},
configurable: true
});
});
function once(fn) {
var f3 = function() {
if (f3.called)
return f3.value;
f3.called = true;
return f3.value = fn.apply(this, arguments);
};
f3.called = false;
return f3;
}
function onceStrict(fn) {
var f3 = function() {
if (f3.called)
throw new Error(f3.onceError);
f3.called = true;
return f3.value = fn.apply(this, arguments);
};
var name = fn.name || "Function wrapped with `once`";
f3.onceError = name + " shouldn't be called more than once";
f3.called = false;
return f3;
}
}
});
// ../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js
var require_inflight = __commonJS({
"../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js"(exports2, module2) {
var wrappy = require_wrappy();
var reqs = /* @__PURE__ */ Object.create(null);
var once = require_once();
module2.exports = wrappy(inflight);
function inflight(key, cb) {
if (reqs[key]) {
reqs[key].push(cb);
return null;
} else {
reqs[key] = [cb];
return makeres(key);
}
}
function makeres(key) {
return once(function RES() {
var cbs = reqs[key];
var len = cbs.length;
var args = slice(arguments);
try {
for (var i2 = 0; i2 < len; i2++) {
cbs[i2].apply(null, args);
}
} finally {
if (cbs.length > len) {
cbs.splice(0, len);
process.nextTick(function() {
RES.apply(null, args);
});
} else {
delete reqs[key];
}
}
});
}
function slice(args) {
var length = args.length;
var array2 = [];
for (var i2 = 0; i2 < length; i2++)
array2[i2] = args[i2];
return array2;
}
}
});
// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js
var require_glob = __commonJS({
"../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js"(exports2, module2) {
module2.exports = glob2;
var rp = require_fs();
var minimatch2 = require_minimatch();
var Minimatch2 = minimatch2.Minimatch;
var inherits = require_inherits();
var EE = require("events").EventEmitter;
var path4 = require("path");
var assert = require("assert");
var isAbsolute = require("path").isAbsolute;
var globSync = require_sync();
var common = require_common();
var setopts = common.setopts;
var ownProp = common.ownProp;
var inflight = require_inflight();
var util2 = require("util");
var childrenIgnored = common.childrenIgnored;
var isIgnored = common.isIgnored;
var once = require_once();
function glob2(pattern, options, cb) {
if (typeof options === "function")
cb = options, options = {};
if (!options)
options = {};
if (options.sync) {
if (cb)
throw new TypeError("callback provided to sync glob");
return globSync(pattern, options);
}
return new Glob(pattern, options, cb);
}
glob2.sync = globSync;
var GlobSync = glob2.GlobSync = globSync.GlobSync;
glob2.glob = glob2;
function extend(origin, add) {
if (add === null || typeof add !== "object") {
return origin;
}
var keys = Object.keys(add);
var i2 = keys.length;
while (i2--) {
origin[keys[i2]] = add[keys[i2]];
}
return origin;
}
glob2.hasMagic = function(pattern, options_) {
var options = extend({}, options_);
options.noprocess = true;
var g = new Glob(pattern, options);
var set = g.minimatch.set;
if (!pattern)
return false;
if (set.length > 1)
return true;
for (var j = 0; j < set[0].length; j++) {
if (typeof set[0][j] !== "string")
return true;
}
return false;
};
glob2.Glob = Glob;
inherits(Glob, EE);
function Glob(pattern, options, cb) {
if (typeof options === "function") {
cb = options;
options = null;
}
if (options && options.sync) {
if (cb)
throw new TypeError("callback provided to sync glob");
return new GlobSync(pattern, options);
}
if (!(this instanceof Glob))
return new Glob(pattern, options, cb);
setopts(this, pattern, options);
this._didRealPath = false;
var n = this.minimatch.set.length;
this.matches = new Array(n);
if (typeof cb === "function") {
cb = once(cb);
this.on("error", cb);
this.on("end", function(matches) {
cb(null, matches);
});
}
var self2 = this;
this._processing = 0;
this._emitQueue = [];
this._processQueue = [];
this.paused = false;
if (this.noprocess)
return this;
if (n === 0)
return done();
var sync2 = true;
for (var i2 = 0; i2 < n; i2++) {
this._process(this.minimatch.set[i2], i2, false, done);
}
sync2 = false;
function done() {
--self2._processing;
if (self2._processing <= 0) {
if (sync2) {
process.nextTick(function() {
self2._finish();
});
} else {
self2._finish();
}
}
}
}
Glob.prototype._finish = function() {
assert(this instanceof Glob);
if (this.aborted)
return;
if (this.realpath && !this._didRealpath)
return this._realpath();
common.finish(this);
this.emit("end", this.found);
};
Glob.prototype._realpath = function() {
if (this._didRealpath)
return;
this._didRealpath = true;
var n = this.matches.length;
if (n === 0)
return this._finish();
var self2 = this;
for (var i2 = 0; i2 < this.matches.length; i2++)
this._realpathSet(i2, next);
function next() {
if (--n === 0)
self2._finish();
}
};
Glob.prototype._realpathSet = function(index5, cb) {
var matchset = this.matches[index5];
if (!matchset)
return cb();
var found = Object.keys(matchset);
var self2 = this;
var n = found.length;
if (n === 0)
return cb();
var set = this.matches[index5] = /* @__PURE__ */ Object.create(null);
found.forEach(function(p, i2) {
p = self2._makeAbs(p);
rp.realpath(p, self2.realpathCache, function(er, real) {
if (!er)
set[real] = true;
else if (er.syscall === "stat")
set[p] = true;
else
self2.emit("error", er);
if (--n === 0) {
self2.matches[index5] = set;
cb();
}
});
});
};
Glob.prototype._mark = function(p) {
return common.mark(this, p);
};
Glob.prototype._makeAbs = function(f3) {
return common.makeAbs(this, f3);
};
Glob.prototype.abort = function() {
this.aborted = true;
this.emit("abort");
};
Glob.prototype.pause = function() {
if (!this.paused) {
this.paused = true;
this.emit("pause");
}
};
Glob.prototype.resume = function() {
if (this.paused) {
this.emit("resume");
this.paused = false;
if (this._emitQueue.length) {
var eq = this._emitQueue.slice(0);
this._emitQueue.length = 0;
for (var i2 = 0; i2 < eq.length; i2++) {
var e2 = eq[i2];
this._emitMatch(e2[0], e2[1]);
}
}
if (this._processQueue.length) {
var pq = this._processQueue.slice(0);
this._processQueue.length = 0;
for (var i2 = 0; i2 < pq.length; i2++) {
var p = pq[i2];
this._processing--;
this._process(p[0], p[1], p[2], p[3]);
}
}
}
};
Glob.prototype._process = function(pattern, index5, inGlobStar, cb) {
assert(this instanceof Glob);
assert(typeof cb === "function");
if (this.aborted)
return;
this._processing++;
if (this.paused) {
this._processQueue.push([pattern, index5, inGlobStar, cb]);
return;
}
var n = 0;
while (typeof pattern[n] === "string") {
n++;
}
var prefix2;
switch (n) {
case pattern.length:
this._processSimple(pattern.join("/"), index5, cb);
return;
case 0:
prefix2 = null;
break;
default:
prefix2 = pattern.slice(0, n).join("/");
break;
}
var remain = pattern.slice(n);
var read;
if (prefix2 === null)
read = ".";
else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
return typeof p === "string" ? p : "[*]";
}).join("/"))) {
if (!prefix2 || !isAbsolute(prefix2))
prefix2 = "/" + prefix2;
read = prefix2;
} else
read = prefix2;
var abs = this._makeAbs(read);
if (childrenIgnored(this, read))
return cb();
var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
if (isGlobStar)
this._processGlobStar(prefix2, read, abs, remain, index5, inGlobStar, cb);
else
this._processReaddir(prefix2, read, abs, remain, index5, inGlobStar, cb);
};
Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index5, inGlobStar, cb) {
var self2 = this;
this._readdir(abs, inGlobStar, function(er, entries) {
return self2._processReaddir2(prefix2, read, abs, remain, index5, inGlobStar, entries, cb);
});
};
Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index5, inGlobStar, entries, cb) {
if (!entries)
return cb();
var pn = remain[0];
var negate = !!this.minimatch.negate;
var rawGlob = pn._glob;
var dotOk = this.dot || rawGlob.charAt(0) === ".";
var matchedEntries = [];
for (var i2 = 0; i2 < entries.length; i2++) {
var e2 = entries[i2];
if (e2.charAt(0) !== "." || dotOk) {
var m2;
if (negate && !prefix2) {
m2 = !e2.match(pn);
} else {
m2 = e2.match(pn);
}
if (m2)
matchedEntries.push(e2);
}
}
var len = matchedEntries.length;
if (len === 0)
return cb();
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index5])
this.matches[index5] = /* @__PURE__ */ Object.create(null);
for (var i2 = 0; i2 < len; i2++) {
var e2 = matchedEntries[i2];
if (prefix2) {
if (prefix2 !== "/")
e2 = prefix2 + "/" + e2;
else
e2 = prefix2 + e2;
}
if (e2.charAt(0) === "/" && !this.nomount) {
e2 = path4.join(this.root, e2);
}
this._emitMatch(index5, e2);
}
return cb();
}
remain.shift();
for (var i2 = 0; i2 < len; i2++) {
var e2 = matchedEntries[i2];
var newPattern;
if (prefix2) {
if (prefix2 !== "/")
e2 = prefix2 + "/" + e2;
else
e2 = prefix2 + e2;
}
this._process([e2].concat(remain), index5, inGlobStar, cb);
}
cb();
};
Glob.prototype._emitMatch = function(index5, e2) {
if (this.aborted)
return;
if (isIgnored(this, e2))
return;
if (this.paused) {
this._emitQueue.push([index5, e2]);
return;
}
var abs = isAbsolute(e2) ? e2 : this._makeAbs(e2);
if (this.mark)
e2 = this._mark(e2);
if (this.absolute)
e2 = abs;
if (this.matches[index5][e2])
return;
if (this.nodir) {
var c = this.cache[abs];
if (c === "DIR" || Array.isArray(c))
return;
}
this.matches[index5][e2] = true;
var st = this.statCache[abs];
if (st)
this.emit("stat", e2, st);
this.emit("match", e2);
};
Glob.prototype._readdirInGlobStar = function(abs, cb) {
if (this.aborted)
return;
if (this.follow)
return this._readdir(abs, false, cb);
var lstatkey = "lstat\0" + abs;
var self2 = this;
var lstatcb = inflight(lstatkey, lstatcb_);
if (lstatcb)
self2.fs.lstat(abs, lstatcb);
function lstatcb_(er, lstat) {
if (er && er.code === "ENOENT")
return cb();
var isSym = lstat && lstat.isSymbolicLink();
self2.symlinks[abs] = isSym;
if (!isSym && lstat && !lstat.isDirectory()) {
self2.cache[abs] = "FILE";
cb();
} else
self2._readdir(abs, false, cb);
}
};
Glob.prototype._readdir = function(abs, inGlobStar, cb) {
if (this.aborted)
return;
cb = inflight("readdir\0" + abs + "\0" + inGlobStar, cb);
if (!cb)
return;
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs, cb);
if (ownProp(this.cache, abs)) {
var c = this.cache[abs];
if (!c || c === "FILE")
return cb();
if (Array.isArray(c))
return cb(null, c);
}
var self2 = this;
self2.fs.readdir(abs, readdirCb(this, abs, cb));
};
function readdirCb(self2, abs, cb) {
return function(er, entries) {
if (er)
self2._readdirError(abs, er, cb);
else
self2._readdirEntries(abs, entries, cb);
};
}
Glob.prototype._readdirEntries = function(abs, entries, cb) {
if (this.aborted)
return;
if (!this.mark && !this.stat) {
for (var i2 = 0; i2 < entries.length; i2++) {
var e2 = entries[i2];
if (abs === "/")
e2 = abs + e2;
else
e2 = abs + "/" + e2;
this.cache[e2] = true;
}
}
this.cache[abs] = entries;
return cb(null, entries);
};
Glob.prototype._readdirError = function(f3, er, cb) {
if (this.aborted)
return;
switch (er.code) {
case "ENOTSUP":
case "ENOTDIR":
var abs = this._makeAbs(f3);
this.cache[abs] = "FILE";
if (abs === this.cwdAbs) {
var error2 = new Error(er.code + " invalid cwd " + this.cwd);
error2.path = this.cwd;
error2.code = er.code;
this.emit("error", error2);
this.abort();
}
break;
case "ENOENT":
case "ELOOP":
case "ENAMETOOLONG":
case "UNKNOWN":
this.cache[this._makeAbs(f3)] = false;
break;
default:
this.cache[this._makeAbs(f3)] = false;
if (this.strict) {
this.emit("error", er);
this.abort();
}
if (!this.silent)
console.error("glob error", er);
break;
}
return cb();
};
Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index5, inGlobStar, cb) {
var self2 = this;
this._readdir(abs, inGlobStar, function(er, entries) {
self2._processGlobStar2(prefix2, read, abs, remain, index5, inGlobStar, entries, cb);
});
};
Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index5, inGlobStar, entries, cb) {
if (!entries)
return cb();
var remainWithoutGlobStar = remain.slice(1);
var gspref = prefix2 ? [prefix2] : [];
var noGlobStar = gspref.concat(remainWithoutGlobStar);
this._process(noGlobStar, index5, false, cb);
var isSym = this.symlinks[abs];
var len = entries.length;
if (isSym && inGlobStar)
return cb();
for (var i2 = 0; i2 < len; i2++) {
var e2 = entries[i2];
if (e2.charAt(0) === "." && !this.dot)
continue;
var instead = gspref.concat(entries[i2], remainWithoutGlobStar);
this._process(instead, index5, true, cb);
var below = gspref.concat(entries[i2], remain);
this._process(below, index5, true, cb);
}
cb();
};
Glob.prototype._processSimple = function(prefix2, index5, cb) {
var self2 = this;
this._stat(prefix2, function(er, exists) {
self2._processSimple2(prefix2, index5, er, exists, cb);
});
};
Glob.prototype._processSimple2 = function(prefix2, index5, er, exists, cb) {
if (!this.matches[index5])
this.matches[index5] = /* @__PURE__ */ Object.create(null);
if (!exists)
return cb();
if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix2);
if (prefix2.charAt(0) === "/") {
prefix2 = path4.join(this.root, prefix2);
} else {
prefix2 = path4.resolve(this.root, prefix2);
if (trail)
prefix2 += "/";
}
}
if (process.platform === "win32")
prefix2 = prefix2.replace(/\\/g, "/");
this._emitMatch(index5, prefix2);
cb();
};
Glob.prototype._stat = function(f3, cb) {
var abs = this._makeAbs(f3);
var needDir = f3.slice(-1) === "/";
if (f3.length > this.maxLength)
return cb();
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs];
if (Array.isArray(c))
c = "DIR";
if (!needDir || c === "DIR")
return cb(null, c);
if (needDir && c === "FILE")
return cb();
}
var exists;
var stat2 = this.statCache[abs];
if (stat2 !== void 0) {
if (stat2 === false)
return cb(null, stat2);
else {
var type = stat2.isDirectory() ? "DIR" : "FILE";
if (needDir && type === "FILE")
return cb();
else
return cb(null, type, stat2);
}
}
var self2 = this;
var statcb = inflight("stat\0" + abs, lstatcb_);
if (statcb)
self2.fs.lstat(abs, statcb);
function lstatcb_(er, lstat) {
if (lstat && lstat.isSymbolicLink()) {
return self2.fs.stat(abs, function(er2, stat3) {
if (er2)
self2._stat2(f3, abs, null, lstat, cb);
else
self2._stat2(f3, abs, er2, stat3, cb);
});
} else {
self2._stat2(f3, abs, er, lstat, cb);
}
}
};
Glob.prototype._stat2 = function(f3, abs, er, stat2, cb) {
if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
this.statCache[abs] = false;
return cb();
}
var needDir = f3.slice(-1) === "/";
this.statCache[abs] = stat2;
if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory())
return cb(null, false, stat2);
var c = true;
if (stat2)
c = stat2.isDirectory() ? "DIR" : "FILE";
this.cache[abs] = this.cache[abs] || c;
if (needDir && c === "FILE")
return cb();
return cb(null, c, stat2);
};
}
});
// src/extensions/getTablesFilterByExtensions.ts
var getTablesFilterByExtensions;
var init_getTablesFilterByExtensions = __esm({
"src/extensions/getTablesFilterByExtensions.ts"() {
"use strict";
getTablesFilterByExtensions = ({
extensionsFilters,
dialect: dialect6
}) => {
if (extensionsFilters) {
if (extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
return ["!geography_columns", "!geometry_columns", "!spatial_ref_sys"];
}
}
return [];
};
}
});
// src/cli/validations/outputs.ts
var withStyle, outputs;
var init_outputs = __esm({
"src/cli/validations/outputs.ts"() {
"use strict";
init_source();
init_common();
withStyle = {
error: (str) => `${source_default.red(`${source_default.white.bgRed(" Invalid input ")} ${str}`)}`,
warning: (str) => `${source_default.white.bgGray(" Warning ")} ${str}`,
errorWarning: (str) => `${source_default.red(`${source_default.white.bgRed(" Warning ")} ${str}`)}`,
fullWarning: (str) => `${source_default.black.bgYellow(" Warning ")} ${source_default.bold(str)}`,
suggestion: (str) => `${source_default.white.bgGray(" Suggestion ")} ${str}`,
info: (str) => `${source_default.grey(str)}`
};
outputs = {
studio: {
drivers: (param) => withStyle.error(
`"${param}" is not a valid driver. Available drivers: "pg", "mysql2", "better-sqlite", "libsql", "turso". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
),
noCredentials: () => withStyle.error(
`Please specify a 'dbCredentials' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
),
noDriver: () => withStyle.error(
`Please specify a 'driver' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
),
noDialect: () => withStyle.error(
`Please specify 'dialect' param in config, either of 'postgresql', 'mysql', 'sqlite', turso or singlestore`
)
},
common: {
ambiguousParams: (command) => withStyle.error(
`You can't use both --config and other cli options for ${command} command`
),
schema: (command) => withStyle.error(`"--schema" is a required field for ${command} command`)
},
postgres: {
connection: {
required: () => withStyle.error(
`Either "url" or "host", "database" are required for database connection`
),
awsDataApi: () => withStyle.error(
"You need to provide 'database', 'secretArn' and 'resourceArn' for Drizzle Kit to connect to AWS Data API"
)
}
},
mysql: {
connection: {
driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
required: () => withStyle.error(
`Either "url" or "host", "database" are required for database connection`
)
}
},
sqlite: {
connection: {
driver: () => {
const listOfDrivers = sqliteDriversLiterals.map((it) => `'${it.value}'`).join(", ");
return withStyle.error(
`Either ${listOfDrivers} are available options for 'driver' param`
);
},
url: (driver2) => withStyle.error(
`"url" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
),
authToken: (driver2) => withStyle.error(
`"authToken" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
)
},
introspect: {},
push: {}
},
singlestore: {
connection: {
driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
required: () => withStyle.error(
`Either "url" or "host", "database" are required for database connection`
)
}
}
};
}
});
// src/cli/validations/common.ts
var assertCollisions, sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema, drivers, wrapParam;
var init_common = __esm({
"src/cli/validations/common.ts"() {
"use strict";
init_source();
init_lib();
init_schemaValidator();
init_outputs();
assertCollisions = (command, options, whitelist, remainingKeys) => {
const { config, ...rest } = options;
let atLeastOneParam = false;
for (const key of Object.keys(rest)) {
if (whitelist.includes(key))
continue;
atLeastOneParam = atLeastOneParam || rest[key] !== void 0;
}
if (!config && atLeastOneParam) {
return "cli";
}
if (!atLeastOneParam) {
return "config";
}
console.log(outputs.common.ambiguousParams(command));
process.exit(1);
};
sqliteDriversLiterals = [
literalType("d1-http"),
literalType("expo"),
literalType("durable-sqlite")
];
postgresqlDriversLiterals = [
literalType("aws-data-api"),
literalType("pglite")
];
prefixes = [
"index",
"timestamp",
"supabase",
"unix",
"none"
];
prefix = enumType(prefixes);
{
const _2 = "";
}
casingTypes = ["snake_case", "camelCase"];
casingType = enumType(casingTypes);
sqliteDriver = unionType(sqliteDriversLiterals);
postgresDriver = unionType(postgresqlDriversLiterals);
driver = unionType([sqliteDriver, postgresDriver]);
configMigrations = objectType({
table: stringType().optional(),
schema: stringType().optional(),
prefix: prefix.optional().default("index")
}).optional();
configCommonSchema = objectType({
dialect: dialect4,
schema: unionType([stringType(), stringType().array()]).optional(),
out: stringType().optional(),
breakpoints: booleanType().optional().default(true),
verbose: booleanType().optional().default(false),
driver: driver.optional(),
tablesFilter: unionType([stringType(), stringType().array()]).optional(),
schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
migrations: configMigrations,
dbCredentials: anyType().optional(),
casing: casingType.optional(),
sql: booleanType().default(true)
}).passthrough();
casing = unionType([literalType("camel"), literalType("preserve")]).default(
"camel"
);
introspectParams = objectType({
schema: unionType([stringType(), stringType().array()]).optional(),
out: stringType().optional().default("./drizzle"),
breakpoints: booleanType().default(true),
tablesFilter: unionType([stringType(), stringType().array()]).optional(),
schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
introspect: objectType({
casing
}).default({ casing: "camel" })
});
configIntrospectCliSchema = objectType({
schema: unionType([stringType(), stringType().array()]).optional(),
out: stringType().optional().default("./drizzle"),
breakpoints: booleanType().default(true),
tablesFilter: unionType([stringType(), stringType().array()]).optional(),
schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default(
"camel"
)
});
configGenerateSchema = objectType({
schema: unionType([stringType(), stringType().array()]),
out: stringType().optional().default("./drizzle"),
breakpoints: booleanType().default(true)
});
configPushSchema = objectType({
dialect: dialect4,
schema: unionType([stringType(), stringType().array()]),
tablesFilter: unionType([stringType(), stringType().array()]).optional(),
schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
verbose: booleanType().default(false),
strict: booleanType().default(false),
out: stringType().optional()
});
drivers = ["d1-http", "expo", "aws-data-api", "pglite", "durable-sqlite"];
wrapParam = (name, param, optional = false, type) => {
const check2 = `[${source_default.green("\u2713")}]`;
const cross = `[${source_default.red("x")}]`;
if (typeof param === "string") {
if (param.length === 0) {
return ` ${cross} ${name}: ''`;
}
if (type === "secret") {
return ` ${check2} ${name}: '*****'`;
} else if (type === "url") {
return ` ${check2} ${name}: '${param.replace(/(?<=:\/\/[^:\n]*:)([^@]*)/, "****")}'`;
}
return ` ${check2} ${name}: '${param}'`;
}
if (optional) {
return source_default.gray(` ${name}?: `);
}
return ` ${cross} ${name}: ${source_default.gray("undefined")}`;
};
}
});
// src/cli/validations/cli.ts
var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck;
var init_cli = __esm({
"src/cli/validations/cli.ts"() {
"use strict";
init_lib();
init_schemaValidator();
init_common();
cliConfigGenerate = objectType({
dialect: dialect4.optional(),
schema: unionType([stringType(), stringType().array()]).optional(),
out: stringType().optional().default("./drizzle"),
config: stringType().optional(),
name: stringType().optional(),
prefix: prefix.optional(),
breakpoints: booleanType().optional().default(true),
custom: booleanType().optional().default(false)
}).strict();
pushParams = objectType({
dialect: dialect4,
casing: casingType.optional(),
schema: unionType([stringType(), stringType().array()]),
tablesFilter: unionType([stringType(), stringType().array()]).optional(),
schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
extensionsFilters: literalType("postgis").array().optional(),
verbose: booleanType().optional(),
strict: booleanType().optional(),
entities: objectType({
roles: booleanType().or(objectType({
provider: stringType().optional(),
include: stringType().array().optional(),
exclude: stringType().array().optional()
})).optional().default(false)
}).optional()
}).passthrough();
pullParams = objectType({
config: stringType().optional(),
dialect: dialect4,
out: stringType().optional().default("drizzle"),
tablesFilter: unionType([stringType(), stringType().array()]).optional(),
schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
extensionsFilters: literalType("postgis").array().optional(),
casing,
breakpoints: booleanType().optional().default(true),
migrations: objectType({
prefix: prefix.optional().default("index")
}).optional(),
entities: objectType({
roles: booleanType().or(objectType({
provider: stringType().optional(),
include: stringType().array().optional(),
exclude: stringType().array().optional()
})).optional().default(false)
}).optional()
}).passthrough();
configCheck = objectType({
dialect: dialect4.optional(),
out: stringType().optional()
});
cliConfigCheck = intersectionType(
objectType({
config: stringType().optional()
}),
configCheck
);
}
});
// src/cli/validations/libsql.ts
var libSQLCredentials, printConfigConnectionIssues;
var init_libsql = __esm({
"src/cli/validations/libsql.ts"() {
"use strict";
init_lib();
init_views();
init_common();
libSQLCredentials = objectType({
url: stringType().min(1),
authToken: stringType().min(1).optional()
});
printConfigConnectionIssues = (options, command) => {
let text = `Please provide required params for 'turso' dialect:
`;
console.log(error(text));
console.log(wrapParam("url", options.url));
console.log(wrapParam("authToken", options.authToken, true, "secret"));
process.exit(1);
};
}
});
// src/cli/validations/mysql.ts
var mysqlCredentials, printConfigConnectionIssues2;
var init_mysql = __esm({
"src/cli/validations/mysql.ts"() {
"use strict";
init_lib();
init_views();
init_common();
init_outputs();
mysqlCredentials = unionType([
objectType({
host: stringType().min(1),
port: coerce.number().min(1).optional(),
user: stringType().min(1).optional(),
password: stringType().min(1).optional(),
database: stringType().min(1),
ssl: unionType([
stringType(),
objectType({
pfx: stringType().optional(),
key: stringType().optional(),
passphrase: stringType().optional(),
cert: stringType().optional(),
ca: unionType([stringType(), stringType().array()]).optional(),
crl: unionType([stringType(), stringType().array()]).optional(),
ciphers: stringType().optional(),
rejectUnauthorized: booleanType().optional()
})
]).optional()
}),
objectType({
url: stringType().min(1)
})
]);
printConfigConnectionIssues2 = (options) => {
if ("url" in options) {
let text2 = `Please provide required params for MySQL driver:
`;
console.log(error(text2));
console.log(wrapParam("url", options.url, false, "url"));
process.exit(1);
}
let text = `Please provide required params for MySQL driver:
`;
console.log(error(text));
console.log(wrapParam("host", options.host));
console.log(wrapParam("port", options.port, true));
console.log(wrapParam("user", options.user, true));
console.log(wrapParam("password", options.password, true, "secret"));
console.log(wrapParam("database", options.database));
console.log(wrapParam("ssl", options.ssl, true));
process.exit(1);
};
}
});
// src/cli/validations/postgres.ts
var postgresCredentials, printConfigConnectionIssues3;
var init_postgres = __esm({
"src/cli/validations/postgres.ts"() {
"use strict";
init_lib();
init_views();
init_common();
postgresCredentials = unionType([
objectType({
driver: undefinedType(),
host: stringType().min(1),
port: coerce.number().min(1).optional(),
user: stringType().min(1).optional(),
password: stringType().min(1).optional(),
database: stringType().min(1),
ssl: unionType([
literalType("require"),
literalType("allow"),
literalType("prefer"),
literalType("verify-full"),
booleanType(),
objectType({}).passthrough()
]).optional()
}).transform((o) => {
delete o.driver;
return o;
}),
objectType({
driver: undefinedType(),
url: stringType().min(1)
}).transform((o) => {
delete o.driver;
return o;
}),
objectType({
driver: literalType("aws-data-api"),
database: stringType().min(1),
secretArn: stringType().min(1),
resourceArn: stringType().min(1)
}),
objectType({
driver: literalType("pglite"),
url: stringType().min(1)
})
]);
printConfigConnectionIssues3 = (options) => {
if (options.driver === "aws-data-api") {
let text = `Please provide required params for AWS Data API driver:
`;
console.log(error(text));
console.log(wrapParam("database", options.database));
console.log(wrapParam("secretArn", options.secretArn, false, "secret"));
console.log(wrapParam("resourceArn", options.resourceArn, false, "secret"));
process.exit(1);
}
if ("url" in options) {
let text = `Please provide required params for Postgres driver:
`;
console.log(error(text));
console.log(wrapParam("url", options.url, false, "url"));
process.exit(1);
}
if ("host" in options || "database" in options) {
let text = `Please provide required params for Postgres driver:
`;
console.log(error(text));
console.log(wrapParam("host", options.host));
console.log(wrapParam("port", options.port, true));
console.log(wrapParam("user", options.user, true));
console.log(wrapParam("password", options.password, true, "secret"));
console.log(wrapParam("database", options.database));
console.log(wrapParam("ssl", options.ssl, true));
process.exit(1);
}
console.log(
error(
`Either connection "url" or "host", "database" are required for PostgreSQL database connection`
)
);
process.exit(1);
};
}
});
// src/cli/validations/singlestore.ts
var singlestoreCredentials, printConfigConnectionIssues4;
var init_singlestore = __esm({
"src/cli/validations/singlestore.ts"() {
"use strict";
init_lib();
init_views();
init_common();
init_outputs();
singlestoreCredentials = unionType([
objectType({
host: stringType().min(1),
port: coerce.number().min(1).optional(),
user: stringType().min(1).optional(),
password: stringType().min(1).optional(),
database: stringType().min(1),
ssl: unionType([
stringType(),
objectType({
pfx: stringType().optional(),
key: stringType().optional(),
passphrase: stringType().optional(),
cert: stringType().optional(),
ca: unionType([stringType(), stringType().array()]).optional(),
crl: unionType([stringType(), stringType().array()]).optional(),
ciphers: stringType().optional(),
rejectUnauthorized: booleanType().optional()
})
]).optional()
}),
objectType({
url: stringType().min(1)
})
]);
printConfigConnectionIssues4 = (options) => {
if ("url" in options) {
let text2 = `Please provide required params for SingleStore driver:
`;
console.log(error(text2));
console.log(wrapParam("url", options.url, false, "url"));
process.exit(1);
}
let text = `Please provide required params for SingleStore driver:
`;
console.log(error(text));
console.log(wrapParam("host", options.host));
console.log(wrapParam("port", options.port, true));
console.log(wrapParam("user", options.user, true));
console.log(wrapParam("password", options.password, true, "secret"));
console.log(wrapParam("database", options.database));
console.log(wrapParam("ssl", options.ssl, true));
process.exit(1);
};
}
});
// src/cli/validations/sqlite.ts
var sqliteCredentials, printConfigConnectionIssues5;
var init_sqlite = __esm({
"src/cli/validations/sqlite.ts"() {
"use strict";
init_global();
init_lib();
init_views();
init_common();
sqliteCredentials = unionType([
objectType({
driver: literalType("turso"),
url: stringType().min(1),
authToken: stringType().min(1).optional()
}),
objectType({
driver: literalType("d1-http"),
accountId: stringType().min(1),
databaseId: stringType().min(1),
token: stringType().min(1)
}),
objectType({
driver: undefinedType(),
url: stringType().min(1)
}).transform((o) => {
delete o.driver;
return o;
})
]);
printConfigConnectionIssues5 = (options, command) => {
const parsedDriver = sqliteDriver.safeParse(options.driver);
const driver2 = parsedDriver.success ? parsedDriver.data : "";
if (driver2 === "expo") {
if (command === "migrate") {
console.log(
error(
`You can't use 'migrate' command with Expo SQLite, please follow migration instructions in our docs - https://orm.drizzle.team/docs/get-started-sqlite#expo-sqlite`
)
);
} else if (command === "studio") {
console.log(
error(
`You can't use 'studio' command with Expo SQLite, please use Expo Plugin https://www.npmjs.com/package/expo-drizzle-studio-plugin`
)
);
} else if (command === "pull") {
console.log(error("You can't use 'pull' command with Expo SQLite"));
} else if (command === "push") {
console.log(error("You can't use 'push' command with Expo SQLite"));
} else {
console.log(error("Unexpected error with expo driver \u{1F914}"));
}
process.exit(1);
} else if (driver2 === "d1-http") {
let text2 = `Please provide required params for D1 HTTP driver:
`;
console.log(error(text2));
console.log(wrapParam("accountId", options.accountId));
console.log(wrapParam("databaseId", options.databaseId));
console.log(wrapParam("token", options.token, false, "secret"));
process.exit(1);
} else if (driver2 === "durable-sqlite") {
if (command === "migrate") {
console.log(
error(
`You can't use 'migrate' command with SQLite Durable Objects`
)
);
} else if (command === "studio") {
console.log(
error(
`You can't use 'migrate' command with SQLite Durable Objects`
)
);
} else if (command === "pull") {
console.log(error("You can't use 'pull' command with SQLite Durable Objects"));
} else if (command === "push") {
console.log(error("You can't use 'push' command with SQLite Durable Objects"));
} else {
console.log(error("Unexpected error with SQLite Durable Object driver \u{1F914}"));
}
process.exit(1);
} else {
softAssertUnreachable(driver2);
}
let text = `Please provide required params:
`;
console.log(error(text));
console.log(wrapParam("url", options.url));
process.exit(1);
};
}
});
// src/cli/validations/studio.ts
var credentials, studioCliParams, studioConfig;
var init_studio = __esm({
"src/cli/validations/studio.ts"() {
"use strict";
init_lib();
init_schemaValidator();
init_mysql();
init_postgres();
init_sqlite();
credentials = intersectionType(
postgresCredentials,
mysqlCredentials,
sqliteCredentials
);
studioCliParams = objectType({
port: coerce.number().optional().default(4983),
host: stringType().optional().default("127.0.0.1"),
config: stringType().optional()
});
studioConfig = objectType({
dialect: dialect4,
schema: unionType([stringType(), stringType().array()]).optional()
});
}
});
// src/cli/commands/_es5.ts
var es5_exports = {};
__export(es5_exports, {
default: () => es5_default
});
var _, es5_default;
var init_es5 = __esm({
"src/cli/commands/_es5.ts"() {
"use strict";
_ = "";
es5_default = _;
}
});
// ../node_modules/.pnpm/ms@2.1.2/node_modules/ms/index.js
var require_ms = __commonJS({
"../node_modules/.pnpm/ms@2.1.2/node_modules/ms/index.js"(exports2, module2) {
var s2 = 1e3;
var m2 = s2 * 60;
var h2 = m2 * 60;
var d = h2 * 24;
var w = d * 7;
var y = d * 365.25;
module2.exports = function(val2, options) {
options = options || {};
var type = typeof val2;
if (type === "string" && val2.length > 0) {
return parse5(val2);
} else if (type === "number" && isFinite(val2)) {
return options.long ? fmtLong(val2) : fmtShort(val2);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val2)
);
};
function parse5(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match2) {
return;
}
var n = parseFloat(match2[1]);
var type = (match2[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h2;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m2;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s2;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return void 0;
}
}
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + "d";
}
if (msAbs >= h2) {
return Math.round(ms / h2) + "h";
}
if (msAbs >= m2) {
return Math.round(ms / m2) + "m";
}
if (msAbs >= s2) {
return Math.round(ms / s2) + "s";
}
return ms + "ms";
}
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural2(ms, msAbs, d, "day");
}
if (msAbs >= h2) {
return plural2(ms, msAbs, h2, "hour");
}
if (msAbs >= m2) {
return plural2(ms, msAbs, m2, "minute");
}
if (msAbs >= s2) {
return plural2(ms, msAbs, s2, "second");
}
return ms + " ms";
}
function plural2(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
}
}
});
// ../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/common.js
var require_common2 = __commonJS({
"../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/common.js"(exports2, module2) {
function setup(env3) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce2;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require_ms();
createDebug.destroy = destroy;
Object.keys(env3).forEach((key) => {
createDebug[key] = env3[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i2 = 0; i2 < namespace.length; i2++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i2);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
if (!debug.enabled) {
return;
}
const self2 = debug;
const curr = Number(/* @__PURE__ */ new Date());
const ms = curr - (prevTime || curr);
self2.diff = ms;
self2.prev = prevTime;
self2.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index5 = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format) => {
if (match2 === "%%") {
return "%";
}
index5++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val2 = args[index5];
match2 = formatter.call(self2, val2);
args.splice(index5, 1);
index5--;
}
return match2;
});
createDebug.formatArgs.call(self2, args);
const logFn = self2.log || createDebug.log;
logFn.apply(self2, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy;
Object.defineProperty(debug, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i2;
const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
const len = split.length;
for (i2 = 0; i2 < len; i2++) {
if (!split[i2]) {
continue;
}
namespaces = split[i2].replace(/\*/g, ".*?");
if (namespaces[0] === "-") {
createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
} else {
createDebug.names.push(new RegExp("^" + namespaces + "$"));
}
}
}
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name) {
if (name[name.length - 1] === "*") {
return true;
}
let i2;
let len;
for (i2 = 0, len = createDebug.skips.length; i2 < len; i2++) {
if (createDebug.skips[i2].test(name)) {
return false;
}
}
for (i2 = 0, len = createDebug.names.length; i2 < len; i2++) {
if (createDebug.names[i2].test(name)) {
return true;
}
}
return false;
}
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
}
function coerce2(val2) {
if (val2 instanceof Error) {
return val2.stack || val2.message;
}
return val2;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
module2.exports = setup;
}
});
// ../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/browser.js
var require_browser = __commonJS({
"../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/browser.js"(exports2, module2) {
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load;
exports2.useColors = useColors;
exports2.storage = localstorage();
exports2.destroy = /* @__PURE__ */ (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports2.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index5 = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match2) => {
if (match2 === "%%") {
return;
}
index5++;
if (match2 === "%c") {
lastC = index5;
}
});
args.splice(lastC, 0, c);
}
exports2.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports2.storage.setItem("debug", namespaces);
} else {
exports2.storage.removeItem("debug");
}
} catch (error2) {
}
}
function load() {
let r2;
try {
r2 = exports2.storage.getItem("debug");
} catch (error2) {
}
if (!r2 && typeof process !== "undefined" && "env" in process) {
r2 = process.env.DEBUG;
}
return r2;
}
function localstorage() {
try {
return localStorage;
} catch (error2) {
}
}
module2.exports = require_common2()(exports2);
var { formatters } = module2.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error2) {
return "[UnexpectedJSONParseError]: " + error2.message;
}
};
}
});
// ../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js
var require_has_flag = __commonJS({
"../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(exports2, module2) {
"use strict";
module2.exports = (flag, argv = process.argv) => {
const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix2 + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
};
}
});
// ../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js
var require_supports_color = __commonJS({
"../node_modules/.pnpm/supports-color@8.1.1/node_modules/supports-color/index.js"(exports2, module2) {
"use strict";
var os3 = require("os");
var tty2 = require("tty");
var hasFlag2 = require_has_flag();
var { env: env3 } = process;
var flagForceColor2;
if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
flagForceColor2 = 0;
} else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
flagForceColor2 = 1;
}
function envForceColor2() {
if ("FORCE_COLOR" in env3) {
if (env3.FORCE_COLOR === "true") {
return 1;
}
if (env3.FORCE_COLOR === "false") {
return 0;
}
return env3.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env3.FORCE_COLOR, 10), 3);
}
}
function translateLevel2(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function supportsColor2(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
const noFlagForceColor = envForceColor2();
if (noFlagForceColor !== void 0) {
flagForceColor2 = noFlagForceColor;
}
const forceColor = sniffFlags ? flagForceColor2 : noFlagForceColor;
if (forceColor === 0) {
return 0;
}
if (sniffFlags) {
if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
return 3;
}
if (hasFlag2("color=256")) {
return 2;
}
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env3.TERM === "dumb") {
return min;
}
if (process.platform === "win32") {
const osRelease = os3.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env3) {
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env3) || env3.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env3) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
}
if (env3.COLORTERM === "truecolor") {
return 3;
}
if ("TERM_PROGRAM" in env3) {
const version3 = Number.parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env3.TERM_PROGRAM) {
case "iTerm.app":
return version3 >= 3 ? 3 : 2;
case "Apple_Terminal":
return 2;
}
}
if (/-256(color)?$/i.test(env3.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
return 1;
}
if ("COLORTERM" in env3) {
return 1;
}
return min;
}
function getSupportLevel(stream, options = {}) {
const level = supportsColor2(stream, {
streamIsTTY: stream && stream.isTTY,
...options
});
return translateLevel2(level);
}
module2.exports = {
supportsColor: getSupportLevel,
stdout: getSupportLevel({ isTTY: tty2.isatty(1) }),
stderr: getSupportLevel({ isTTY: tty2.isatty(2) })
};
}
});
// ../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/node.js
var require_node = __commonJS({
"../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/node.js"(exports2, module2) {
var tty2 = require("tty");
var util2 = require("util");
exports2.init = init2;
exports2.log = log;
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load;
exports2.useColors = useColors;
exports2.destroy = util2.deprecate(
() => {
},
"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
);
exports2.colors = [6, 2, 3, 4, 5, 1];
try {
const supportsColor2 = require_supports_color();
if (supportsColor2 && (supportsColor2.stderr || supportsColor2).level >= 2) {
exports2.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error2) {
}
exports2.inspectOpts = Object.keys(process.env).filter((key) => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k) => {
return k.toUpperCase();
});
let val2 = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val2)) {
val2 = true;
} else if (/^(no|off|false|disabled)$/i.test(val2)) {
val2 = false;
} else if (val2 === "null") {
val2 = null;
} else {
val2 = Number(val2);
}
obj[prop] = val2;
return obj;
}, {});
function useColors() {
return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty2.isatty(process.stderr.fd);
}
function formatArgs(args) {
const { namespace: name, useColors: useColors2 } = this;
if (useColors2) {
const c = this.color;
const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
const prefix2 = ` ${colorCode};1m${name} \x1B[0m`;
args[0] = prefix2 + args[0].split("\n").join("\n" + prefix2);
args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = getDate() + name + " " + args[0];
}
}
function getDate() {
if (exports2.inspectOpts.hideDate) {
return "";
}
return (/* @__PURE__ */ new Date()).toISOString() + " ";
}
function log(...args) {
return process.stderr.write(util2.format(...args) + "\n");
}
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
delete process.env.DEBUG;
}
}
function load() {
return process.env.DEBUG;
}
function init2(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports2.inspectOpts);
for (let i2 = 0; i2 < keys.length; i2++) {
debug.inspectOpts[keys[i2]] = exports2.inspectOpts[keys[i2]];
}
}
module2.exports = require_common2()(exports2);
var { formatters } = module2.exports;
formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
};
formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts);
};
}
});
// ../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/index.js
var require_src2 = __commonJS({
"../node_modules/.pnpm/debug@4.3.4/node_modules/debug/src/index.js"(exports2, module2) {
if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
module2.exports = require_browser();
} else {
module2.exports = require_node();
}
}
});
// ../node_modules/.pnpm/esbuild-register@3.5.0_esbuild@0.19.12/node_modules/esbuild-register/dist/node.js
var require_node2 = __commonJS({
"../node_modules/.pnpm/esbuild-register@3.5.0_esbuild@0.19.12/node_modules/esbuild-register/dist/node.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
function _interopRequireDefault2(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var __create3 = Object.create;
var __defProp3 = Object.defineProperty;
var __getProtoOf3 = Object.getPrototypeOf;
var __hasOwnProp3 = Object.prototype.hasOwnProperty;
var __getOwnPropNames3 = Object.getOwnPropertyNames;
var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
var __markAsModule = (target) => __defProp3(target, "__esModule", { value: true });
var __commonJS3 = (callback, module22) => () => {
if (!module22) {
module22 = { exports: {} };
callback(module22.exports, module22);
}
return module22.exports;
};
var __exportStar3 = (target, module22, desc) => {
if (module22 && typeof module22 === "object" || typeof module22 === "function") {
for (let key of __getOwnPropNames3(module22))
if (!__hasOwnProp3.call(target, key) && key !== "default")
__defProp3(target, key, { get: () => module22[key], enumerable: !(desc = __getOwnPropDesc3(module22, key)) || desc.enumerable });
}
return target;
};
var __toModule = (module22) => {
return __exportStar3(__markAsModule(__defProp3(module22 != null ? __create3(__getProtoOf3(module22)) : {}, "default", module22 && module22.__esModule && "default" in module22 ? { get: () => module22.default, enumerable: true } : { value: module22, enumerable: true })), module22);
};
var require_base64 = __commonJS3((exports3) => {
var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
exports3.encode = function(number2) {
if (0 <= number2 && number2 < intToCharMap.length) {
return intToCharMap[number2];
}
throw new TypeError("Must be between 0 and 63: " + number2);
};
exports3.decode = function(charCode) {
var bigA = 65;
var bigZ = 90;
var littleA = 97;
var littleZ = 122;
var zero = 48;
var nine = 57;
var plus = 43;
var slash = 47;
var littleOffset = 26;
var numberOffset = 52;
if (bigA <= charCode && charCode <= bigZ) {
return charCode - bigA;
}
if (littleA <= charCode && charCode <= littleZ) {
return charCode - littleA + littleOffset;
}
if (zero <= charCode && charCode <= nine) {
return charCode - zero + numberOffset;
}
if (charCode == plus) {
return 62;
}
if (charCode == slash) {
return 63;
}
return -1;
};
});
var require_base64_vlq = __commonJS3((exports3) => {
var base64 = require_base64();
var VLQ_BASE_SHIFT = 5;
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
var VLQ_BASE_MASK = VLQ_BASE - 1;
var VLQ_CONTINUATION_BIT = VLQ_BASE;
function toVLQSigned(aValue) {
return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
}
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative ? -shifted : shifted;
}
exports3.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
exports3.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};
});
var require_util3 = __commonJS3((exports3) => {
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports3.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match2 = aUrl.match(urlRegexp);
if (!match2) {
return null;
}
return {
scheme: match2[1],
auth: match2[2],
host: match2[3],
port: match2[4],
path: match2[5]
};
}
exports3.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = "";
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ":";
}
url += "//";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@";
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port;
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports3.urlGenerate = urlGenerate;
function normalize(aPath) {
var path4 = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path4 = url.path;
}
var isAbsolute = exports3.isAbsolute(path4);
var parts = path4.split(/\/+/);
for (var part, up2 = 0, i2 = parts.length - 1; i2 >= 0; i2--) {
part = parts[i2];
if (part === ".") {
parts.splice(i2, 1);
} else if (part === "..") {
up2++;
} else if (up2 > 0) {
if (part === "") {
parts.splice(i2 + 1, up2);
up2 = 0;
} else {
parts.splice(i2, 2);
up2--;
}
}
}
path4 = parts.join("/");
if (path4 === "") {
path4 = isAbsolute ? "/" : ".";
}
if (url) {
url.path = path4;
return urlGenerate(url);
}
return path4;
}
exports3.normalize = normalize;
function join22(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || "/";
}
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === "/" ? aPath : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports3.join = join22;
exports3.isAbsolute = function(aPath) {
return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
};
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, "");
var level = 0;
while (aPath.indexOf(aRoot + "/") !== 0) {
var index5 = aRoot.lastIndexOf("/");
if (index5 < 0) {
return aPath;
}
aRoot = aRoot.slice(0, index5);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports3.relative = relative;
var supportsNullProto = function() {
var obj = /* @__PURE__ */ Object.create(null);
return !("__proto__" in obj);
}();
function identity(s2) {
return s2;
}
function toSetString(aStr) {
if (isProtoString(aStr)) {
return "$" + aStr;
}
return aStr;
}
exports3.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports3.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s2) {
if (!s2) {
return false;
}
var length = s2.length;
if (length < 9) {
return false;
}
if (s2.charCodeAt(length - 1) !== 95 || s2.charCodeAt(length - 2) !== 95 || s2.charCodeAt(length - 3) !== 111 || s2.charCodeAt(length - 4) !== 116 || s2.charCodeAt(length - 5) !== 111 || s2.charCodeAt(length - 6) !== 114 || s2.charCodeAt(length - 7) !== 112 || s2.charCodeAt(length - 8) !== 95 || s2.charCodeAt(length - 9) !== 95) {
return false;
}
for (var i2 = length - 10; i2 >= 0; i2--) {
if (s2.charCodeAt(i2) !== 36) {
return false;
}
}
return true;
}
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports3.compareByOriginalPositions = compareByOriginalPositions;
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports3.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 === null) {
return 1;
}
if (aStr2 === null) {
return -1;
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports3.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
function parseSourceMapInput(str) {
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
}
exports3.parseSourceMapInput = parseSourceMapInput;
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
sourceURL = sourceURL || "";
if (sourceRoot) {
if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
sourceRoot += "/";
}
sourceURL = sourceRoot + sourceURL;
}
if (sourceMapURL) {
var parsed = urlParse(sourceMapURL);
if (!parsed) {
throw new Error("sourceMapURL could not be parsed");
}
if (parsed.path) {
var index5 = parsed.path.lastIndexOf("/");
if (index5 >= 0) {
parsed.path = parsed.path.substring(0, index5 + 1);
}
}
sourceURL = join22(urlGenerate(parsed), sourceURL);
}
return normalize(sourceURL);
}
exports3.computeSourceURL = computeSourceURL;
});
var require_array_set = __commonJS3((exports3) => {
var util2 = require_util3();
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";
function ArraySet() {
this._array = [];
this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
}
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i2 = 0, len = aArray.length; i2 < len; i2++) {
set.add(aArray[i2], aAllowDuplicates);
}
return set;
};
ArraySet.prototype.size = function ArraySet_size() {
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = hasNativeMap ? aStr : util2.toSetString(aStr);
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
if (hasNativeMap) {
this._set.set(aStr, idx);
} else {
this._set[sStr] = idx;
}
}
};
ArraySet.prototype.has = function ArraySet_has(aStr) {
if (hasNativeMap) {
return this._set.has(aStr);
} else {
var sStr = util2.toSetString(aStr);
return has.call(this._set, sStr);
}
};
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (hasNativeMap) {
var idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
} else {
var sStr = util2.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
}
throw new Error('"' + aStr + '" is not in the set.');
};
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error("No element indexed by " + aIdx);
};
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports3.ArraySet = ArraySet;
});
var require_mapping_list = __commonJS3((exports3) => {
var util2 = require_util3();
function generatedPositionAfter(mappingA, mappingB) {
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA || util2.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
function MappingList() {
this._array = [];
this._sorted = true;
this._last = { generatedLine: -1, generatedColumn: 0 };
}
MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util2.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports3.MappingList = MappingList;
});
var require_source_map_generator = __commonJS3((exports3) => {
var base64VLQ = require_base64_vlq();
var util2 = require_util3();
var ArraySet = require_array_set().ArraySet;
var MappingList = require_mapping_list().MappingList;
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util2.getArg(aArgs, "file", null);
this._sourceRoot = util2.getArg(aArgs, "sourceRoot", null);
this._skipValidation = util2.getArg(aArgs, "skipValidation", false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot
});
aSourceMapConsumer.eachMapping(function(mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util2.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function(sourceFile) {
var sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util2.relative(sourceRoot, sourceFile);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
var generated = util2.getArg(aArgs, "generated");
var original = util2.getArg(aArgs, "original", null);
var source = util2.getArg(aArgs, "source", null);
var name = util2.getArg(aArgs, "name", null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source,
name
});
};
SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util2.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
if (!this._sourcesContents) {
this._sourcesContents = /* @__PURE__ */ Object.create(null);
}
this._sourcesContents[util2.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
delete this._sourcesContents[util2.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
if (sourceRoot != null) {
sourceFile = util2.relative(sourceRoot, sourceFile);
}
var newSources = new ArraySet();
var newNames = new ArraySet();
this._mappings.unsortedForEach(function(mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util2.join(aSourceMapPath, mapping.source);
}
if (sourceRoot != null) {
mapping.source = util2.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
aSourceMapConsumer.sources.forEach(function(sourceFile2) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile2);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile2 = util2.join(aSourceMapPath, sourceFile2);
}
if (sourceRoot != null) {
sourceFile2 = util2.relative(sourceRoot, sourceFile2);
}
this.setSourceContent(sourceFile2, content);
}
}, this);
};
SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");
}
if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
return;
} else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
return;
} else {
throw new Error("Invalid mapping: " + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = "";
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i2 = 0, len = mappings.length; i2 < len; i2++) {
mapping = mappings[i2];
next = "";
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ";";
previousGeneratedLine++;
}
} else {
if (i2 > 0) {
if (!util2.compareByGeneratedPositionsInflated(mapping, mappings[i2 - 1])) {
continue;
}
next += ",";
}
}
next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function(source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util2.relative(aSourceRoot, source);
}
var key = util2.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
}, this);
};
SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
var map2 = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map2.file = this._file;
}
if (this._sourceRoot != null) {
map2.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot);
}
return map2;
};
SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports3.SourceMapGenerator = SourceMapGenerator;
});
var require_binary_search = __commonJS3((exports3) => {
exports3.GREATEST_LOWER_BOUND = 1;
exports3.LEAST_UPPER_BOUND = 2;
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
return mid;
} else if (cmp > 0) {
if (aHigh - mid > 1) {
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
if (aBias == exports3.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
} else {
if (mid - aLow > 1) {
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
if (aBias == exports3.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
exports3.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index5 = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports3.GREATEST_LOWER_BOUND);
if (index5 < 0) {
return -1;
}
while (index5 - 1 >= 0) {
if (aCompare(aHaystack[index5], aHaystack[index5 - 1], true) !== 0) {
break;
}
--index5;
}
return index5;
};
});
var require_quick_sort = __commonJS3((exports3) => {
function swap(ary, x2, y) {
var temp = ary[x2];
ary[x2] = ary[y];
ary[y] = temp;
}
function randomIntInRange(low, high) {
return Math.round(low + Math.random() * (high - low));
}
function doQuickSort(ary, comparator, p, r2) {
if (p < r2) {
var pivotIndex = randomIntInRange(p, r2);
var i2 = p - 1;
swap(ary, pivotIndex, r2);
var pivot = ary[r2];
for (var j = p; j < r2; j++) {
if (comparator(ary[j], pivot) <= 0) {
i2 += 1;
swap(ary, i2, j);
}
}
swap(ary, i2 + 1, j);
var q = i2 + 1;
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r2);
}
}
exports3.quickSort = function(ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};
});
var require_source_map_consumer = __commonJS3((exports3) => {
var util2 = require_util3();
var binarySearch = require_binary_search();
var ArraySet = require_array_set().ArraySet;
var base64VLQ = require_base64_vlq();
var quickSort = require_quick_sort().quickSort;
function SourceMapConsumer(aSourceMap, aSourceMapURL) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === "string") {
sourceMap = util2.parseSourceMapInput(aSourceMap);
}
return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
}
SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
};
SourceMapConsumer.prototype._version = 3;
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", {
configurable: true,
enumerable: true,
get: function() {
if (!this.__generatedMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", {
configurable: true,
enumerable: true,
get: function() {
if (!this.__originalMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index5) {
var c = aStr.charAt(index5);
return c === ";" || c === ",";
};
SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
throw new Error("Subclasses must implement _parseMappings");
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer.LEAST_UPPER_BOUND = 2;
SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function(mapping) {
var source = mapping.source === null ? null : this._sources.at(mapping.source);
source = util2.computeSourceURL(sourceRoot, source, this._sourceMapURL);
return {
source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name === null ? null : this._names.at(mapping.name)
};
}, this).forEach(aCallback, context);
};
SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
var line = util2.getArg(aArgs, "line");
var needle = {
source: util2.getArg(aArgs, "source"),
originalLine: line,
originalColumn: util2.getArg(aArgs, "column", 0)
};
needle.source = this._findSourceIndex(needle.source);
if (needle.source < 0) {
return [];
}
var mappings = [];
var index5 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND);
if (index5 >= 0) {
var mapping = this._originalMappings[index5];
if (aArgs.column === void 0) {
var originalLine = mapping.originalLine;
while (mapping && mapping.originalLine === originalLine) {
mappings.push({
line: util2.getArg(mapping, "generatedLine", null),
column: util2.getArg(mapping, "generatedColumn", null),
lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
});
mapping = this._originalMappings[++index5];
}
} else {
var originalColumn = mapping.originalColumn;
while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
mappings.push({
line: util2.getArg(mapping, "generatedLine", null),
column: util2.getArg(mapping, "generatedColumn", null),
lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
});
mapping = this._originalMappings[++index5];
}
}
}
return mappings;
};
exports3.SourceMapConsumer = SourceMapConsumer;
function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === "string") {
sourceMap = util2.parseSourceMapInput(aSourceMap);
}
var version3 = util2.getArg(sourceMap, "version");
var sources = util2.getArg(sourceMap, "sources");
var names = util2.getArg(sourceMap, "names", []);
var sourceRoot = util2.getArg(sourceMap, "sourceRoot", null);
var sourcesContent = util2.getArg(sourceMap, "sourcesContent", null);
var mappings = util2.getArg(sourceMap, "mappings");
var file = util2.getArg(sourceMap, "file", null);
if (version3 != this._version) {
throw new Error("Unsupported version: " + version3);
}
if (sourceRoot) {
sourceRoot = util2.normalize(sourceRoot);
}
sources = sources.map(String).map(util2.normalize).map(function(source) {
return sourceRoot && util2.isAbsolute(sourceRoot) && util2.isAbsolute(source) ? util2.relative(sourceRoot, source) : source;
});
this._names = ArraySet.fromArray(names.map(String), true);
this._sources = ArraySet.fromArray(sources, true);
this._absoluteSources = this._sources.toArray().map(function(s2) {
return util2.computeSourceURL(sourceRoot, s2, aSourceMapURL);
});
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this._sourceMapURL = aSourceMapURL;
this.file = file;
}
BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
var relativeSource = aSource;
if (this.sourceRoot != null) {
relativeSource = util2.relative(this.sourceRoot, relativeSource);
}
if (this._sources.has(relativeSource)) {
return this._sources.indexOf(relativeSource);
}
var i2;
for (i2 = 0; i2 < this._absoluteSources.length; ++i2) {
if (this._absoluteSources[i2] == aSource) {
return i2;
}
}
return -1;
};
BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
var smc = Object.create(BasicSourceMapConsumer.prototype);
var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
smc.file = aSourceMap._file;
smc._sourceMapURL = aSourceMapURL;
smc._absoluteSources = smc._sources.toArray().map(function(s2) {
return util2.computeSourceURL(smc.sourceRoot, s2, aSourceMapURL);
});
var generatedMappings = aSourceMap._mappings.toArray().slice();
var destGeneratedMappings = smc.__generatedMappings = [];
var destOriginalMappings = smc.__originalMappings = [];
for (var i2 = 0, length = generatedMappings.length; i2 < length; i2++) {
var srcMapping = generatedMappings[i2];
var destMapping = new Mapping();
destMapping.generatedLine = srcMapping.generatedLine;
destMapping.generatedColumn = srcMapping.generatedColumn;
if (srcMapping.source) {
destMapping.source = sources.indexOf(srcMapping.source);
destMapping.originalLine = srcMapping.originalLine;
destMapping.originalColumn = srcMapping.originalColumn;
if (srcMapping.name) {
destMapping.name = names.indexOf(srcMapping.name);
}
destOriginalMappings.push(destMapping);
}
destGeneratedMappings.push(destMapping);
}
quickSort(smc.__originalMappings, util2.compareByOriginalPositions);
return smc;
};
BasicSourceMapConsumer.prototype._version = 3;
Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", {
get: function() {
return this._absoluteSources.slice();
}
});
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var length = aStr.length;
var index5 = 0;
var cachedSegments = {};
var temp = {};
var originalMappings = [];
var generatedMappings = [];
var mapping, str, segment, end, value;
while (index5 < length) {
if (aStr.charAt(index5) === ";") {
generatedLine++;
index5++;
previousGeneratedColumn = 0;
} else if (aStr.charAt(index5) === ",") {
index5++;
} else {
mapping = new Mapping();
mapping.generatedLine = generatedLine;
for (end = index5; end < length; end++) {
if (this._charIsMappingSeparator(aStr, end)) {
break;
}
}
str = aStr.slice(index5, end);
segment = cachedSegments[str];
if (segment) {
index5 += str.length;
} else {
segment = [];
while (index5 < end) {
base64VLQ.decode(aStr, index5, temp);
value = temp.value;
index5 = temp.rest;
segment.push(value);
}
if (segment.length === 2) {
throw new Error("Found a source, but no line and column");
}
if (segment.length === 3) {
throw new Error("Found a source and line, but no column");
}
cachedSegments[str] = segment;
}
mapping.generatedColumn = previousGeneratedColumn + segment[0];
previousGeneratedColumn = mapping.generatedColumn;
if (segment.length > 1) {
mapping.source = previousSource + segment[1];
previousSource += segment[1];
mapping.originalLine = previousOriginalLine + segment[2];
previousOriginalLine = mapping.originalLine;
mapping.originalLine += 1;
mapping.originalColumn = previousOriginalColumn + segment[3];
previousOriginalColumn = mapping.originalColumn;
if (segment.length > 4) {
mapping.name = previousName + segment[4];
previousName += segment[4];
}
}
generatedMappings.push(mapping);
if (typeof mapping.originalLine === "number") {
originalMappings.push(mapping);
}
}
}
quickSort(generatedMappings, util2.compareByGeneratedPositionsDeflated);
this.__generatedMappings = generatedMappings;
quickSort(originalMappings, util2.compareByOriginalPositions);
this.__originalMappings = originalMappings;
};
BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
if (aNeedle[aLineName] <= 0) {
throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
};
BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
for (var index5 = 0; index5 < this._generatedMappings.length; ++index5) {
var mapping = this._generatedMappings[index5];
if (index5 + 1 < this._generatedMappings.length) {
var nextMapping = this._generatedMappings[index5 + 1];
if (mapping.generatedLine === nextMapping.generatedLine) {
mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
continue;
}
}
mapping.lastGeneratedColumn = Infinity;
}
};
BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util2.getArg(aArgs, "line"),
generatedColumn: util2.getArg(aArgs, "column")
};
var index5 = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util2.compareByGeneratedPositionsDeflated, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index5 >= 0) {
var mapping = this._generatedMappings[index5];
if (mapping.generatedLine === needle.generatedLine) {
var source = util2.getArg(mapping, "source", null);
if (source !== null) {
source = this._sources.at(source);
source = util2.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
}
var name = util2.getArg(mapping, "name", null);
if (name !== null) {
name = this._names.at(name);
}
return {
source,
line: util2.getArg(mapping, "originalLine", null),
column: util2.getArg(mapping, "originalColumn", null),
name
};
}
}
return {
source: null,
line: null,
column: null,
name: null
};
};
BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
if (!this.sourcesContent) {
return false;
}
return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
return sc == null;
});
};
BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
if (!this.sourcesContent) {
return null;
}
var index5 = this._findSourceIndex(aSource);
if (index5 >= 0) {
return this.sourcesContent[index5];
}
var relativeSource = aSource;
if (this.sourceRoot != null) {
relativeSource = util2.relative(this.sourceRoot, relativeSource);
}
var url;
if (this.sourceRoot != null && (url = util2.urlParse(this.sourceRoot))) {
var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
}
if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) {
return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
}
}
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + relativeSource + '" is not in the SourceMap.');
}
};
BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
var source = util2.getArg(aArgs, "source");
source = this._findSourceIndex(source);
if (source < 0) {
return {
line: null,
column: null,
lastColumn: null
};
}
var needle = {
source,
originalLine: util2.getArg(aArgs, "line"),
originalColumn: util2.getArg(aArgs, "column")
};
var index5 = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index5 >= 0) {
var mapping = this._originalMappings[index5];
if (mapping.source === needle.source) {
return {
line: util2.getArg(mapping, "generatedLine", null),
column: util2.getArg(mapping, "generatedColumn", null),
lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null)
};
}
}
return {
line: null,
column: null,
lastColumn: null
};
};
exports3.BasicSourceMapConsumer = BasicSourceMapConsumer;
function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === "string") {
sourceMap = util2.parseSourceMapInput(aSourceMap);
}
var version3 = util2.getArg(sourceMap, "version");
var sections = util2.getArg(sourceMap, "sections");
if (version3 != this._version) {
throw new Error("Unsupported version: " + version3);
}
this._sources = new ArraySet();
this._names = new ArraySet();
var lastOffset = {
line: -1,
column: 0
};
this._sections = sections.map(function(s2) {
if (s2.url) {
throw new Error("Support for url field in sections not implemented.");
}
var offset = util2.getArg(s2, "offset");
var offsetLine = util2.getArg(offset, "line");
var offsetColumn = util2.getArg(offset, "column");
if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
throw new Error("Section offsets must be ordered and non-overlapping.");
}
lastOffset = offset;
return {
generatedOffset: {
generatedLine: offsetLine + 1,
generatedColumn: offsetColumn + 1
},
consumer: new SourceMapConsumer(util2.getArg(s2, "map"), aSourceMapURL)
};
});
}
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
IndexedSourceMapConsumer.prototype._version = 3;
Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", {
get: function() {
var sources = [];
for (var i2 = 0; i2 < this._sections.length; i2++) {
for (var j = 0; j < this._sections[i2].consumer.sources.length; j++) {
sources.push(this._sections[i2].consumer.sources[j]);
}
}
return sources;
}
});
IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util2.getArg(aArgs, "line"),
generatedColumn: util2.getArg(aArgs, "column")
};
var sectionIndex = binarySearch.search(needle, this._sections, function(needle2, section2) {
var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine;
if (cmp) {
return cmp;
}
return needle2.generatedColumn - section2.generatedOffset.generatedColumn;
});
var section = this._sections[sectionIndex];
if (!section) {
return {
source: null,
line: null,
column: null,
name: null
};
}
return section.consumer.originalPositionFor({
line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
bias: aArgs.bias
});
};
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
return this._sections.every(function(s2) {
return s2.consumer.hasContentsOfAllSources();
});
};
IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
for (var i2 = 0; i2 < this._sections.length; i2++) {
var section = this._sections[i2];
var content = section.consumer.sourceContentFor(aSource, true);
if (content) {
return content;
}
}
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
for (var i2 = 0; i2 < this._sections.length; i2++) {
var section = this._sections[i2];
if (section.consumer._findSourceIndex(util2.getArg(aArgs, "source")) === -1) {
continue;
}
var generatedPosition = section.consumer.generatedPositionFor(aArgs);
if (generatedPosition) {
var ret = {
line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
};
return ret;
}
}
return {
line: null,
column: null
};
};
IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
this.__generatedMappings = [];
this.__originalMappings = [];
for (var i2 = 0; i2 < this._sections.length; i2++) {
var section = this._sections[i2];
var sectionMappings = section.consumer._generatedMappings;
for (var j = 0; j < sectionMappings.length; j++) {
var mapping = sectionMappings[j];
var source = section.consumer._sources.at(mapping.source);
source = util2.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
this._sources.add(source);
source = this._sources.indexOf(source);
var name = null;
if (mapping.name) {
name = section.consumer._names.at(mapping.name);
this._names.add(name);
name = this._names.indexOf(name);
}
var adjustedMapping = {
source,
generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name
};
this.__generatedMappings.push(adjustedMapping);
if (typeof adjustedMapping.originalLine === "number") {
this.__originalMappings.push(adjustedMapping);
}
}
}
quickSort(this.__generatedMappings, util2.compareByGeneratedPositionsDeflated);
quickSort(this.__originalMappings, util2.compareByOriginalPositions);
};
exports3.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
});
var require_source_node = __commonJS3((exports3) => {
var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
var util2 = require_util3();
var REGEX_NEWLINE = /(\r?\n)/;
var NEWLINE_CODE = 10;
var isSourceNode = "$$$isSourceNode$$$";
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null)
this.add(aChunks);
}
SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
var node = new SourceNode();
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var remainingLinesIndex = 0;
var shiftNextLine = function() {
var lineContents = getNextLine();
var newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
}
};
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
var lastMapping = null;
aSourceMapConsumer.eachMapping(function(mapping) {
if (lastMapping !== null) {
if (lastGeneratedLine < mapping.generatedLine) {
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
} else {
var nextLine = remainingLines[remainingLinesIndex] || "";
var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
lastMapping = mapping;
return;
}
}
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[remainingLinesIndex] || "";
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
if (remainingLinesIndex < remainingLines.length) {
if (lastMapping) {
addMappingWithCode(lastMapping, shiftNextLine());
}
node.add(remainingLines.splice(remainingLinesIndex).join(""));
}
aSourceMapConsumer.sources.forEach(function(sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util2.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === void 0) {
node.add(code);
} else {
var source = aRelativePath ? util2.join(aRelativePath, mapping.source) : mapping.source;
node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
}
}
};
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function(chunk) {
this.add(chunk);
}, this);
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i2 = aChunk.length - 1; i2 >= 0; i2--) {
this.prepend(aChunk[i2]);
}
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i2 = 0, len = this.children.length; i2 < len; i2++) {
chunk = this.children[i2];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
} else {
if (chunk !== "") {
aFn(chunk, {
source: this.source,
line: this.line,
column: this.column,
name: this.name
});
}
}
}
};
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i2;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i2 = 0; i2 < len - 1; i2++) {
newChildren.push(this.children[i2]);
newChildren.push(aSep);
}
newChildren.push(this.children[i2]);
this.children = newChildren;
}
return this;
};
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
} else if (typeof lastChild === "string") {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
} else {
this.children.push("".replace(aPattern, aReplacement));
}
return this;
};
SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util2.toSetString(aSourceFile)] = aSourceContent;
};
SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
for (var i2 = 0, len = this.children.length; i2 < len; i2++) {
if (this.children[i2][isSourceNode]) {
this.children[i2].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i2 = 0, len = sources.length; i2 < len; i2++) {
aFn(util2.fromSetString(sources[i2]), this.sourceContents[sources[i2]]);
}
};
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function(chunk) {
str += chunk;
});
return str;
};
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map2 = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function(chunk, original) {
generated.code += chunk;
if (original.source !== null && original.line !== null && original.column !== null) {
if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
map2.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map2.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map2.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function(sourceFile, sourceContent) {
map2.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map2 };
};
exports3.SourceNode = SourceNode;
});
var require_source_map = __commonJS3((exports3) => {
exports3.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
exports3.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
exports3.SourceNode = require_source_node().SourceNode;
});
var require_buffer_from = __commonJS3((exports3, module22) => {
var toString = Object.prototype.toString;
var isModern = typeof Buffer.alloc === "function" && typeof Buffer.allocUnsafe === "function" && typeof Buffer.from === "function";
function isArrayBuffer(input) {
return toString.call(input).slice(8, -1) === "ArrayBuffer";
}
function fromArrayBuffer(obj, byteOffset, length) {
byteOffset >>>= 0;
var maxLength = obj.byteLength - byteOffset;
if (maxLength < 0) {
throw new RangeError("'offset' is out of bounds");
}
if (length === void 0) {
length = maxLength;
} else {
length >>>= 0;
if (length > maxLength) {
throw new RangeError("'length' is out of bounds");
}
}
return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)));
}
function fromString(string2, encoding) {
if (typeof encoding !== "string" || encoding === "") {
encoding = "utf8";
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding');
}
return isModern ? Buffer.from(string2, encoding) : new Buffer(string2, encoding);
}
function bufferFrom(value, encodingOrOffset, length) {
if (typeof value === "number") {
throw new TypeError('"value" argument must not be a number');
}
if (isArrayBuffer(value)) {
return fromArrayBuffer(value, encodingOrOffset, length);
}
if (typeof value === "string") {
return fromString(value, encodingOrOffset);
}
return isModern ? Buffer.from(value) : new Buffer(value);
}
module22.exports = bufferFrom;
});
var require_source_map_support = __commonJS3((exports3, module22) => {
var SourceMapConsumer = require_source_map().SourceMapConsumer;
var path4 = require("path");
var fs32;
try {
fs32 = require("fs");
if (!fs32.existsSync || !fs32.readFileSync) {
fs32 = null;
}
} catch (err2) {
}
var bufferFrom = require_buffer_from();
function dynamicRequire(mod, request) {
return mod.require(request);
}
var errorFormatterInstalled = false;
var uncaughtShimInstalled = false;
var emptyCacheBetweenOperations = false;
var environment = "auto";
var fileContentsCache = {};
var sourceMapCache = {};
var reSourceMap = /^data:application\/json[^,]+base64,/;
var retrieveFileHandlers = [];
var retrieveMapHandlers = [];
function isInBrowser() {
if (environment === "browser")
return true;
if (environment === "node")
return false;
return typeof window !== "undefined" && typeof XMLHttpRequest === "function" && !(window.require && window.module && window.process && window.process.type === "renderer");
}
function hasGlobalProcessEventEmitter() {
return typeof process === "object" && process !== null && typeof process.on === "function";
}
function handlerExec(list) {
return function(arg) {
for (var i2 = 0; i2 < list.length; i2++) {
var ret = list[i2](arg);
if (ret) {
return ret;
}
}
return null;
};
}
var retrieveFile = handlerExec(retrieveFileHandlers);
retrieveFileHandlers.push(function(path22) {
path22 = path22.trim();
if (/^file:/.test(path22)) {
path22 = path22.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
return drive ? "" : "/";
});
}
if (path22 in fileContentsCache) {
return fileContentsCache[path22];
}
var contents = "";
try {
if (!fs32) {
var xhr = new XMLHttpRequest();
xhr.open("GET", path22, false);
xhr.send(null);
if (xhr.readyState === 4 && xhr.status === 200) {
contents = xhr.responseText;
}
} else if (fs32.existsSync(path22)) {
contents = fs32.readFileSync(path22, "utf8");
}
} catch (er) {
}
return fileContentsCache[path22] = contents;
});
function supportRelativeURL(file, url) {
if (!file)
return url;
var dir = path4.dirname(file);
var match2 = /^\w+:\/\/[^\/]*/.exec(dir);
var protocol = match2 ? match2[0] : "";
var startPath = dir.slice(protocol.length);
if (protocol && /^\/\w\:/.test(startPath)) {
protocol += "/";
return protocol + path4.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
}
return protocol + path4.resolve(dir.slice(protocol.length), url);
}
function retrieveSourceMapURL(source) {
var fileData;
if (isInBrowser()) {
try {
var xhr = new XMLHttpRequest();
xhr.open("GET", source, false);
xhr.send(null);
fileData = xhr.readyState === 4 ? xhr.responseText : null;
var sourceMapHeader = xhr.getResponseHeader("SourceMap") || xhr.getResponseHeader("X-SourceMap");
if (sourceMapHeader) {
return sourceMapHeader;
}
} catch (e2) {
}
}
fileData = retrieveFile(source);
var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
var lastMatch, match2;
while (match2 = re.exec(fileData))
lastMatch = match2;
if (!lastMatch)
return null;
return lastMatch[1];
}
var retrieveSourceMap = handlerExec(retrieveMapHandlers);
retrieveMapHandlers.push(function(source) {
var sourceMappingURL = retrieveSourceMapURL(source);
if (!sourceMappingURL)
return null;
var sourceMapData;
if (reSourceMap.test(sourceMappingURL)) {
var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
sourceMapData = bufferFrom(rawData, "base64").toString();
sourceMappingURL = source;
} else {
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
sourceMapData = retrieveFile(sourceMappingURL);
}
if (!sourceMapData) {
return null;
}
return {
url: sourceMappingURL,
map: sourceMapData
};
});
function mapSourcePosition(position) {
var sourceMap = sourceMapCache[position.source];
if (!sourceMap) {
var urlAndMap = retrieveSourceMap(position.source);
if (urlAndMap) {
sourceMap = sourceMapCache[position.source] = {
url: urlAndMap.url,
map: new SourceMapConsumer(urlAndMap.map)
};
if (sourceMap.map.sourcesContent) {
sourceMap.map.sources.forEach(function(source, i2) {
var contents = sourceMap.map.sourcesContent[i2];
if (contents) {
var url = supportRelativeURL(sourceMap.url, source);
fileContentsCache[url] = contents;
}
});
}
} else {
sourceMap = sourceMapCache[position.source] = {
url: null,
map: null
};
}
}
if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === "function") {
var originalPosition = sourceMap.map.originalPositionFor(position);
if (originalPosition.source !== null) {
originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source);
return originalPosition;
}
}
return position;
}
function mapEvalOrigin(origin) {
var match2 = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
if (match2) {
var position = mapSourcePosition({
source: match2[2],
line: +match2[3],
column: match2[4] - 1
});
return "eval at " + match2[1] + " (" + position.source + ":" + position.line + ":" + (position.column + 1) + ")";
}
match2 = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
if (match2) {
return "eval at " + match2[1] + " (" + mapEvalOrigin(match2[2]) + ")";
}
return origin;
}
function CallSiteToString() {
var fileName;
var fileLocation = "";
if (this.isNative()) {
fileLocation = "native";
} else {
fileName = this.getScriptNameOrSourceURL();
if (!fileName && this.isEval()) {
fileLocation = this.getEvalOrigin();
fileLocation += ", ";
}
if (fileName) {
fileLocation += fileName;
} else {
fileLocation += "<anonymous>";
}
var lineNumber = this.getLineNumber();
if (lineNumber != null) {
fileLocation += ":" + lineNumber;
var columnNumber = this.getColumnNumber();
if (columnNumber) {
fileLocation += ":" + columnNumber;
}
}
}
var line = "";
var functionName = this.getFunctionName();
var addSuffix = true;
var isConstructor = this.isConstructor();
var isMethodCall = !(this.isToplevel() || isConstructor);
if (isMethodCall) {
var typeName = this.getTypeName();
if (typeName === "[object Object]") {
typeName = "null";
}
var methodName = this.getMethodName();
if (functionName) {
if (typeName && functionName.indexOf(typeName) != 0) {
line += typeName + ".";
}
line += functionName;
if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
line += " [as " + methodName + "]";
}
} else {
line += typeName + "." + (methodName || "<anonymous>");
}
} else if (isConstructor) {
line += "new " + (functionName || "<anonymous>");
} else if (functionName) {
line += functionName;
} else {
line += fileLocation;
addSuffix = false;
}
if (addSuffix) {
line += " (" + fileLocation + ")";
}
return line;
}
function cloneCallSite(frame) {
var object = {};
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
object[name] = /^(?:is|get)/.test(name) ? function() {
return frame[name].call(frame);
} : frame[name];
});
object.toString = CallSiteToString;
return object;
}
function wrapCallSite(frame, state) {
if (state === void 0) {
state = { nextPosition: null, curPosition: null };
}
if (frame.isNative()) {
state.curPosition = null;
return frame;
}
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
if (source) {
var line = frame.getLineNumber();
var column9 = frame.getColumnNumber() - 1;
var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
var headerLength = noHeader.test(process.version) ? 0 : 62;
if (line === 1 && column9 > headerLength && !isInBrowser() && !frame.isEval()) {
column9 -= headerLength;
}
var position = mapSourcePosition({
source,
line,
column: column9
});
state.curPosition = position;
frame = cloneCallSite(frame);
var originalFunctionName = frame.getFunctionName;
frame.getFunctionName = function() {
if (state.nextPosition == null) {
return originalFunctionName();
}
return state.nextPosition.name || originalFunctionName();
};
frame.getFileName = function() {
return position.source;
};
frame.getLineNumber = function() {
return position.line;
};
frame.getColumnNumber = function() {
return position.column + 1;
};
frame.getScriptNameOrSourceURL = function() {
return position.source;
};
return frame;
}
var origin = frame.isEval() && frame.getEvalOrigin();
if (origin) {
origin = mapEvalOrigin(origin);
frame = cloneCallSite(frame);
frame.getEvalOrigin = function() {
return origin;
};
return frame;
}
return frame;
}
function prepareStackTrace(error2, stack) {
if (emptyCacheBetweenOperations) {
fileContentsCache = {};
sourceMapCache = {};
}
var name = error2.name || "Error";
var message = error2.message || "";
var errorString = name + ": " + message;
var state = { nextPosition: null, curPosition: null };
var processedStack = [];
for (var i2 = stack.length - 1; i2 >= 0; i2--) {
processedStack.push("\n at " + wrapCallSite(stack[i2], state));
state.nextPosition = state.curPosition;
}
state.curPosition = state.nextPosition = null;
return errorString + processedStack.reverse().join("");
}
function getErrorSource(error2) {
var match2 = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error2.stack);
if (match2) {
var source = match2[1];
var line = +match2[2];
var column9 = +match2[3];
var contents = fileContentsCache[source];
if (!contents && fs32 && fs32.existsSync(source)) {
try {
contents = fs32.readFileSync(source, "utf8");
} catch (er) {
contents = "";
}
}
if (contents) {
var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
if (code) {
return source + ":" + line + "\n" + code + "\n" + new Array(column9).join(" ") + "^";
}
}
}
return null;
}
function printErrorAndExit(error2) {
var source = getErrorSource(error2);
if (process.stderr._handle && process.stderr._handle.setBlocking) {
process.stderr._handle.setBlocking(true);
}
if (source) {
console.error();
console.error(source);
}
console.error(error2.stack);
process.exit(1);
}
function shimEmitUncaughtException() {
var origEmit = process.emit;
process.emit = function(type) {
if (type === "uncaughtException") {
var hasStack = arguments[1] && arguments[1].stack;
var hasListeners = this.listeners(type).length > 0;
if (hasStack && !hasListeners) {
return printErrorAndExit(arguments[1]);
}
}
return origEmit.apply(this, arguments);
};
}
var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
exports3.wrapCallSite = wrapCallSite;
exports3.getErrorSource = getErrorSource;
exports3.mapSourcePosition = mapSourcePosition;
exports3.retrieveSourceMap = retrieveSourceMap;
exports3.install = function(options) {
options = options || {};
if (options.environment) {
environment = options.environment;
if (["node", "browser", "auto"].indexOf(environment) === -1) {
throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}");
}
}
if (options.retrieveFile) {
if (options.overrideRetrieveFile) {
retrieveFileHandlers.length = 0;
}
retrieveFileHandlers.unshift(options.retrieveFile);
}
if (options.retrieveSourceMap) {
if (options.overrideRetrieveSourceMap) {
retrieveMapHandlers.length = 0;
}
retrieveMapHandlers.unshift(options.retrieveSourceMap);
}
if (options.hookRequire && !isInBrowser()) {
var Module = dynamicRequire(module22, "module");
var $compile = Module.prototype._compile;
if (!$compile.__sourceMapSupport) {
Module.prototype._compile = function(content, filename) {
fileContentsCache[filename] = content;
sourceMapCache[filename] = void 0;
return $compile.call(this, content, filename);
};
Module.prototype._compile.__sourceMapSupport = true;
}
}
if (!emptyCacheBetweenOperations) {
emptyCacheBetweenOperations = "emptyCacheBetweenOperations" in options ? options.emptyCacheBetweenOperations : false;
}
if (!errorFormatterInstalled) {
errorFormatterInstalled = true;
Error.prepareStackTrace = prepareStackTrace;
}
if (!uncaughtShimInstalled) {
var installHandler = "handleUncaughtExceptions" in options ? options.handleUncaughtExceptions : true;
try {
var worker_threads = dynamicRequire(module22, "worker_threads");
if (worker_threads.isMainThread === false) {
installHandler = false;
}
} catch (e2) {
}
if (installHandler && hasGlobalProcessEventEmitter()) {
uncaughtShimInstalled = true;
shimEmitUncaughtException();
}
}
};
exports3.resetRetrieveHandlers = function() {
retrieveFileHandlers.length = 0;
retrieveMapHandlers.length = 0;
retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
retrieveSourceMap = handlerExec(retrieveMapHandlers);
retrieveFile = handlerExec(retrieveFileHandlers);
};
});
var require_node_modules_regexp = __commonJS3((exports3, module22) => {
"use strict";
module22.exports = /^(?:.*[\\\/])?node_modules(?:[\\\/].*)?$/;
});
var require_lib2 = __commonJS3((exports3, module22) => {
"use strict";
Object.defineProperty(exports3, "__esModule", {
value: true
});
exports3.addHook = addHook2;
var _module = _interopRequireDefault(require("module"));
var _path = _interopRequireDefault(require("path"));
var _nodeModulesRegexp = _interopRequireDefault(require_node_modules_regexp());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var Module = module22.constructor.length > 1 ? module22.constructor : _module.default;
var HOOK_RETURNED_NOTHING_ERROR_MESSAGE = "[Pirates] A hook returned a non-string, or nothing at all! This is a violation of intergalactic law!\n--------------------\nIf you have no idea what this means or what Pirates is, let me explain: Pirates is a module that makes is easy to implement require hooks. One of the require hooks you're using uses it. One of these require hooks didn't return anything from it's handler, so we don't know what to do. You might want to debug this.";
function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
if (typeof filename !== "string") {
return false;
}
if (exts.indexOf(_path.default.extname(filename)) === -1) {
return false;
}
const resolvedFilename = _path.default.resolve(filename);
if (ignoreNodeModules && _nodeModulesRegexp.default.test(resolvedFilename)) {
return false;
}
if (matcher && typeof matcher === "function") {
return !!matcher(resolvedFilename);
}
return true;
}
function addHook2(hook, opts = {}) {
let reverted = false;
const loaders = [];
const oldLoaders = [];
let exts;
const originalJSLoader = Module._extensions[".js"];
const matcher = opts.matcher || null;
const ignoreNodeModules = opts.ignoreNodeModules !== false;
exts = opts.extensions || opts.exts || opts.extension || opts.ext || [".js"];
if (!Array.isArray(exts)) {
exts = [exts];
}
exts.forEach((ext2) => {
if (typeof ext2 !== "string") {
throw new TypeError(`Invalid Extension: ${ext2}`);
}
const oldLoader = Module._extensions[ext2] || originalJSLoader;
oldLoaders[ext2] = oldLoader;
loaders[ext2] = Module._extensions[ext2] = function newLoader(mod, filename) {
let compile;
if (!reverted) {
if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
compile = mod._compile;
mod._compile = function _compile(code) {
mod._compile = compile;
const newCode = hook(code, filename);
if (typeof newCode !== "string") {
throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
}
return mod._compile(newCode, filename);
};
}
}
oldLoader(mod, filename);
};
});
return function revert() {
if (reverted)
return;
reverted = true;
exts.forEach((ext2) => {
if (Module._extensions[ext2] === loaders[ext2]) {
Module._extensions[ext2] = oldLoaders[ext2];
}
});
};
}
});
var require_lib22 = __commonJS3((exports3, module22) => {
"use strict";
Object.defineProperty(exports3, "__esModule", {
value: true
});
exports3.default = void 0;
var _fs = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function asyncGeneratorStep(gen, resolve2, reject, _next, _throw, key, arg) {
try {
var info2 = gen[key](arg);
var value = info2.value;
} catch (error2) {
reject(error2);
return;
}
if (info2.done) {
resolve2(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self2 = this, args = arguments;
return new Promise(function(resolve2, reject) {
var gen = fn.apply(self2, args);
function _next(value) {
asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "next", value);
}
function _throw(err2) {
asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "throw", err2);
}
_next(void 0);
});
};
}
var readFile2 = (fp) => new Promise((resolve2, reject) => {
_fs.default.readFile(fp, "utf8", (err2, data) => {
if (err2)
return reject(err2);
resolve2(data);
});
});
var readFileSync3 = (fp) => {
return _fs.default.readFileSync(fp, "utf8");
};
var pathExists = (fp) => new Promise((resolve2) => {
_fs.default.access(fp, (err2) => {
resolve2(!err2);
});
});
var pathExistsSync = _fs.default.existsSync;
var JoyCon2 = class {
constructor({
files,
cwd = process.cwd(),
stopDir,
packageKey,
parseJSON = JSON.parse
} = {}) {
this.options = {
files,
cwd,
stopDir,
packageKey,
parseJSON
};
this.existsCache = /* @__PURE__ */ new Map();
this.loaders = /* @__PURE__ */ new Set();
this.packageJsonCache = /* @__PURE__ */ new Map();
}
addLoader(loader) {
this.loaders.add(loader);
return this;
}
removeLoader(name) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = void 0;
try {
for (var _iterator = this.loaders[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const loader = _step.value;
if (name && loader.name === name) {
this.loaders.delete(loader);
}
}
} catch (err2) {
_didIteratorError = true;
_iteratorError = err2;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return this;
}
recusivelyResolve(options) {
var _this = this;
return _asyncToGenerator(function* () {
if (options.cwd === options.stopDir || _path.default.basename(options.cwd) === "node_modules") {
return null;
}
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = void 0;
try {
for (var _iterator4 = options.files[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
const filename = _step4.value;
const file = _path.default.resolve(options.cwd, filename);
const exists = process.env.NODE_ENV !== "test" && _this.existsCache.has(file) ? _this.existsCache.get(file) : yield pathExists(file);
_this.existsCache.set(file, exists);
if (exists) {
if (!options.packageKey || _path.default.basename(file) !== "package.json") {
return file;
}
const data = require(file);
delete require.cache[file];
const hasPackageKey = Object.prototype.hasOwnProperty.call(data, options.packageKey);
if (hasPackageKey) {
_this.packageJsonCache.set(file, data);
return file;
}
}
continue;
}
} catch (err2) {
_didIteratorError4 = true;
_iteratorError4 = err2;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
return _this.recusivelyResolve(Object.assign({}, options, {
cwd: _path.default.dirname(options.cwd)
}));
})();
}
recusivelyResolveSync(options) {
if (options.cwd === options.stopDir || _path.default.basename(options.cwd) === "node_modules") {
return null;
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = void 0;
try {
for (var _iterator2 = options.files[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
const filename = _step2.value;
const file = _path.default.resolve(options.cwd, filename);
const exists = process.env.NODE_ENV !== "test" && this.existsCache.has(file) ? this.existsCache.get(file) : pathExistsSync(file);
this.existsCache.set(file, exists);
if (exists) {
if (!options.packageKey || _path.default.basename(file) !== "package.json") {
return file;
}
const data = require(file);
delete require.cache[file];
const hasPackageKey = Object.prototype.hasOwnProperty.call(data, options.packageKey);
if (hasPackageKey) {
this.packageJsonCache.set(file, data);
return file;
}
}
continue;
}
} catch (err2) {
_didIteratorError2 = true;
_iteratorError2 = err2;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return this.recusivelyResolveSync(Object.assign({}, options, {
cwd: _path.default.dirname(options.cwd)
}));
}
resolve(...args) {
var _this2 = this;
return _asyncToGenerator(function* () {
const options = _this2.normalizeOptions(args);
return _this2.recusivelyResolve(options);
})();
}
resolveSync(...args) {
const options = this.normalizeOptions(args);
return this.recusivelyResolveSync(options);
}
load(...args) {
var _this3 = this;
return _asyncToGenerator(function* () {
const options = _this3.normalizeOptions(args);
const filepath = yield _this3.recusivelyResolve(options);
if (filepath) {
const loader = _this3.findLoader(filepath);
if (loader) {
return {
path: filepath,
data: yield loader.load(filepath)
};
}
const extname2 = _path.default.extname(filepath).slice(1);
if (extname2 === "js") {
delete require.cache[filepath];
return {
path: filepath,
data: require(filepath)
};
}
if (extname2 === "json") {
if (_this3.packageJsonCache.has(filepath)) {
return {
path: filepath,
data: _this3.packageJsonCache.get(filepath)[options.packageKey]
};
}
const data = _this3.options.parseJSON(yield readFile2(filepath));
return {
path: filepath,
data
};
}
return {
path: filepath,
data: yield readFile2(filepath)
};
}
return {};
})();
}
loadSync(...args) {
const options = this.normalizeOptions(args);
const filepath = this.recusivelyResolveSync(options);
if (filepath) {
const loader = this.findLoader(filepath);
if (loader) {
return {
path: filepath,
data: loader.loadSync(filepath)
};
}
const extname2 = _path.default.extname(filepath).slice(1);
if (extname2 === "js") {
delete require.cache[filepath];
return {
path: filepath,
data: require(filepath)
};
}
if (extname2 === "json") {
if (this.packageJsonCache.has(filepath)) {
return {
path: filepath,
data: this.packageJsonCache.get(filepath)[options.packageKey]
};
}
const data = this.options.parseJSON(readFileSync3(filepath));
return {
path: filepath,
data
};
}
return {
path: filepath,
data: readFileSync3(filepath)
};
}
return {};
}
findLoader(filepath) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = void 0;
try {
for (var _iterator3 = this.loaders[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
const loader = _step3.value;
if (loader.test && loader.test.test(filepath)) {
return loader;
}
}
} catch (err2) {
_didIteratorError3 = true;
_iteratorError3 = err2;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
return null;
}
clearCache() {
this.existsCache.clear();
this.packageJsonCache.clear();
return this;
}
normalizeOptions(args) {
const options = Object.assign({}, this.options);
if (Object.prototype.toString.call(args[0]) === "[object Object]") {
Object.assign(options, args[0]);
} else {
if (args[0]) {
options.files = args[0];
}
if (args[1]) {
options.cwd = args[1];
}
if (args[2]) {
options.stopDir = args[2];
}
}
options.cwd = _path.default.resolve(options.cwd);
options.stopDir = options.stopDir ? _path.default.resolve(options.stopDir) : _path.default.parse(options.cwd).root;
if (!options.files || options.files.length === 0) {
throw new Error("[joycon] files must be an non-empty array!");
}
options.__normalized__ = true;
return options;
}
};
exports3.default = JoyCon2;
module22.exports = JoyCon2;
module22.exports.default = JoyCon2;
});
var require_filesystem = __commonJS3((exports3) => {
"use strict";
Object.defineProperty(exports3, "__esModule", { value: true });
exports3.removeExtension = exports3.fileExistsAsync = exports3.readJsonFromDiskAsync = exports3.readJsonFromDiskSync = exports3.fileExistsSync = void 0;
var fs32 = require("fs");
function fileExistsSync(path4) {
if (!fs32.existsSync(path4)) {
return false;
}
try {
var stats = fs32.statSync(path4);
return stats.isFile();
} catch (err2) {
return false;
}
}
exports3.fileExistsSync = fileExistsSync;
function readJsonFromDiskSync(packageJsonPath) {
if (!fs32.existsSync(packageJsonPath)) {
return void 0;
}
return require(packageJsonPath);
}
exports3.readJsonFromDiskSync = readJsonFromDiskSync;
function readJsonFromDiskAsync(path4, callback) {
fs32.readFile(path4, "utf8", function(err2, result) {
if (err2 || !result) {
return callback();
}
var json = JSON.parse(result);
return callback(void 0, json);
});
}
exports3.readJsonFromDiskAsync = readJsonFromDiskAsync;
function fileExistsAsync(path22, callback2) {
fs32.stat(path22, function(err2, stats) {
if (err2) {
return callback2(void 0, false);
}
callback2(void 0, stats ? stats.isFile() : false);
});
}
exports3.fileExistsAsync = fileExistsAsync;
function removeExtension(path4) {
return path4.substring(0, path4.lastIndexOf(".")) || path4;
}
exports3.removeExtension = removeExtension;
});
var require_mapping_entry = __commonJS3((exports3) => {
"use strict";
Object.defineProperty(exports3, "__esModule", { value: true });
exports3.getAbsoluteMappingEntries = void 0;
var path4 = require("path");
function getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll) {
var sortedKeys = sortByLongestPrefix(Object.keys(paths));
var absolutePaths = [];
for (var _i = 0, sortedKeys_1 = sortedKeys; _i < sortedKeys_1.length; _i++) {
var key = sortedKeys_1[_i];
absolutePaths.push({
pattern: key,
paths: paths[key].map(function(pathToResolve) {
return path4.resolve(absoluteBaseUrl, pathToResolve);
})
});
}
if (!paths["*"] && addMatchAll) {
absolutePaths.push({
pattern: "*",
paths: ["".concat(absoluteBaseUrl.replace(/\/$/, ""), "/*")]
});
}
return absolutePaths;
}
exports3.getAbsoluteMappingEntries = getAbsoluteMappingEntries;
function sortByLongestPrefix(arr) {
return arr.concat().sort(function(a, b) {
return getPrefixLength(b) - getPrefixLength(a);
});
}
function getPrefixLength(pattern) {
var prefixLength = pattern.indexOf("*");
return pattern.substr(0, prefixLength).length;
}
});
var require_try_path = __commonJS3((exports3) => {
"use strict";
Object.defineProperty(exports3, "__esModule", { value: true });
exports3.exhaustiveTypeException = exports3.getStrippedPath = exports3.getPathsToTry = void 0;
var path4 = require("path");
var path_1 = require("path");
var filesystem_1 = require_filesystem();
function getPathsToTry(extensions, absolutePathMappings, requestedModule) {
if (!absolutePathMappings || !requestedModule || requestedModule[0] === ".") {
return void 0;
}
var pathsToTry = [];
for (var _i = 0, absolutePathMappings_1 = absolutePathMappings; _i < absolutePathMappings_1.length; _i++) {
var entry = absolutePathMappings_1[_i];
var starMatch = entry.pattern === requestedModule ? "" : matchStar(entry.pattern, requestedModule);
if (starMatch !== void 0) {
var _loop_1 = function(physicalPathPattern2) {
var physicalPath = physicalPathPattern2.replace("*", starMatch);
pathsToTry.push({ type: "file", path: physicalPath });
pathsToTry.push.apply(pathsToTry, extensions.map(function(e2) {
return { type: "extension", path: physicalPath + e2 };
}));
pathsToTry.push({
type: "package",
path: path4.join(physicalPath, "/package.json")
});
var indexPath = path4.join(physicalPath, "/index");
pathsToTry.push.apply(pathsToTry, extensions.map(function(e2) {
return { type: "index", path: indexPath + e2 };
}));
};
for (var _a = 0, _b = entry.paths; _a < _b.length; _a++) {
var physicalPathPattern = _b[_a];
_loop_1(physicalPathPattern);
}
}
}
return pathsToTry.length === 0 ? void 0 : pathsToTry;
}
exports3.getPathsToTry = getPathsToTry;
function getStrippedPath(tryPath) {
return tryPath.type === "index" ? (0, path_1.dirname)(tryPath.path) : tryPath.type === "file" ? tryPath.path : tryPath.type === "extension" ? (0, filesystem_1.removeExtension)(tryPath.path) : tryPath.type === "package" ? tryPath.path : exhaustiveTypeException(tryPath.type);
}
exports3.getStrippedPath = getStrippedPath;
function exhaustiveTypeException(check2) {
throw new Error("Unknown type ".concat(check2));
}
exports3.exhaustiveTypeException = exhaustiveTypeException;
function matchStar(pattern, search) {
if (search.length < pattern.length) {
return void 0;
}
if (pattern === "*") {
return search;
}
var star2 = pattern.indexOf("*");
if (star2 === -1) {
return void 0;
}
var part1 = pattern.substring(0, star2);
var part2 = pattern.substring(star2 + 1);
if (search.substr(0, star2) !== part1) {
return void 0;
}
if (search.substr(search.length - part2.length) !== part2) {
return void 0;
}
return search.substr(star2, search.length - part2.length);
}
});
var require_match_path_sync = __commonJS3((exports3) => {
"use strict";
Object.defineProperty(exports3, "__esModule", { value: true });
exports3.matchFromAbsolutePaths = exports3.createMatchPath = void 0;
var path4 = require("path");
var Filesystem = require_filesystem();
var MappingEntry = require_mapping_entry();
var TryPath = require_try_path();
function createMatchPath2(absoluteBaseUrl, paths, mainFields, addMatchAll) {
if (mainFields === void 0) {
mainFields = ["main"];
}
if (addMatchAll === void 0) {
addMatchAll = true;
}
var absolutePaths = MappingEntry.getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll);
return function(requestedModule, readJson, fileExists, extensions) {
return matchFromAbsolutePaths(absolutePaths, requestedModule, readJson, fileExists, extensions, mainFields);
};
}
exports3.createMatchPath = createMatchPath2;
function matchFromAbsolutePaths(absolutePathMappings, requestedModule, readJson, fileExists, extensions, mainFields) {
if (readJson === void 0) {
readJson = Filesystem.readJsonFromDiskSync;
}
if (fileExists === void 0) {
fileExists = Filesystem.fileExistsSync;
}
if (extensions === void 0) {
extensions = Object.keys(require.extensions);
}
if (mainFields === void 0) {
mainFields = ["main"];
}
var tryPaths = TryPath.getPathsToTry(extensions, absolutePathMappings, requestedModule);
if (!tryPaths) {
return void 0;
}
return findFirstExistingPath(tryPaths, readJson, fileExists, mainFields);
}
exports3.matchFromAbsolutePaths = matchFromAbsolutePaths;
function findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExists) {
for (var index5 = 0; index5 < mainFields.length; index5++) {
var mainFieldSelector = mainFields[index5];
var candidateMapping = typeof mainFieldSelector === "string" ? packageJson[mainFieldSelector] : mainFieldSelector.reduce(function(obj, key) {
return obj[key];
}, packageJson);
if (candidateMapping && typeof candidateMapping === "string") {
var candidateFilePath = path4.join(path4.dirname(packageJsonPath), candidateMapping);
if (fileExists(candidateFilePath)) {
return candidateFilePath;
}
}
}
return void 0;
}
function findFirstExistingPath(tryPaths, readJson, fileExists, mainFields) {
if (readJson === void 0) {
readJson = Filesystem.readJsonFromDiskSync;
}
if (mainFields === void 0) {
mainFields = ["main"];
}
for (var _i = 0, tryPaths_1 = tryPaths; _i < tryPaths_1.length; _i++) {
var tryPath = tryPaths_1[_i];
if (tryPath.type === "file" || tryPath.type === "extension" || tryPath.type === "index") {
if (fileExists(tryPath.path)) {
return TryPath.getStrippedPath(tryPath);
}
} else if (tryPath.type === "package") {
var packageJson = readJson(tryPath.path);
if (packageJson) {
var mainFieldMappedFile = findFirstExistingMainFieldMappedFile(packageJson, mainFields, tryPath.path, fileExists);
if (mainFieldMappedFile) {
return mainFieldMappedFile;
}
}
} else {
TryPath.exhaustiveTypeException(tryPath.type);
}
}
return void 0;
}
});
var require_match_path_async = __commonJS3((exports3) => {
"use strict";
Object.defineProperty(exports3, "__esModule", { value: true });
exports3.matchFromAbsolutePathsAsync = exports3.createMatchPathAsync = void 0;
var path4 = require("path");
var TryPath = require_try_path();
var MappingEntry = require_mapping_entry();
var Filesystem = require_filesystem();
function createMatchPathAsync(absoluteBaseUrl, paths, mainFields, addMatchAll) {
if (mainFields === void 0) {
mainFields = ["main"];
}
if (addMatchAll === void 0) {
addMatchAll = true;
}
var absolutePaths = MappingEntry.getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll);
return function(requestedModule, readJson, fileExists, extensions, callback) {
return matchFromAbsolutePathsAsync(absolutePaths, requestedModule, readJson, fileExists, extensions, callback, mainFields);
};
}
exports3.createMatchPathAsync = createMatchPathAsync;
function matchFromAbsolutePathsAsync(absolutePathMappings, requestedModule, readJson, fileExists, extensions, callback, mainFields) {
if (readJson === void 0) {
readJson = Filesystem.readJsonFromDiskAsync;
}
if (fileExists === void 0) {
fileExists = Filesystem.fileExistsAsync;
}
if (extensions === void 0) {
extensions = Object.keys(require.extensions);
}
if (mainFields === void 0) {
mainFields = ["main"];
}
var tryPaths = TryPath.getPathsToTry(extensions, absolutePathMappings, requestedModule);
if (!tryPaths) {
return callback();
}
findFirstExistingPath(tryPaths, readJson, fileExists, callback, 0, mainFields);
}
exports3.matchFromAbsolutePathsAsync = matchFromAbsolutePathsAsync;
function findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExistsAsync, doneCallback, index5) {
if (index5 === void 0) {
index5 = 0;
}
if (index5 >= mainFields.length) {
return doneCallback(void 0, void 0);
}
var tryNext = function() {
return findFirstExistingMainFieldMappedFile(packageJson, mainFields, packageJsonPath, fileExistsAsync, doneCallback, index5 + 1);
};
var mainFieldSelector = mainFields[index5];
var mainFieldMapping = typeof mainFieldSelector === "string" ? packageJson[mainFieldSelector] : mainFieldSelector.reduce(function(obj, key) {
return obj[key];
}, packageJson);
if (typeof mainFieldMapping !== "string") {
return tryNext();
}
var mappedFilePath = path4.join(path4.dirname(packageJsonPath), mainFieldMapping);
fileExistsAsync(mappedFilePath, function(err2, exists) {
if (err2) {
return doneCallback(err2);
}
if (exists) {
return doneCallback(void 0, mappedFilePath);
}
return tryNext();
});
}
function findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5, mainFields) {
if (index5 === void 0) {
index5 = 0;
}
if (mainFields === void 0) {
mainFields = ["main"];
}
var tryPath = tryPaths[index5];
if (tryPath.type === "file" || tryPath.type === "extension" || tryPath.type === "index") {
fileExists(tryPath.path, function(err2, exists) {
if (err2) {
return doneCallback(err2);
}
if (exists) {
return doneCallback(void 0, TryPath.getStrippedPath(tryPath));
}
if (index5 === tryPaths.length - 1) {
return doneCallback();
}
return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5 + 1, mainFields);
});
} else if (tryPath.type === "package") {
readJson(tryPath.path, function(err2, packageJson) {
if (err2) {
return doneCallback(err2);
}
if (packageJson) {
return findFirstExistingMainFieldMappedFile(packageJson, mainFields, tryPath.path, fileExists, function(mainFieldErr, mainFieldMappedFile) {
if (mainFieldErr) {
return doneCallback(mainFieldErr);
}
if (mainFieldMappedFile) {
return doneCallback(void 0, mainFieldMappedFile);
}
return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5 + 1, mainFields);
});
}
return findFirstExistingPath(tryPaths, readJson, fileExists, doneCallback, index5 + 1, mainFields);
});
} else {
TryPath.exhaustiveTypeException(tryPath.type);
}
}
});
var require_unicode = __commonJS3((exports3, module22) => {
module22.exports.Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
module22.exports.ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
module22.exports.ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF
Showing 512.00 KB of 2.99 MB. Use Edit/Download for full content.
Directory Contents
Dirs: 1 × Files: 15