"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 __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/colors/lib/styles.js var require_styles = __commonJS({ "node_modules/colors/lib/styles.js"(exports2, module2) { var styles = {}; module2["exports"] = styles; var codes = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], brightRed: [91, 39], brightGreen: [92, 39], brightYellow: [93, 39], brightBlue: [94, 39], brightMagenta: [95, 39], brightCyan: [96, 39], brightWhite: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgGray: [100, 49], bgGrey: [100, 49], bgBrightRed: [101, 49], bgBrightGreen: [102, 49], bgBrightYellow: [103, 49], bgBrightBlue: [104, 49], bgBrightMagenta: [105, 49], bgBrightCyan: [106, 49], bgBrightWhite: [107, 49], // legacy styles for colors pre v1.0.0 blackBG: [40, 49], redBG: [41, 49], greenBG: [42, 49], yellowBG: [43, 49], blueBG: [44, 49], magentaBG: [45, 49], cyanBG: [46, 49], whiteBG: [47, 49] }; Object.keys(codes).forEach(function(key) { var val = codes[key]; var style = styles[key] = []; style.open = "\x1B[" + val[0] + "m"; style.close = "\x1B[" + val[1] + "m"; }); } }); // node_modules/colors/lib/system/has-flag.js var require_has_flag = __commonJS({ "node_modules/colors/lib/system/has-flag.js"(exports2, module2) { "use strict"; module2.exports = function(flag, argv) { argv = argv || process.argv; var terminatorPos = argv.indexOf("--"); var prefix = /^-{1,2}/.test(flag) ? "" : "--"; var pos = argv.indexOf(prefix + flag); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; } }); // node_modules/colors/lib/system/supports-colors.js var require_supports_colors = __commonJS({ "node_modules/colors/lib/system/supports-colors.js"(exports2, module2) { "use strict"; var os = require("os"); var hasFlag = require_has_flag(); var env = process.env; var forceColor = void 0; if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) { forceColor = false; } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { forceColor = true; } if ("FORCE_COLOR" in env) { forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(stream) { if (forceColor === false) { return 0; } if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { return 3; } if (hasFlag("color=256")) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } var min = forceColor ? 1 : 0; if (process.platform === "win32") { var osRelease = os.release().split("."); if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ("CI" in env) { if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) { return 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 ("TERM_PROGRAM" in env) { var version2 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env.TERM_PROGRAM) { case "iTerm.app": return version2 >= 3 ? 3 : 2; case "Hyper": return 3; case "Apple_Terminal": return 2; } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ("COLORTERM" in env) { return 1; } if (env.TERM === "dumb") { return min; } return min; } function getSupportLevel(stream) { var level = supportsColor(stream); return translateLevel(level); } module2.exports = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; } }); // node_modules/colors/lib/custom/trap.js var require_trap = __commonJS({ "node_modules/colors/lib/custom/trap.js"(exports2, module2) { module2["exports"] = function runTheTrap(text, options) { var result = ""; text = text || "Run the trap, drop the bass"; text = text.split(""); var trap = { a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"], b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"], c: ["\xA9", "\u023B", "\u03FE"], d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"], e: [ "\xCB", "\u0115", "\u018E", "\u0258", "\u03A3", "\u03BE", "\u04BC", "\u0A6C" ], f: ["\u04FA"], g: ["\u0262"], h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"], i: ["\u0F0F"], j: ["\u0134"], k: ["\u0138", "\u04A0", "\u04C3", "\u051E"], l: ["\u0139"], m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"], n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"], o: [ "\xD8", "\xF5", "\xF8", "\u01FE", "\u0298", "\u047A", "\u05DD", "\u06DD", "\u0E4F" ], p: ["\u01F7", "\u048E"], q: ["\u09CD"], r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"], s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"], t: ["\u0141", "\u0166", "\u0373"], u: ["\u01B1", "\u054D"], v: ["\u05D8"], w: ["\u0428", "\u0460", "\u047C", "\u0D70"], x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"], y: ["\xA5", "\u04B0", "\u04CB"], z: ["\u01B5", "\u0240"] }; text.forEach(function(c) { c = c.toLowerCase(); var chars = trap[c] || [" "]; var rand = Math.floor(Math.random() * chars.length); if (typeof trap[c] !== "undefined") { result += trap[c][rand]; } else { result += c; } }); return result; }; } }); // node_modules/colors/lib/custom/zalgo.js var require_zalgo = __commonJS({ "node_modules/colors/lib/custom/zalgo.js"(exports2, module2) { module2["exports"] = function zalgo(text, options) { text = text || " he is here "; var soul = { "up": [ "\u030D", "\u030E", "\u0304", "\u0305", "\u033F", "\u0311", "\u0306", "\u0310", "\u0352", "\u0357", "\u0351", "\u0307", "\u0308", "\u030A", "\u0342", "\u0313", "\u0308", "\u034A", "\u034B", "\u034C", "\u0303", "\u0302", "\u030C", "\u0350", "\u0300", "\u0301", "\u030B", "\u030F", "\u0312", "\u0313", "\u0314", "\u033D", "\u0309", "\u0363", "\u0364", "\u0365", "\u0366", "\u0367", "\u0368", "\u0369", "\u036A", "\u036B", "\u036C", "\u036D", "\u036E", "\u036F", "\u033E", "\u035B", "\u0346", "\u031A" ], "down": [ "\u0316", "\u0317", "\u0318", "\u0319", "\u031C", "\u031D", "\u031E", "\u031F", "\u0320", "\u0324", "\u0325", "\u0326", "\u0329", "\u032A", "\u032B", "\u032C", "\u032D", "\u032E", "\u032F", "\u0330", "\u0331", "\u0332", "\u0333", "\u0339", "\u033A", "\u033B", "\u033C", "\u0345", "\u0347", "\u0348", "\u0349", "\u034D", "\u034E", "\u0353", "\u0354", "\u0355", "\u0356", "\u0359", "\u035A", "\u0323" ], "mid": [ "\u0315", "\u031B", "\u0300", "\u0301", "\u0358", "\u0321", "\u0322", "\u0327", "\u0328", "\u0334", "\u0335", "\u0336", "\u035C", "\u035D", "\u035E", "\u035F", "\u0360", "\u0362", "\u0338", "\u0337", "\u0361", " \u0489" ] }; var all = [].concat(soul.up, soul.down, soul.mid); function randomNumber(range) { var r = Math.floor(Math.random() * range); return r; } function isChar(character) { var bool = false; all.filter(function(i) { bool = i === character; }); return bool; } function heComes(text2, options2) { var result = ""; var counts; var l; options2 = options2 || {}; options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true; options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true; options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true; options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi"; text2 = text2.split(""); for (l in text2) { if (isChar(l)) { continue; } result = result + text2[l]; counts = { "up": 0, "down": 0, "mid": 0 }; switch (options2.size) { case "mini": counts.up = randomNumber(8); counts.mid = randomNumber(2); counts.down = randomNumber(8); break; case "maxi": counts.up = randomNumber(16) + 3; counts.mid = randomNumber(4) + 1; counts.down = randomNumber(64) + 3; break; default: counts.up = randomNumber(8) + 1; counts.mid = randomNumber(6) / 2; counts.down = randomNumber(8) + 1; break; } var arr = ["up", "mid", "down"]; for (var d in arr) { var index = arr[d]; for (var i = 0; i <= counts[index]; i++) { if (options2[index]) { result = result + soul[index][randomNumber(soul[index].length)]; } } } } return result; } return heComes(text, options); }; } }); // node_modules/colors/lib/maps/america.js var require_america = __commonJS({ "node_modules/colors/lib/maps/america.js"(exports2, module2) { module2["exports"] = function(colors2) { return function(letter, i, exploded) { if (letter === " ") return letter; switch (i % 3) { case 0: return colors2.red(letter); case 1: return colors2.white(letter); case 2: return colors2.blue(letter); } }; }; } }); // node_modules/colors/lib/maps/zebra.js var require_zebra = __commonJS({ "node_modules/colors/lib/maps/zebra.js"(exports2, module2) { module2["exports"] = function(colors2) { return function(letter, i, exploded) { return i % 2 === 0 ? letter : colors2.inverse(letter); }; }; } }); // node_modules/colors/lib/maps/rainbow.js var require_rainbow = __commonJS({ "node_modules/colors/lib/maps/rainbow.js"(exports2, module2) { module2["exports"] = function(colors2) { var rainbowColors = ["red", "yellow", "green", "blue", "magenta"]; return function(letter, i, exploded) { if (letter === " ") { return letter; } else { return colors2[rainbowColors[i++ % rainbowColors.length]](letter); } }; }; } }); // node_modules/colors/lib/maps/random.js var require_random = __commonJS({ "node_modules/colors/lib/maps/random.js"(exports2, module2) { module2["exports"] = function(colors2) { var available = [ "underline", "inverse", "grey", "yellow", "red", "green", "blue", "white", "cyan", "magenta", "brightYellow", "brightRed", "brightGreen", "brightBlue", "brightWhite", "brightCyan", "brightMagenta" ]; return function(letter, i, exploded) { return letter === " " ? letter : colors2[available[Math.round(Math.random() * (available.length - 2))]](letter); }; }; } }); // node_modules/colors/lib/colors.js var require_colors = __commonJS({ "node_modules/colors/lib/colors.js"(exports2, module2) { var colors2 = {}; module2["exports"] = colors2; colors2.themes = {}; var util2 = require("util"); var ansiStyles = colors2.styles = require_styles(); var defineProps = Object.defineProperties; var newLineRegex = new RegExp(/[\r\n]+/g); colors2.supportsColor = require_supports_colors().supportsColor; if (typeof colors2.enabled === "undefined") { colors2.enabled = colors2.supportsColor() !== false; } colors2.enable = function() { colors2.enabled = true; }; colors2.disable = function() { colors2.enabled = false; }; colors2.stripColors = colors2.strip = function(str) { return ("" + str).replace(/\x1B\[\d+m/g, ""); }; var stylize = colors2.stylize = function stylize2(str, style) { if (!colors2.enabled) { return str + ""; } var styleMap = ansiStyles[style]; if (!styleMap && style in colors2) { return colors2[style](str); } return styleMap.open + str + styleMap.close; }; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function(str) { if (typeof str !== "string") { throw new TypeError("Expected a string"); } return str.replace(matchOperatorsRe, "\\$&"); }; function build(_styles) { var builder = function builder2() { return applyStyle.apply(builder2, arguments); }; builder._styles = _styles; builder.__proto__ = proto; return builder; } var styles = (function() { var ret = {}; ansiStyles.grey = ansiStyles.gray; Object.keys(ansiStyles).forEach(function(key) { ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), "g"); ret[key] = { get: function() { return build(this._styles.concat(key)); } }; }); return ret; })(); var proto = defineProps(function colors3() { }, styles); function applyStyle() { var args = Array.prototype.slice.call(arguments); var str = args.map(function(arg) { if (arg != null && arg.constructor === String) { return arg; } else { return util2.inspect(arg); } }).join(" "); if (!colors2.enabled || !str) { return str; } var newLinesPresent = str.indexOf("\n") != -1; var nestedStyles = this._styles; var i = nestedStyles.length; while (i--) { var code = ansiStyles[nestedStyles[i]]; str = code.open + str.replace(code.closeRe, code.open) + code.close; if (newLinesPresent) { str = str.replace(newLineRegex, function(match) { return code.close + match + code.open; }); } } return str; } colors2.setTheme = function(theme) { if (typeof theme === "string") { console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));"); return; } for (var style in theme) { (function(style2) { colors2[style2] = function(str) { if (typeof theme[style2] === "object") { var out = str; for (var i in theme[style2]) { out = colors2[theme[style2][i]](out); } return out; } return colors2[theme[style2]](str); }; })(style); } }; function init() { var ret = {}; Object.keys(styles).forEach(function(name) { ret[name] = { get: function() { return build([name]); } }; }); return ret; } var sequencer = function sequencer2(map3, str) { var exploded = str.split(""); exploded = exploded.map(map3); return exploded.join(""); }; colors2.trap = require_trap(); colors2.zalgo = require_zalgo(); colors2.maps = {}; colors2.maps.america = require_america()(colors2); colors2.maps.zebra = require_zebra()(colors2); colors2.maps.rainbow = require_rainbow()(colors2); colors2.maps.random = require_random()(colors2); for (map2 in colors2.maps) { (function(map3) { colors2[map3] = function(str) { return sequencer(colors2.maps[map3], str); }; })(map2); } var map2; defineProps(colors2, init()); } }); // node_modules/colors/safe.js var require_safe = __commonJS({ "node_modules/colors/safe.js"(exports2, module2) { var colors2 = require_colors(); module2["exports"] = colors2; } }); // node_modules/ms/index.js var require_ms = __commonJS({ "node_modules/ms/index.js"(exports2, module2) { var s = 1e3; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; module2.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === "string" && val.length > 0) { return parse3(val); } else if (type === "number" && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) ); }; function parse3(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || "ms").toLowerCase(); switch (type) { case "years": case "year": case "yrs": case "yr": case "y": return n * y; case "weeks": case "week": case "w": return n * w; case "days": case "day": case "d": return n * d; case "hours": case "hour": case "hrs": case "hr": case "h": return n * h; case "minutes": case "minute": case "mins": case "min": case "m": return n * m; case "seconds": case "second": case "secs": case "sec": case "s": return n * s; 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 >= h) { return Math.round(ms / h) + "h"; } if (msAbs >= m) { return Math.round(ms / m) + "m"; } if (msAbs >= s) { return Math.round(ms / s) + "s"; } return ms + "ms"; } function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, "day"); } if (msAbs >= h) { return plural(ms, msAbs, h, "hour"); } if (msAbs >= m) { return plural(ms, msAbs, m, "minute"); } if (msAbs >= s) { return plural(ms, msAbs, s, "second"); } return ms + " ms"; } function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); } } }); // node_modules/debug/src/common.js var require_common = __commonJS({ "node_modules/debug/src/common.js"(exports2, module2) { function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require_ms(); createDebug.destroy = destroy; Object.keys(env).forEach((key) => { createDebug[key] = env[key]; }); createDebug.names = []; createDebug.skips = []; createDebug.formatters = {}; function selectColor(namespace) { let hash2 = 0; for (let i = 0; i < namespace.length; i++) { hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); hash2 |= 0; } return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; } createDebug.selectColor = selectColor; function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug2(...args) { if (!debug2.enabled) { return; } const self = debug2; const curr = Number(/* @__PURE__ */ new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== "string") { args.unshift("%O"); } let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { if (match === "%%") { return "%"; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === "function") { const val = args[index]; match = formatter.call(self, val); args.splice(index, 1); index--; } return match; }); createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug2.namespace = namespace; debug2.useColors = createDebug.useColors(); debug2.color = createDebug.selectColor(namespace); debug2.extend = extend2; debug2.destroy = createDebug.destroy; Object.defineProperty(debug2, "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(debug2); } return debug2; } function extend2(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); newDebug.log = this.log; return newDebug; } function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); for (const ns of split) { if (ns[0] === "-") { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { if (template[templateIndex] === "*") { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; } } while (templateIndex < template.length && template[templateIndex] === "*") { templateIndex++; } return templateIndex === template.length; } function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace) ].join(","); createDebug.enable(""); return namespaces; } function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } function destroy() { console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } createDebug.enable(createDebug.load()); return createDebug; } module2.exports = setup; } }); // node_modules/debug/src/browser.js var require_browser = __commonJS({ "node_modules/debug/src/browser.js"(exports2, module2) { exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load; exports2.useColors = useColors; exports2.storage = localstorage(); exports2.destroy = /* @__PURE__ */ (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } }; })(); exports2.colors = [ "#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33" ]; function useColors() { if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { return true; } if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; 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 && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } function formatArgs(args) { args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); if (!this.useColors) { return; } const c = "color: " + this.color; args.splice(1, 0, c, "color: inherit"); let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, (match) => { if (match === "%%") { return; } index++; if (match === "%c") { lastC = index; } }); args.splice(lastC, 0, c); } exports2.log = console.debug || console.log || (() => { }); function save(namespaces) { try { if (namespaces) { exports2.storage.setItem("debug", namespaces); } else { exports2.storage.removeItem("debug"); } } catch (error48) { } } function load() { let r; try { r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); } catch (error48) { } if (!r && typeof process !== "undefined" && "env" in process) { r = process.env.DEBUG; } return r; } function localstorage() { try { return localStorage; } catch (error48) { } } module2.exports = require_common()(exports2); var { formatters } = module2.exports; formatters.j = function(v) { try { return JSON.stringify(v); } catch (error48) { return "[UnexpectedJSONParseError]: " + error48.message; } }; } }); // node_modules/has-flag/index.js var require_has_flag2 = __commonJS({ "node_modules/has-flag/index.js"(exports2, module2) { "use strict"; module2.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf("--"); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; } }); // node_modules/supports-color/index.js var require_supports_color = __commonJS({ "node_modules/supports-color/index.js"(exports2, module2) { "use strict"; var os = require("os"); var tty = require("tty"); var hasFlag = require_has_flag2(); var { env } = process; var flagForceColor; 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; } 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 (haveStream && !streamIsTTY && forceColor === void 0) { return 0; } const min = forceColor || 0; if (env.TERM === "dumb") { return min; } if (process.platform === "win32") { const osRelease = os.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 (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "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 ("TERM_PROGRAM" in env) { const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); switch (env.TERM_PROGRAM) { case "iTerm.app": return version2 >= 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 getSupportLevel(stream, options = {}) { const level = supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options }); return translateLevel(level); } module2.exports = { supportsColor: getSupportLevel, stdout: getSupportLevel({ isTTY: tty.isatty(1) }), stderr: getSupportLevel({ isTTY: tty.isatty(2) }) }; } }); // node_modules/debug/src/node.js var require_node = __commonJS({ "node_modules/debug/src/node.js"(exports2, module2) { var tty = require("tty"); var util2 = require("util"); exports2.init = init; exports2.log = log; exports2.formatArgs = formatArgs; exports2.save = save; exports2.load = load; exports2.useColors = useColors; exports2.destroy = util2.deprecate( () => { }, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." ); exports2.colors = [6, 2, 3, 4, 5, 1]; try { const supportsColor = require_supports_color(); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports2.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error48) { } exports2.inspectOpts = Object.keys(process.env).filter((key) => { return /^debug_/i.test(key); }).reduce((obj, key) => { const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === "null") { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); function useColors() { return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); } function formatArgs(args) { const { namespace: name, useColors: useColors2 } = this; if (useColors2) { const c = this.color; const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); const prefix = ` ${colorCode};1m${name} \x1B[0m`; args[0] = prefix + args[0].split("\n").join("\n" + prefix); args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); } else { args[0] = getDate() + name + " " + args[0]; } } function getDate() { if (exports2.inspectOpts.hideDate) { return ""; } return (/* @__PURE__ */ new Date()).toISOString() + " "; } function log(...args) { return process.stderr.write(util2.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); } function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { delete process.env.DEBUG; } } function load() { return process.env.DEBUG; } function init(debug2) { debug2.inspectOpts = {}; const keys = Object.keys(exports2.inspectOpts); for (let i = 0; i < keys.length; i++) { debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; } } module2.exports = require_common()(exports2); var { formatters } = module2.exports; formatters.o = function(v) { this.inspectOpts.colors = this.useColors; return util2.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); }; formatters.O = function(v) { this.inspectOpts.colors = this.useColors; return util2.inspect(v, this.inspectOpts); }; } }); // node_modules/debug/src/index.js var require_src = __commonJS({ "node_modules/debug/src/index.js"(exports2, module2) { if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { module2.exports = require_browser(); } else { module2.exports = require_node(); } } }); // node_modules/ini/lib/ini.js var require_ini = __commonJS({ "node_modules/ini/lib/ini.js"(exports2, module2) { var { hasOwnProperty } = Object.prototype; var encode3 = (obj, opt = {}) => { if (typeof opt === "string") { opt = { section: opt }; } opt.align = opt.align === true; opt.newline = opt.newline === true; opt.sort = opt.sort === true; opt.whitespace = opt.whitespace === true || opt.align === true; opt.platform = opt.platform || typeof process !== "undefined" && process.platform; opt.bracketedArray = opt.bracketedArray !== false; const eol = opt.platform === "win32" ? "\r\n" : "\n"; const separator = opt.whitespace ? " = " : "="; const children = []; const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj); let padToChars = 0; if (opt.align) { padToChars = safe( keys.filter((k) => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== "object").map((k) => Array.isArray(obj[k]) ? `${k}[]` : k).concat([""]).reduce((a, b) => safe(a).length >= safe(b).length ? a : b) ).length; } let out = ""; const arraySuffix = opt.bracketedArray ? "[]" : ""; for (const k of keys) { const val = obj[k]; if (val && Array.isArray(val)) { for (const item of val) { out += safe(`${k}${arraySuffix}`).padEnd(padToChars, " ") + separator + safe(item) + eol; } } else if (val && typeof val === "object") { children.push(k); } else { out += safe(k).padEnd(padToChars, " ") + separator + safe(val) + eol; } } if (opt.section && out.length) { out = "[" + safe(opt.section) + "]" + (opt.newline ? eol + eol : eol) + out; } for (const k of children) { const nk = splitSections(k, ".").join("\\."); const section = (opt.section ? opt.section + "." : "") + nk; const child = encode3(obj[k], { ...opt, section }); if (out.length && child.length) { out += eol; } out += child; } return out; }; function splitSections(str, separator) { var lastMatchIndex = 0; var lastSeparatorIndex = 0; var nextIndex = 0; var sections = []; do { nextIndex = str.indexOf(separator, lastMatchIndex); if (nextIndex !== -1) { lastMatchIndex = nextIndex + separator.length; if (nextIndex > 0 && str[nextIndex - 1] === "\\") { continue; } sections.push(str.slice(lastSeparatorIndex, nextIndex)); lastSeparatorIndex = nextIndex + separator.length; } } while (nextIndex !== -1); sections.push(str.slice(lastSeparatorIndex)); return sections; } var decode3 = (str, opt = {}) => { opt.bracketedArray = opt.bracketedArray !== false; const out = /* @__PURE__ */ Object.create(null); let p = out; let section = null; const re = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i; const lines = str.split(/[\r\n]+/g); const duplicates = {}; for (const line of lines) { if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) { continue; } const match = line.match(re); if (!match) { continue; } if (match[1] !== void 0) { section = unsafe(match[1]); if (section === "__proto__") { p = /* @__PURE__ */ Object.create(null); continue; } p = out[section] = out[section] || /* @__PURE__ */ Object.create(null); continue; } const keyRaw = unsafe(match[2]); let isArray; if (opt.bracketedArray) { isArray = keyRaw.length > 2 && keyRaw.slice(-2) === "[]"; } else { duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1; isArray = duplicates[keyRaw] > 1; } const key = isArray && keyRaw.endsWith("[]") ? keyRaw.slice(0, -2) : keyRaw; if (key === "__proto__") { continue; } const valueRaw = match[3] ? unsafe(match[4]) : true; const value = valueRaw === "true" || valueRaw === "false" || valueRaw === "null" ? JSON.parse(valueRaw) : valueRaw; if (isArray) { if (!hasOwnProperty.call(p, key)) { p[key] = []; } else if (!Array.isArray(p[key])) { p[key] = [p[key]]; } } if (Array.isArray(p[key])) { p[key].push(value); } else { p[key] = value; } } const remove = []; for (const k of Object.keys(out)) { if (!hasOwnProperty.call(out, k) || typeof out[k] !== "object" || Array.isArray(out[k])) { continue; } const parts = splitSections(k, "."); p = out; const l = parts.pop(); const nl = l.replace(/\\\./g, "."); for (const part of parts) { if (part === "__proto__") { continue; } if (!hasOwnProperty.call(p, part) || typeof p[part] !== "object") { p[part] = /* @__PURE__ */ Object.create(null); } p = p[part]; } if (p === out && nl === l) { continue; } p[nl] = out[k]; remove.push(k); } for (const del of remove) { delete out[del]; } return out; }; var isQuoted = (val) => { return val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'"); }; var safe = (val) => { if (typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim()) { return JSON.stringify(val); } return val.split(";").join("\\;").split("#").join("\\#"); }; var unsafe = (val) => { val = (val || "").trim(); if (isQuoted(val)) { if (val.charAt(0) === "'") { val = val.slice(1, -1); } try { val = JSON.parse(val); } catch { } } else { let esc2 = false; let unesc = ""; for (let i = 0, l = val.length; i < l; i++) { const c = val.charAt(i); if (esc2) { if ("\\;#".indexOf(c) !== -1) { unesc += c; } else { unesc += "\\" + c; } esc2 = false; } else if (";#".indexOf(c) !== -1) { break; } else if (c === "\\") { esc2 = true; } else { unesc += c; } } if (esc2) { unesc += "\\"; } return unesc.trim(); } return val; }; module2.exports = { parse: decode3, decode: decode3, stringify: encode3, encode: encode3, safe, unsafe }; } }); // node_modules/dotenv/package.json var require_package = __commonJS({ "node_modules/dotenv/package.json"(exports2, module2) { module2.exports = { name: "dotenv", version: "16.6.1", description: "Loads environment variables from .env file", main: "lib/main.js", types: "lib/main.d.ts", exports: { ".": { types: "./lib/main.d.ts", require: "./lib/main.js", default: "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }, scripts: { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", pretest: "npm run lint && npm run dts-check", test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000", "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov", prerelease: "npm test", release: "standard-version" }, repository: { type: "git", url: "git://github.com/motdotla/dotenv.git" }, homepage: "https://github.com/motdotla/dotenv#readme", funding: "https://dotenvx.com", keywords: [ "dotenv", "env", ".env", "environment", "variables", "config", "settings" ], readmeFilename: "README.md", license: "BSD-2-Clause", devDependencies: { "@types/node": "^18.11.3", decache: "^4.6.2", sinon: "^14.0.1", standard: "^17.0.0", "standard-version": "^9.5.0", tap: "^19.2.0", typescript: "^4.8.4" }, engines: { node: ">=12" }, browser: { fs: false } }; } }); // node_modules/dotenv/lib/main.js var require_main = __commonJS({ "node_modules/dotenv/lib/main.js"(exports2, module2) { var fs = require("fs"); var path = require("path"); var os = require("os"); var crypto4 = require("crypto"); var packageJson = require_package(); var version2 = packageJson.version; var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; function parse3(src) { const obj = {}; let lines = src.toString(); lines = lines.replace(/\r\n?/mg, "\n"); let match; while ((match = LINE.exec(lines)) != null) { const key = match[1]; let value = match[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) { options = options || {}; const vaultPath = _vaultPath(options); options.path = vaultPath; const result = DotenvModule.configDotenv(options); if (!result.parsed) { const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); err.code = "MISSING_DATA"; throw err; } const keys = _dotenvKey(options).split(","); const length = keys.length; let decrypted; for (let i = 0; i < length; i++) { try { const key = keys[i].trim(); const attrs = _instructions(result, key); decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); break; } catch (error48) { if (i + 1 >= length) { throw error48; } } } return DotenvModule.parse(decrypted); } function _warn(message) { console.log(`[dotenv@${version2}][WARN] ${message}`); } function _debug(message) { console.log(`[dotenv@${version2}][DEBUG] ${message}`); } function _log(message) { console.log(`[dotenv@${version2}] ${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 (error48) { if (error48.code === "ERR_INVALID_URL") { const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development"); err.code = "INVALID_DOTENV_KEY"; throw err; } throw error48; } const key = uri.password; if (!key) { const err = new Error("INVALID_DOTENV_KEY: Missing key part"); err.code = "INVALID_DOTENV_KEY"; throw err; } const environment = uri.searchParams.get("environment"); if (!environment) { const err = new Error("INVALID_DOTENV_KEY: Missing environment part"); err.code = "INVALID_DOTENV_KEY"; throw err; } const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; const ciphertext = result.parsed[environmentKey]; if (!ciphertext) { const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); err.code = "NOT_FOUND_DOTENV_ENVIRONMENT"; throw err; } 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 (fs.existsSync(filepath)) { possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`; } } } else { possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`; } } else { possibleVaultPath = path.resolve(process.cwd(), ".env.vault"); } if (fs.existsSync(possibleVaultPath)) { return possibleVaultPath; } return null; } function _resolveHome(envPath) { return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath; } function _configVault(options) { const debug2 = Boolean(options && options.debug); const quiet = options && "quiet" in options ? options.quiet : true; if (debug2 || !quiet) { _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 = path.resolve(process.cwd(), ".env"); let encoding = "utf8"; const debug2 = Boolean(options && options.debug); const quiet = options && "quiet" in options ? options.quiet : true; if (options && options.encoding) { encoding = options.encoding; } else { if (debug2) { _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 path2 of optionPaths) { try { const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding })); DotenvModule.populate(parsedAll, parsed, options); } catch (e) { if (debug2) { _debug(`Failed to load ${path2} ${e.message}`); } lastError = e; } } let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsedAll, options); if (debug2 || !quiet) { const keysCount = Object.keys(parsedAll).length; const shortPaths = []; for (const filePath of optionPaths) { try { const relative = path.relative(process.cwd(), filePath); shortPaths.push(relative); } catch (e) { if (debug2) { _debug(`Failed to load ${filePath} ${e.message}`); } lastError = e; } } _log(`injecting env (${keysCount}) from ${shortPaths.join(",")}`); } if (lastError) { return { parsed: parsedAll, error: lastError }; } else { return { parsed: parsedAll }; } } function config2(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 = crypto4.createDecipheriv("aes-256-gcm", key, nonce); aesgcm.setAuthTag(authTag); return `${aesgcm.update(ciphertext)}${aesgcm.final()}`; } catch (error48) { const isRange = error48 instanceof RangeError; const invalidKeyLength = error48.message === "Invalid key length"; const decryptionFailed = error48.message === "Unsupported state or unable to authenticate data"; if (isRange || invalidKeyLength) { const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)"); err.code = "INVALID_DOTENV_KEY"; throw err; } else if (decryptionFailed) { const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY"); err.code = "DECRYPTION_FAILED"; throw err; } else { throw error48; } } } function populate(processEnv, parsed, options = {}) { const debug2 = Boolean(options && options.debug); const override = Boolean(options && options.override); if (typeof parsed !== "object") { const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate"); err.code = "OBJECT_REQUIRED"; throw err; } for (const key of Object.keys(parsed)) { if (Object.prototype.hasOwnProperty.call(processEnv, key)) { if (override === true) { processEnv[key] = parsed[key]; } if (debug2) { 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: config2, decrypt, parse: parse3, 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/agent-base/dist/helpers.js var require_helpers = __commonJS({ "node_modules/agent-base/dist/helpers.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.req = exports2.json = exports2.toBuffer = void 0; var http = __importStar(require("http")); var https = __importStar(require("https")); async function toBuffer(stream) { let length = 0; const chunks = []; for await (const chunk of stream) { length += chunk.length; chunks.push(chunk); } return Buffer.concat(chunks, length); } exports2.toBuffer = toBuffer; async function json2(stream) { const buf = await toBuffer(stream); const str = buf.toString("utf8"); try { return JSON.parse(str); } catch (_err) { const err = _err; err.message += ` (input: ${str})`; throw err; } } exports2.json = json2; function req(url2, opts = {}) { const href = typeof url2 === "string" ? url2 : url2.href; const req2 = (href.startsWith("https:") ? https : http).request(url2, opts); const promise2 = new Promise((resolve, reject) => { req2.once("response", resolve).once("error", reject).end(); }); req2.then = promise2.then.bind(promise2); return req2; } exports2.req = req; } }); // node_modules/agent-base/dist/index.js var require_dist = __commonJS({ "node_modules/agent-base/dist/index.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Agent = void 0; var net = __importStar(require("net")); var http = __importStar(require("http")); var https_1 = require("https"); __exportStar(require_helpers(), exports2); var INTERNAL = Symbol("AgentBaseInternalState"); var Agent = class extends http.Agent { constructor(opts) { super(opts); this[INTERNAL] = {}; } /** * Determine whether this is an `http` or `https` request. */ isSecureEndpoint(options) { if (options) { if (typeof options.secureEndpoint === "boolean") { return options.secureEndpoint; } if (typeof options.protocol === "string") { return options.protocol === "https:"; } } const { stack } = new Error(); if (typeof stack !== "string") return false; return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); } // In order to support async signatures in `connect()` and Node's native // connection pooling in `http.Agent`, the array of sockets for each origin // has to be updated synchronously. This is so the length of the array is // accurate when `addRequest()` is next called. We achieve this by creating a // fake socket and adding it to `sockets[origin]` and incrementing // `totalSocketCount`. incrementSockets(name) { if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { return null; } if (!this.sockets[name]) { this.sockets[name] = []; } const fakeSocket = new net.Socket({ writable: false }); this.sockets[name].push(fakeSocket); this.totalSocketCount++; return fakeSocket; } decrementSockets(name, socket) { if (!this.sockets[name] || socket === null) { return; } const sockets = this.sockets[name]; const index = sockets.indexOf(socket); if (index !== -1) { sockets.splice(index, 1); this.totalSocketCount--; if (sockets.length === 0) { delete this.sockets[name]; } } } // In order to properly update the socket pool, we need to call `getName()` on // the core `https.Agent` if it is a secureEndpoint. getName(options) { const secureEndpoint = this.isSecureEndpoint(options); if (secureEndpoint) { return https_1.Agent.prototype.getName.call(this, options); } return super.getName(options); } createSocket(req, options, cb) { const connectOpts = { ...options, secureEndpoint: this.isSecureEndpoint(options) }; const name = this.getName(connectOpts); const fakeSocket = this.incrementSockets(name); Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { this.decrementSockets(name, fakeSocket); if (socket instanceof http.Agent) { try { return socket.addRequest(req, connectOpts); } catch (err) { return cb(err); } } this[INTERNAL].currentSocket = socket; super.createSocket(req, options, cb); }, (err) => { this.decrementSockets(name, fakeSocket); cb(err); }); } createConnection() { const socket = this[INTERNAL].currentSocket; this[INTERNAL].currentSocket = void 0; if (!socket) { throw new Error("No socket was returned in the `connect()` function"); } return socket; } get defaultPort() { return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); } set defaultPort(v) { if (this[INTERNAL]) { this[INTERNAL].defaultPort = v; } } get protocol() { return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); } set protocol(v) { if (this[INTERNAL]) { this[INTERNAL].protocol = v; } } }; exports2.Agent = Agent; } }); // node_modules/https-proxy-agent/dist/parse-proxy-response.js var require_parse_proxy_response = __commonJS({ "node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { "use strict"; var __importDefault = exports2 && exports2.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.parseProxyResponse = void 0; var debug_1 = __importDefault(require_src()); var debug2 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); function parseProxyResponse(socket) { return new Promise((resolve, reject) => { let buffersLength = 0; const buffers = []; function read() { const b = socket.read(); if (b) ondata(b); else socket.once("readable", read); } function cleanup() { socket.removeListener("end", onend); socket.removeListener("error", onerror); socket.removeListener("readable", read); } function onend() { cleanup(); debug2("onend"); reject(new Error("Proxy connection ended before receiving CONNECT response")); } function onerror(err) { cleanup(); debug2("onerror %o", err); reject(err); } function ondata(b) { buffers.push(b); buffersLength += b.length; const buffered = Buffer.concat(buffers, buffersLength); const endOfHeaders = buffered.indexOf("\r\n\r\n"); if (endOfHeaders === -1) { debug2("have not received end of HTTP headers yet..."); read(); return; } const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); const firstLine = headerParts.shift(); if (!firstLine) { socket.destroy(); return reject(new Error("No header received from proxy CONNECT response")); } const firstLineParts = firstLine.split(" "); const statusCode = +firstLineParts[1]; const statusText = firstLineParts.slice(2).join(" "); const headers = {}; for (const header of headerParts) { if (!header) continue; const firstColon = header.indexOf(":"); if (firstColon === -1) { socket.destroy(); return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); } const key = header.slice(0, firstColon).toLowerCase(); const value = header.slice(firstColon + 1).trimStart(); const current = headers[key]; if (typeof current === "string") { headers[key] = [current, value]; } else if (Array.isArray(current)) { current.push(value); } else { headers[key] = value; } } debug2("got proxy server response: %o %o", firstLine, headers); cleanup(); resolve({ connect: { statusCode, statusText, headers }, buffered }); } socket.on("error", onerror); socket.on("end", onend); read(); }); } exports2.parseProxyResponse = parseProxyResponse; } }); // node_modules/https-proxy-agent/dist/index.js var require_dist2 = __commonJS({ "node_modules/https-proxy-agent/dist/index.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; var __importDefault = exports2 && exports2.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.HttpsProxyAgent = void 0; var net = __importStar(require("net")); var tls = __importStar(require("tls")); var assert_1 = __importDefault(require("assert")); var debug_1 = __importDefault(require_src()); var agent_base_1 = require_dist(); var url_1 = require("url"); var parse_proxy_response_1 = require_parse_proxy_response(); var debug2 = (0, debug_1.default)("https-proxy-agent"); var setServernameFromNonIpHost = (options) => { if (options.servername === void 0 && options.host && !net.isIP(options.host)) { return { ...options, servername: options.host }; } return options; }; var HttpsProxyAgent2 = class extends agent_base_1.Agent { constructor(proxy, opts) { super(opts); this.options = { path: void 0 }; this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; this.proxyHeaders = opts?.headers ?? {}; debug2("Creating new HttpsProxyAgent instance: %o", this.proxy.href); const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; this.connectOpts = { // Attempt to negotiate http/1.1 for proxy servers that support http/2 ALPNProtocols: ["http/1.1"], ...opts ? omit2(opts, "headers") : null, host, port }; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. */ async connect(req, opts) { const { proxy } = this; if (!opts.host) { throw new TypeError('No "host" provided'); } let socket; if (proxy.protocol === "https:") { debug2("Creating `tls.Socket`: %o", this.connectOpts); socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); } else { debug2("Creating `net.Socket`: %o", this.connectOpts); socket = net.connect(this.connectOpts); } const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r `; if (proxy.username || proxy.password) { const auth2 = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth2).toString("base64")}`; } headers.Host = `${host}:${opts.port}`; if (!headers["Proxy-Connection"]) { headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; } for (const name of Object.keys(headers)) { payload += `${name}: ${headers[name]}\r `; } const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); socket.write(`${payload}\r `); const { connect, buffered } = await proxyResponsePromise; req.emit("proxyConnect", connect); this.emit("proxyConnect", connect, req); if (connect.statusCode === 200) { req.once("socket", resume); if (opts.secureEndpoint) { debug2("Upgrading socket connection to TLS"); return tls.connect({ ...omit2(setServernameFromNonIpHost(opts), "host", "path", "port"), socket }); } return socket; } socket.destroy(); const fakeSocket = new net.Socket({ writable: false }); fakeSocket.readable = true; req.once("socket", (s) => { debug2("Replaying proxy buffer for failed request"); (0, assert_1.default)(s.listenerCount("data") > 0); s.push(buffered); s.push(null); }); return fakeSocket; } }; HttpsProxyAgent2.protocols = ["http", "https"]; exports2.HttpsProxyAgent = HttpsProxyAgent2; function resume(socket) { socket.resume(); } function omit2(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } } }); // node_modules/jpeg-js/lib/encoder.js var require_encoder = __commonJS({ "node_modules/jpeg-js/lib/encoder.js"(exports2, module2) { var btoa2 = btoa2 || function(buf) { return Buffer.from(buf).toString("base64"); }; function JPEGEncoder(quality) { var self = this; var fround = Math.round; var ffloor = Math.floor; var YTable = new Array(64); var UVTable = new Array(64); var fdtbl_Y = new Array(64); var fdtbl_UV = new Array(64); var YDC_HT; var UVDC_HT; var YAC_HT; var UVAC_HT; var bitcode = new Array(65535); var category = new Array(65535); var outputfDCTQuant = new Array(64); var DU = new Array(64); var byteout = []; var bytenew = 0; var bytepos = 7; var YDU = new Array(64); var UDU = new Array(64); var VDU = new Array(64); var clt = new Array(256); var RGB_YUV_TABLE = new Array(2048); var currentQuality; var ZigZag = [ 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 ]; var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125]; var std_ac_luminance_values = [ 1, 2, 3, 0, 4, 17, 5, 18, 33, 49, 65, 6, 19, 81, 97, 7, 34, 113, 20, 50, 129, 145, 161, 8, 35, 66, 177, 193, 21, 82, 209, 240, 36, 51, 98, 114, 130, 9, 10, 22, 23, 24, 25, 26, 37, 38, 39, 40, 41, 42, 52, 53, 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, 131, 132, 133, 134, 135, 136, 137, 138, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163, 164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181, 182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199, 200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217, 218, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250 ]; var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119]; var std_ac_chrominance_values = [ 0, 1, 2, 3, 17, 4, 5, 33, 49, 6, 18, 65, 81, 7, 97, 113, 19, 34, 50, 129, 8, 20, 66, 145, 161, 177, 193, 9, 35, 51, 82, 240, 21, 98, 114, 209, 10, 22, 36, 52, 225, 37, 241, 23, 24, 25, 26, 38, 39, 40, 41, 42, 53, 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, 130, 131, 132, 133, 134, 135, 136, 137, 138, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163, 164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181, 182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199, 200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217, 218, 226, 227, 228, 229, 230, 231, 232, 233, 234, 242, 243, 244, 245, 246, 247, 248, 249, 250 ]; function initQuantTables(sf) { var YQT = [ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 ]; for (var i = 0; i < 64; i++) { var t = ffloor((YQT[i] * sf + 50) / 100); if (t < 1) { t = 1; } else if (t > 255) { t = 255; } YTable[ZigZag[i]] = t; } var UVQT = [ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 ]; for (var j = 0; j < 64; j++) { var u = ffloor((UVQT[j] * sf + 50) / 100); if (u < 1) { u = 1; } else if (u > 255) { u = 255; } UVTable[ZigZag[j]] = u; } var aasf = [ 1, 1.387039845, 1.306562965, 1.175875602, 1, 0.785694958, 0.5411961, 0.275899379 ]; var k = 0; for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { fdtbl_Y[k] = 1 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8); fdtbl_UV[k] = 1 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8); k++; } } } function computeHuffmanTbl(nrcodes, std_table) { var codevalue = 0; var pos_in_table = 0; var HT = new Array(); for (var k = 1; k <= 16; k++) { for (var j = 1; j <= nrcodes[k]; j++) { HT[std_table[pos_in_table]] = []; HT[std_table[pos_in_table]][0] = codevalue; HT[std_table[pos_in_table]][1] = k; pos_in_table++; codevalue++; } codevalue *= 2; } return HT; } function initHuffmanTbl() { YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values); UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values); YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values); UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values); } function initCategoryNumber() { var nrlower = 1; var nrupper = 2; for (var cat = 1; cat <= 15; cat++) { for (var nr = nrlower; nr < nrupper; nr++) { category[32767 + nr] = cat; bitcode[32767 + nr] = []; bitcode[32767 + nr][1] = cat; bitcode[32767 + nr][0] = nr; } for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) { category[32767 + nrneg] = cat; bitcode[32767 + nrneg] = []; bitcode[32767 + nrneg][1] = cat; bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg; } nrlower <<= 1; nrupper <<= 1; } } function initRGBYUVTable() { for (var i = 0; i < 256; i++) { RGB_YUV_TABLE[i] = 19595 * i; RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i; RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 32768; RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i; RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i; RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 8421375; RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i; RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i; } } function writeBits(bs) { var value = bs[0]; var posval = bs[1] - 1; while (posval >= 0) { if (value & 1 << posval) { bytenew |= 1 << bytepos; } posval--; bytepos--; if (bytepos < 0) { if (bytenew == 255) { writeByte(255); writeByte(0); } else { writeByte(bytenew); } bytepos = 7; bytenew = 0; } } } function writeByte(value) { byteout.push(value); } function writeWord(value) { writeByte(value >> 8 & 255); writeByte(value & 255); } function fDCTQuant(data, fdtbl) { var d0, d1, d2, d3, d4, d5, d6, d7; var dataOff = 0; var i; var I8 = 8; var I64 = 64; for (i = 0; i < I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 1]; d2 = data[dataOff + 2]; d3 = data[dataOff + 3]; d4 = data[dataOff + 4]; d5 = data[dataOff + 5]; d6 = data[dataOff + 6]; d7 = data[dataOff + 7]; var tmp0 = d0 + d7; var tmp7 = d0 - d7; var tmp1 = d1 + d6; var tmp6 = d1 - d6; var tmp2 = d2 + d5; var tmp5 = d2 - d5; var tmp3 = d3 + d4; var tmp4 = d3 - d4; var tmp10 = tmp0 + tmp3; var tmp13 = tmp0 - tmp3; var tmp11 = tmp1 + tmp2; var tmp12 = tmp1 - tmp2; data[dataOff] = tmp10 + tmp11; data[dataOff + 4] = tmp10 - tmp11; var z1 = (tmp12 + tmp13) * 0.707106781; data[dataOff + 2] = tmp13 + z1; data[dataOff + 6] = tmp13 - z1; tmp10 = tmp4 + tmp5; tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; var z5 = (tmp10 - tmp12) * 0.382683433; var z2 = 0.5411961 * tmp10 + z5; var z4 = 1.306562965 * tmp12 + z5; var z3 = tmp11 * 0.707106781; var z11 = tmp7 + z3; var z13 = tmp7 - z3; data[dataOff + 5] = z13 + z2; data[dataOff + 3] = z13 - z2; data[dataOff + 1] = z11 + z4; data[dataOff + 7] = z11 - z4; dataOff += 8; } dataOff = 0; for (i = 0; i < I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 8]; d2 = data[dataOff + 16]; d3 = data[dataOff + 24]; d4 = data[dataOff + 32]; d5 = data[dataOff + 40]; d6 = data[dataOff + 48]; d7 = data[dataOff + 56]; var tmp0p2 = d0 + d7; var tmp7p2 = d0 - d7; var tmp1p2 = d1 + d6; var tmp6p2 = d1 - d6; var tmp2p2 = d2 + d5; var tmp5p2 = d2 - d5; var tmp3p2 = d3 + d4; var tmp4p2 = d3 - d4; var tmp10p2 = tmp0p2 + tmp3p2; var tmp13p2 = tmp0p2 - tmp3p2; var tmp11p2 = tmp1p2 + tmp2p2; var tmp12p2 = tmp1p2 - tmp2p2; data[dataOff] = tmp10p2 + tmp11p2; data[dataOff + 32] = tmp10p2 - tmp11p2; var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; data[dataOff + 16] = tmp13p2 + z1p2; data[dataOff + 48] = tmp13p2 - z1p2; tmp10p2 = tmp4p2 + tmp5p2; tmp11p2 = tmp5p2 + tmp6p2; tmp12p2 = tmp6p2 + tmp7p2; var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; var z2p2 = 0.5411961 * tmp10p2 + z5p2; var z4p2 = 1.306562965 * tmp12p2 + z5p2; var z3p2 = tmp11p2 * 0.707106781; var z11p2 = tmp7p2 + z3p2; var z13p2 = tmp7p2 - z3p2; data[dataOff + 40] = z13p2 + z2p2; data[dataOff + 24] = z13p2 - z2p2; data[dataOff + 8] = z11p2 + z4p2; data[dataOff + 56] = z11p2 - z4p2; dataOff++; } var fDCTQuant2; for (i = 0; i < I64; ++i) { fDCTQuant2 = data[i] * fdtbl[i]; outputfDCTQuant[i] = fDCTQuant2 > 0 ? fDCTQuant2 + 0.5 | 0 : fDCTQuant2 - 0.5 | 0; } return outputfDCTQuant; } function writeAPP0() { writeWord(65504); writeWord(16); writeByte(74); writeByte(70); writeByte(73); writeByte(70); writeByte(0); writeByte(1); writeByte(1); writeByte(0); writeWord(1); writeWord(1); writeByte(0); writeByte(0); } function writeAPP1(exifBuffer) { if (!exifBuffer) return; writeWord(65505); if (exifBuffer[0] === 69 && exifBuffer[1] === 120 && exifBuffer[2] === 105 && exifBuffer[3] === 102) { writeWord(exifBuffer.length + 2); } else { writeWord(exifBuffer.length + 5 + 2); writeByte(69); writeByte(120); writeByte(105); writeByte(102); writeByte(0); } for (var i = 0; i < exifBuffer.length; i++) { writeByte(exifBuffer[i]); } } function writeSOF0(width, height) { writeWord(65472); writeWord(17); writeByte(8); writeWord(height); writeWord(width); writeByte(3); writeByte(1); writeByte(17); writeByte(0); writeByte(2); writeByte(17); writeByte(1); writeByte(3); writeByte(17); writeByte(1); } function writeDQT() { writeWord(65499); writeWord(132); writeByte(0); for (var i = 0; i < 64; i++) { writeByte(YTable[i]); } writeByte(1); for (var j = 0; j < 64; j++) { writeByte(UVTable[j]); } } function writeDHT() { writeWord(65476); writeWord(418); writeByte(0); for (var i = 0; i < 16; i++) { writeByte(std_dc_luminance_nrcodes[i + 1]); } for (var j = 0; j <= 11; j++) { writeByte(std_dc_luminance_values[j]); } writeByte(16); for (var k = 0; k < 16; k++) { writeByte(std_ac_luminance_nrcodes[k + 1]); } for (var l = 0; l <= 161; l++) { writeByte(std_ac_luminance_values[l]); } writeByte(1); for (var m = 0; m < 16; m++) { writeByte(std_dc_chrominance_nrcodes[m + 1]); } for (var n = 0; n <= 11; n++) { writeByte(std_dc_chrominance_values[n]); } writeByte(17); for (var o = 0; o < 16; o++) { writeByte(std_ac_chrominance_nrcodes[o + 1]); } for (var p = 0; p <= 161; p++) { writeByte(std_ac_chrominance_values[p]); } } function writeCOM(comments) { if (typeof comments === "undefined" || comments.constructor !== Array) return; comments.forEach((e) => { if (typeof e !== "string") return; writeWord(65534); var l = e.length; writeWord(l + 2); var i; for (i = 0; i < l; i++) writeByte(e.charCodeAt(i)); }); } function writeSOS() { writeWord(65498); writeWord(12); writeByte(3); writeByte(1); writeByte(0); writeByte(2); writeByte(17); writeByte(3); writeByte(17); writeByte(0); writeByte(63); writeByte(0); } function processDU(CDU, fdtbl, DC, HTDC, HTAC) { var EOB = HTAC[0]; var M16zeroes = HTAC[240]; var pos; var I16 = 16; var I63 = 63; var I64 = 64; var DU_DCT = fDCTQuant(CDU, fdtbl); for (var j = 0; j < I64; ++j) { DU[ZigZag[j]] = DU_DCT[j]; } var Diff2 = DU[0] - DC; DC = DU[0]; if (Diff2 == 0) { writeBits(HTDC[0]); } else { pos = 32767 + Diff2; writeBits(HTDC[category[pos]]); writeBits(bitcode[pos]); } var end0pos = 63; for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) { } ; if (end0pos == 0) { writeBits(EOB); return DC; } var i = 1; var lng; while (i <= end0pos) { var startpos = i; for (; DU[i] == 0 && i <= end0pos; ++i) { } var nrzeroes = i - startpos; if (nrzeroes >= I16) { lng = nrzeroes >> 4; for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) writeBits(M16zeroes); nrzeroes = nrzeroes & 15; } pos = 32767 + DU[i]; writeBits(HTAC[(nrzeroes << 4) + category[pos]]); writeBits(bitcode[pos]); i++; } if (end0pos != I63) { writeBits(EOB); } return DC; } function initCharLookupTable() { var sfcc = String.fromCharCode; for (var i = 0; i < 256; i++) { clt[i] = sfcc(i); } } this.encode = function(image, quality2) { var time_start = (/* @__PURE__ */ new Date()).getTime(); if (quality2) setQuality(quality2); byteout = new Array(); bytenew = 0; bytepos = 7; writeWord(65496); writeAPP0(); writeCOM(image.comments); writeAPP1(image.exifBuffer); writeDQT(); writeSOF0(image.width, image.height); writeDHT(); writeSOS(); var DCY = 0; var DCU = 0; var DCV = 0; bytenew = 0; bytepos = 7; this.encode.displayName = "_encode_"; var imageData = image.data; var width = image.width; var height = image.height; var quadWidth = width * 4; var tripleWidth = width * 3; var x, y = 0; var r, g, b; var start, p, col, row, pos; while (y < height) { x = 0; while (x < quadWidth) { start = quadWidth * y + x; p = start; col = -1; row = 0; for (pos = 0; pos < 64; pos++) { row = pos >> 3; col = (pos & 7) * 4; p = start + row * quadWidth + col; if (y + row >= height) { p -= quadWidth * (y + 1 + row - height); } if (x + col >= quadWidth) { p -= x + col - quadWidth + 4; } r = imageData[p++]; g = imageData[p++]; b = imageData[p++]; YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128; UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128; VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128; } DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); x += 32; } y += 8; } if (bytepos >= 0) { var fillbits = []; fillbits[1] = bytepos + 1; fillbits[0] = (1 << bytepos + 1) - 1; writeBits(fillbits); } writeWord(65497); if (typeof module2 === "undefined") return new Uint8Array(byteout); return Buffer.from(byteout); var jpegDataUri = "data:image/jpeg;base64," + btoa2(byteout.join("")); byteout = []; var duration3 = (/* @__PURE__ */ new Date()).getTime() - time_start; return jpegDataUri; }; function setQuality(quality2) { if (quality2 <= 0) { quality2 = 1; } if (quality2 > 100) { quality2 = 100; } if (currentQuality == quality2) return; var sf = 0; if (quality2 < 50) { sf = Math.floor(5e3 / quality2); } else { sf = Math.floor(200 - quality2 * 2); } initQuantTables(sf); currentQuality = quality2; } function init() { var time_start = (/* @__PURE__ */ new Date()).getTime(); if (!quality) quality = 50; initCharLookupTable(); initHuffmanTbl(); initCategoryNumber(); initRGBYUVTable(); setQuality(quality); var duration3 = (/* @__PURE__ */ new Date()).getTime() - time_start; } init(); } if (typeof module2 !== "undefined") { module2.exports = encode3; } else if (typeof window !== "undefined") { window["jpeg-js"] = window["jpeg-js"] || {}; window["jpeg-js"].encode = encode3; } function encode3(imgData, qu) { if (typeof qu === "undefined") qu = 50; var encoder = new JPEGEncoder(qu); var data = encoder.encode(imgData, qu); return { data, width: imgData.width, height: imgData.height }; } } }); // node_modules/jpeg-js/lib/decoder.js var require_decoder = __commonJS({ "node_modules/jpeg-js/lib/decoder.js"(exports2, module2) { var JpegImage = (function jpegImage() { "use strict"; var dctZigZag = new Int32Array([ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 ]); var dctCos1 = 4017; var dctSin1 = 799; var dctCos3 = 3406; var dctSin3 = 2276; var dctCos6 = 1567; var dctSin6 = 3784; var dctSqrt2 = 5793; var dctSqrt1d2 = 2896; function constructor() { } function buildHuffmanTable(codeLengths, values) { var k = 0, code = [], i, j, length = 16; while (length > 0 && !codeLengths[length - 1]) length--; code.push({ children: [], index: 0 }); var p = code[0], q; for (i = 0; i < length; i++) { for (j = 0; j < codeLengths[i]; j++) { p = code.pop(); p.children[p.index] = values[k]; while (p.index > 0) { if (code.length === 0) throw new Error("Could not recreate Huffman Table"); p = code.pop(); } p.index++; code.push(p); while (code.length <= i) { code.push(q = { children: [], index: 0 }); p.children[p.index] = q.children; p = q; } k++; } if (i + 1 < length) { code.push(q = { children: [], index: 0 }); p.children[p.index] = q.children; p = q; } } return code[0].children; } function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive, opts) { var precision = frame.precision; var samplesPerLine = frame.samplesPerLine; var scanLines = frame.scanLines; var mcusPerLine = frame.mcusPerLine; var progressive = frame.progressive; var maxH = frame.maxH, maxV = frame.maxV; var startOffset = offset, bitsData = 0, bitsCount = 0; function readBit() { if (bitsCount > 0) { bitsCount--; return bitsData >> bitsCount & 1; } bitsData = data[offset++]; if (bitsData == 255) { var nextByte = data[offset++]; if (nextByte) { throw new Error("unexpected marker: " + (bitsData << 8 | nextByte).toString(16)); } } bitsCount = 7; return bitsData >>> 7; } function decodeHuffman(tree) { var node = tree, bit; while ((bit = readBit()) !== null) { node = node[bit]; if (typeof node === "number") return node; if (typeof node !== "object") throw new Error("invalid huffman sequence"); } return null; } function receive(length) { var n2 = 0; while (length > 0) { var bit = readBit(); if (bit === null) return; n2 = n2 << 1 | bit; length--; } return n2; } function receiveAndExtend(length) { var n2 = receive(length); if (n2 >= 1 << length - 1) return n2; return n2 + (-1 << length) + 1; } function decodeBaseline(component2, zz) { var t = decodeHuffman(component2.huffmanTableDC); var diff2 = t === 0 ? 0 : receiveAndExtend(t); zz[0] = component2.pred += diff2; var k2 = 1; while (k2 < 64) { var rs = decodeHuffman(component2.huffmanTableAC); var s = rs & 15, r = rs >> 4; if (s === 0) { if (r < 15) break; k2 += 16; continue; } k2 += r; var z2 = dctZigZag[k2]; zz[z2] = receiveAndExtend(s); k2++; } } function decodeDCFirst(component2, zz) { var t = decodeHuffman(component2.huffmanTableDC); var diff2 = t === 0 ? 0 : receiveAndExtend(t) << successive; zz[0] = component2.pred += diff2; } function decodeDCSuccessive(component2, zz) { zz[0] |= readBit() << successive; } var eobrun = 0; function decodeACFirst(component2, zz) { if (eobrun > 0) { eobrun--; return; } var k2 = spectralStart, e = spectralEnd; while (k2 <= e) { var rs = decodeHuffman(component2.huffmanTableAC); var s = rs & 15, r = rs >> 4; if (s === 0) { if (r < 15) { eobrun = receive(r) + (1 << r) - 1; break; } k2 += 16; continue; } k2 += r; var z2 = dctZigZag[k2]; zz[z2] = receiveAndExtend(s) * (1 << successive); k2++; } } var successiveACState = 0, successiveACNextValue; function decodeACSuccessive(component2, zz) { var k2 = spectralStart, e = spectralEnd, r = 0; while (k2 <= e) { var z2 = dctZigZag[k2]; var direction = zz[z2] < 0 ? -1 : 1; switch (successiveACState) { case 0: var rs = decodeHuffman(component2.huffmanTableAC); var s = rs & 15, r = rs >> 4; if (s === 0) { if (r < 15) { eobrun = receive(r) + (1 << r); successiveACState = 4; } else { r = 16; successiveACState = 1; } } else { if (s !== 1) throw new Error("invalid ACn encoding"); successiveACNextValue = receiveAndExtend(s); successiveACState = r ? 2 : 3; } continue; case 1: // skipping r zero items case 2: if (zz[z2]) zz[z2] += (readBit() << successive) * direction; else { r--; if (r === 0) successiveACState = successiveACState == 2 ? 3 : 0; } break; case 3: if (zz[z2]) zz[z2] += (readBit() << successive) * direction; else { zz[z2] = successiveACNextValue << successive; successiveACState = 0; } break; case 4: if (zz[z2]) zz[z2] += (readBit() << successive) * direction; break; } k2++; } if (successiveACState === 4) { eobrun--; if (eobrun === 0) successiveACState = 0; } } function decodeMcu(component2, decode4, mcu2, row, col) { var mcuRow = mcu2 / mcusPerLine | 0; var mcuCol = mcu2 % mcusPerLine; var blockRow = mcuRow * component2.v + row; var blockCol = mcuCol * component2.h + col; if (component2.blocks[blockRow] === void 0 && opts.tolerantDecoding) return; decode4(component2, component2.blocks[blockRow][blockCol]); } function decodeBlock(component2, decode4, mcu2) { var blockRow = mcu2 / component2.blocksPerLine | 0; var blockCol = mcu2 % component2.blocksPerLine; if (component2.blocks[blockRow] === void 0 && opts.tolerantDecoding) return; decode4(component2, component2.blocks[blockRow][blockCol]); } var componentsLength = components.length; var component, i, j, k, n; var decodeFn; if (progressive) { if (spectralStart === 0) decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive; else decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive; } else { decodeFn = decodeBaseline; } var mcu = 0, marker; var mcuExpected; if (componentsLength == 1) { mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; } else { mcuExpected = mcusPerLine * frame.mcusPerColumn; } if (!resetInterval) resetInterval = mcuExpected; var h, v; while (mcu < mcuExpected) { for (i = 0; i < componentsLength; i++) components[i].pred = 0; eobrun = 0; if (componentsLength == 1) { component = components[0]; for (n = 0; n < resetInterval; n++) { decodeBlock(component, decodeFn, mcu); mcu++; } } else { for (n = 0; n < resetInterval; n++) { for (i = 0; i < componentsLength; i++) { component = components[i]; h = component.h; v = component.v; for (j = 0; j < v; j++) { for (k = 0; k < h; k++) { decodeMcu(component, decodeFn, mcu, j, k); } } } mcu++; if (mcu === mcuExpected) break; } } if (mcu === mcuExpected) { do { if (data[offset] === 255) { if (data[offset + 1] !== 0) { break; } } offset += 1; } while (offset < data.length - 2); } bitsCount = 0; marker = data[offset] << 8 | data[offset + 1]; if (marker < 65280) { throw new Error("marker was not found"); } if (marker >= 65488 && marker <= 65495) { offset += 2; } else break; } return offset - startOffset; } function buildComponentData(frame, component) { var lines = []; var blocksPerLine = component.blocksPerLine; var blocksPerColumn = component.blocksPerColumn; var samplesPerLine = blocksPerLine << 3; var R = new Int32Array(64), r = new Uint8Array(64); function quantizeAndInverse(zz, dataOut, dataIn) { var qt = component.quantizationTable; var v0, v1, v2, v3, v4, v5, v6, v7, t; var p = dataIn; var i2; for (i2 = 0; i2 < 64; i2++) p[i2] = zz[i2] * qt[i2]; for (i2 = 0; i2 < 8; ++i2) { var row = 8 * i2; if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && p[7 + row] == 0) { t = dctSqrt2 * p[0 + row] + 512 >> 10; p[0 + row] = t; p[1 + row] = t; p[2 + row] = t; p[3 + row] = t; p[4 + row] = t; p[5 + row] = t; p[6 + row] = t; p[7 + row] = t; continue; } v0 = dctSqrt2 * p[0 + row] + 128 >> 8; v1 = dctSqrt2 * p[4 + row] + 128 >> 8; v2 = p[2 + row]; v3 = p[6 + row]; v4 = dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128 >> 8; v7 = dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128 >> 8; v5 = p[3 + row] << 4; v6 = p[5 + row] << 4; t = v0 - v1 + 1 >> 1; v0 = v0 + v1 + 1 >> 1; v1 = t; t = v2 * dctSin6 + v3 * dctCos6 + 128 >> 8; v2 = v2 * dctCos6 - v3 * dctSin6 + 128 >> 8; v3 = t; t = v4 - v6 + 1 >> 1; v4 = v4 + v6 + 1 >> 1; v6 = t; t = v7 + v5 + 1 >> 1; v5 = v7 - v5 + 1 >> 1; v7 = t; t = v0 - v3 + 1 >> 1; v0 = v0 + v3 + 1 >> 1; v3 = t; t = v1 - v2 + 1 >> 1; v1 = v1 + v2 + 1 >> 1; v2 = t; t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12; v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12; v7 = t; t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12; v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12; v6 = t; p[0 + row] = v0 + v7; p[7 + row] = v0 - v7; p[1 + row] = v1 + v6; p[6 + row] = v1 - v6; p[2 + row] = v2 + v5; p[5 + row] = v2 - v5; p[3 + row] = v3 + v4; p[4 + row] = v3 - v4; } for (i2 = 0; i2 < 8; ++i2) { var col = i2; if (p[1 * 8 + col] == 0 && p[2 * 8 + col] == 0 && p[3 * 8 + col] == 0 && p[4 * 8 + col] == 0 && p[5 * 8 + col] == 0 && p[6 * 8 + col] == 0 && p[7 * 8 + col] == 0) { t = dctSqrt2 * dataIn[i2 + 0] + 8192 >> 14; p[0 * 8 + col] = t; p[1 * 8 + col] = t; p[2 * 8 + col] = t; p[3 * 8 + col] = t; p[4 * 8 + col] = t; p[5 * 8 + col] = t; p[6 * 8 + col] = t; p[7 * 8 + col] = t; continue; } v0 = dctSqrt2 * p[0 * 8 + col] + 2048 >> 12; v1 = dctSqrt2 * p[4 * 8 + col] + 2048 >> 12; v2 = p[2 * 8 + col]; v3 = p[6 * 8 + col]; v4 = dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048 >> 12; v7 = dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048 >> 12; v5 = p[3 * 8 + col]; v6 = p[5 * 8 + col]; t = v0 - v1 + 1 >> 1; v0 = v0 + v1 + 1 >> 1; v1 = t; t = v2 * dctSin6 + v3 * dctCos6 + 2048 >> 12; v2 = v2 * dctCos6 - v3 * dctSin6 + 2048 >> 12; v3 = t; t = v4 - v6 + 1 >> 1; v4 = v4 + v6 + 1 >> 1; v6 = t; t = v7 + v5 + 1 >> 1; v5 = v7 - v5 + 1 >> 1; v7 = t; t = v0 - v3 + 1 >> 1; v0 = v0 + v3 + 1 >> 1; v3 = t; t = v1 - v2 + 1 >> 1; v1 = v1 + v2 + 1 >> 1; v2 = t; t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12; v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12; v7 = t; t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12; v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12; v6 = t; p[0 * 8 + col] = v0 + v7; p[7 * 8 + col] = v0 - v7; p[1 * 8 + col] = v1 + v6; p[6 * 8 + col] = v1 - v6; p[2 * 8 + col] = v2 + v5; p[5 * 8 + col] = v2 - v5; p[3 * 8 + col] = v3 + v4; p[4 * 8 + col] = v3 - v4; } for (i2 = 0; i2 < 64; ++i2) { var sample2 = 128 + (p[i2] + 8 >> 4); dataOut[i2] = sample2 < 0 ? 0 : sample2 > 255 ? 255 : sample2; } } requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8); var i, j; for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { var scanLine = blockRow << 3; for (i = 0; i < 8; i++) lines.push(new Uint8Array(samplesPerLine)); for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { quantizeAndInverse(component.blocks[blockRow][blockCol], r, R); var offset = 0, sample = blockCol << 3; for (j = 0; j < 8; j++) { var line = lines[scanLine + j]; for (i = 0; i < 8; i++) line[sample + i] = r[offset++]; } } } return lines; } function clampTo8bit(a) { return a < 0 ? 0 : a > 255 ? 255 : a; } constructor.prototype = { load: function load(path) { var xhr = new XMLHttpRequest(); xhr.open("GET", path, true); xhr.responseType = "arraybuffer"; xhr.onload = (function() { var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); this.parse(data); if (this.onload) this.onload(); }).bind(this); xhr.send(null); }, parse: function parse3(data) { var maxResolutionInPixels = this.opts.maxResolutionInMP * 1e3 * 1e3; var offset = 0, length = data.length; function readUint16() { var value = data[offset] << 8 | data[offset + 1]; offset += 2; return value; } function readDataBlock() { var length2 = readUint16(); var array2 = data.subarray(offset, offset + length2 - 2); offset += array2.length; return array2; } function prepareComponents(frame2) { var maxH2 = 1, maxV2 = 1; var component2, componentId2; for (componentId2 in frame2.components) { if (frame2.components.hasOwnProperty(componentId2)) { component2 = frame2.components[componentId2]; if (maxH2 < component2.h) maxH2 = component2.h; if (maxV2 < component2.v) maxV2 = component2.v; } } var mcusPerLine = Math.ceil(frame2.samplesPerLine / 8 / maxH2); var mcusPerColumn = Math.ceil(frame2.scanLines / 8 / maxV2); for (componentId2 in frame2.components) { if (frame2.components.hasOwnProperty(componentId2)) { component2 = frame2.components[componentId2]; var blocksPerLine = Math.ceil(Math.ceil(frame2.samplesPerLine / 8) * component2.h / maxH2); var blocksPerColumn = Math.ceil(Math.ceil(frame2.scanLines / 8) * component2.v / maxV2); var blocksPerLineForMcu = mcusPerLine * component2.h; var blocksPerColumnForMcu = mcusPerColumn * component2.v; var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu; var blocks = []; requestMemoryAllocation(blocksToAllocate * 256); for (var i2 = 0; i2 < blocksPerColumnForMcu; i2++) { var row = []; for (var j2 = 0; j2 < blocksPerLineForMcu; j2++) row.push(new Int32Array(64)); blocks.push(row); } component2.blocksPerLine = blocksPerLine; component2.blocksPerColumn = blocksPerColumn; component2.blocks = blocks; } } frame2.maxH = maxH2; frame2.maxV = maxV2; frame2.mcusPerLine = mcusPerLine; frame2.mcusPerColumn = mcusPerColumn; } var jfif = null; var adobe = null; var pixels = null; var frame, resetInterval; var quantizationTables = [], frames = []; var huffmanTablesAC = [], huffmanTablesDC = []; var fileMarker = readUint16(); var malformedDataOffset = -1; this.comments = []; if (fileMarker != 65496) { throw new Error("SOI not found"); } fileMarker = readUint16(); while (fileMarker != 65497) { var i, j, l; switch (fileMarker) { case 65280: break; case 65504: // APP0 (Application Specific) case 65505: // APP1 case 65506: // APP2 case 65507: // APP3 case 65508: // APP4 case 65509: // APP5 case 65510: // APP6 case 65511: // APP7 case 65512: // APP8 case 65513: // APP9 case 65514: // APP10 case 65515: // APP11 case 65516: // APP12 case 65517: // APP13 case 65518: // APP14 case 65519: // APP15 case 65534: var appData = readDataBlock(); if (fileMarker === 65534) { var comment = String.fromCharCode.apply(null, appData); this.comments.push(comment); } if (fileMarker === 65504) { if (appData[0] === 74 && appData[1] === 70 && appData[2] === 73 && appData[3] === 70 && appData[4] === 0) { jfif = { version: { major: appData[5], minor: appData[6] }, densityUnits: appData[7], xDensity: appData[8] << 8 | appData[9], yDensity: appData[10] << 8 | appData[11], thumbWidth: appData[12], thumbHeight: appData[13], thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13]) }; } } if (fileMarker === 65505) { if (appData[0] === 69 && appData[1] === 120 && appData[2] === 105 && appData[3] === 102 && appData[4] === 0) { this.exifBuffer = appData.subarray(5, appData.length); } } if (fileMarker === 65518) { if (appData[0] === 65 && appData[1] === 100 && appData[2] === 111 && appData[3] === 98 && appData[4] === 101 && appData[5] === 0) { adobe = { version: appData[6], flags0: appData[7] << 8 | appData[8], flags1: appData[9] << 8 | appData[10], transformCode: appData[11] }; } } break; case 65499: var quantizationTablesLength = readUint16(); var quantizationTablesEnd = quantizationTablesLength + offset - 2; while (offset < quantizationTablesEnd) { var quantizationTableSpec = data[offset++]; requestMemoryAllocation(64 * 4); var tableData = new Int32Array(64); if (quantizationTableSpec >> 4 === 0) { for (j = 0; j < 64; j++) { var z2 = dctZigZag[j]; tableData[z2] = data[offset++]; } } else if (quantizationTableSpec >> 4 === 1) { for (j = 0; j < 64; j++) { var z2 = dctZigZag[j]; tableData[z2] = readUint16(); } } else throw new Error("DQT: invalid table spec"); quantizationTables[quantizationTableSpec & 15] = tableData; } break; case 65472: // SOF0 (Start of Frame, Baseline DCT) case 65473: // SOF1 (Start of Frame, Extended DCT) case 65474: readUint16(); frame = {}; frame.extended = fileMarker === 65473; frame.progressive = fileMarker === 65474; frame.precision = data[offset++]; frame.scanLines = readUint16(); frame.samplesPerLine = readUint16(); frame.components = {}; frame.componentsOrder = []; var pixelsInFrame = frame.scanLines * frame.samplesPerLine; if (pixelsInFrame > maxResolutionInPixels) { var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6); throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`); } var componentsCount = data[offset++], componentId; var maxH = 0, maxV = 0; for (i = 0; i < componentsCount; i++) { componentId = data[offset]; var h = data[offset + 1] >> 4; var v = data[offset + 1] & 15; var qId = data[offset + 2]; if (h <= 0 || v <= 0) { throw new Error("Invalid sampling factor, expected values above 0"); } frame.componentsOrder.push(componentId); frame.components[componentId] = { h, v, quantizationIdx: qId }; offset += 3; } prepareComponents(frame); frames.push(frame); break; case 65476: var huffmanLength = readUint16(); for (i = 2; i < huffmanLength; ) { var huffmanTableSpec = data[offset++]; var codeLengths = new Uint8Array(16); var codeLengthSum = 0; for (j = 0; j < 16; j++, offset++) { codeLengthSum += codeLengths[j] = data[offset]; } requestMemoryAllocation(16 + codeLengthSum); var huffmanValues = new Uint8Array(codeLengthSum); for (j = 0; j < codeLengthSum; j++, offset++) huffmanValues[j] = data[offset]; i += 17 + codeLengthSum; (huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues); } break; case 65501: readUint16(); resetInterval = readUint16(); break; case 65500: readUint16(); readUint16(); break; case 65498: var scanLength = readUint16(); var selectorsCount = data[offset++]; var components = [], component; for (i = 0; i < selectorsCount; i++) { component = frame.components[data[offset++]]; var tableSpec = data[offset++]; component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4]; component.huffmanTableAC = huffmanTablesAC[tableSpec & 15]; components.push(component); } var spectralStart = data[offset++]; var spectralEnd = data[offset++]; var successiveApproximation = data[offset++]; var processed = decodeScan( data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15, this.opts ); offset += processed; break; case 65535: if (data[offset] !== 255) { offset--; } break; default: if (data[offset - 3] == 255 && data[offset - 2] >= 192 && data[offset - 2] <= 254) { offset -= 3; break; } else if (fileMarker === 224 || fileMarker == 225) { if (malformedDataOffset !== -1) { throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`); } malformedDataOffset = offset - 1; const nextOffset = readUint16(); if (data[offset + nextOffset - 2] === 255) { offset += nextOffset - 2; break; } } throw new Error("unknown JPEG marker " + fileMarker.toString(16)); } fileMarker = readUint16(); } if (frames.length != 1) throw new Error("only single frame JPEGs supported"); for (var i = 0; i < frames.length; i++) { var cp = frames[i].components; for (var j in cp) { cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx]; delete cp[j].quantizationIdx; } } this.width = frame.samplesPerLine; this.height = frame.scanLines; this.jfif = jfif; this.adobe = adobe; this.components = []; for (var i = 0; i < frame.componentsOrder.length; i++) { var component = frame.components[frame.componentsOrder[i]]; this.components.push({ lines: buildComponentData(frame, component), scaleX: component.h / frame.maxH, scaleY: component.v / frame.maxV }); } }, getData: function getData(width, height) { var scaleX = this.width / width, scaleY = this.height / height; var component1, component2, component3, component4; var component1Line, component2Line, component3Line, component4Line; var x, y; var offset = 0; var Y, Cb, Cr, K, C, M, Ye, R, G, B; var colorTransform; var dataLength = width * height * this.components.length; requestMemoryAllocation(dataLength); var data = new Uint8Array(dataLength); switch (this.components.length) { case 1: component1 = this.components[0]; for (y = 0; y < height; y++) { component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; for (x = 0; x < width; x++) { Y = component1Line[0 | x * component1.scaleX * scaleX]; data[offset++] = Y; } } break; case 2: component1 = this.components[0]; component2 = this.components[1]; for (y = 0; y < height; y++) { component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; component2Line = component2.lines[0 | y * component2.scaleY * scaleY]; for (x = 0; x < width; x++) { Y = component1Line[0 | x * component1.scaleX * scaleX]; data[offset++] = Y; Y = component2Line[0 | x * component2.scaleX * scaleX]; data[offset++] = Y; } } break; case 3: colorTransform = true; if (this.adobe && this.adobe.transformCode) colorTransform = true; else if (typeof this.opts.colorTransform !== "undefined") colorTransform = !!this.opts.colorTransform; component1 = this.components[0]; component2 = this.components[1]; component3 = this.components[2]; for (y = 0; y < height; y++) { component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; component2Line = component2.lines[0 | y * component2.scaleY * scaleY]; component3Line = component3.lines[0 | y * component3.scaleY * scaleY]; for (x = 0; x < width; x++) { if (!colorTransform) { R = component1Line[0 | x * component1.scaleX * scaleX]; G = component2Line[0 | x * component2.scaleX * scaleX]; B = component3Line[0 | x * component3.scaleX * scaleX]; } else { Y = component1Line[0 | x * component1.scaleX * scaleX]; Cb = component2Line[0 | x * component2.scaleX * scaleX]; Cr = component3Line[0 | x * component3.scaleX * scaleX]; R = clampTo8bit(Y + 1.402 * (Cr - 128)); G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); B = clampTo8bit(Y + 1.772 * (Cb - 128)); } data[offset++] = R; data[offset++] = G; data[offset++] = B; } } break; case 4: if (!this.adobe) throw new Error("Unsupported color mode (4 components)"); colorTransform = false; if (this.adobe && this.adobe.transformCode) colorTransform = true; else if (typeof this.opts.colorTransform !== "undefined") colorTransform = !!this.opts.colorTransform; component1 = this.components[0]; component2 = this.components[1]; component3 = this.components[2]; component4 = this.components[3]; for (y = 0; y < height; y++) { component1Line = component1.lines[0 | y * component1.scaleY * scaleY]; component2Line = component2.lines[0 | y * component2.scaleY * scaleY]; component3Line = component3.lines[0 | y * component3.scaleY * scaleY]; component4Line = component4.lines[0 | y * component4.scaleY * scaleY]; for (x = 0; x < width; x++) { if (!colorTransform) { C = component1Line[0 | x * component1.scaleX * scaleX]; M = component2Line[0 | x * component2.scaleX * scaleX]; Ye = component3Line[0 | x * component3.scaleX * scaleX]; K = component4Line[0 | x * component4.scaleX * scaleX]; } else { Y = component1Line[0 | x * component1.scaleX * scaleX]; Cb = component2Line[0 | x * component2.scaleX * scaleX]; Cr = component3Line[0 | x * component3.scaleX * scaleX]; K = component4Line[0 | x * component4.scaleX * scaleX]; C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128)); M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128)); } data[offset++] = 255 - C; data[offset++] = 255 - M; data[offset++] = 255 - Ye; data[offset++] = 255 - K; } } break; default: throw new Error("Unsupported color mode"); } return data; }, copyToImageData: function copyToImageData(imageData, formatAsRGBA) { var width = imageData.width, height = imageData.height; var imageDataArray = imageData.data; var data = this.getData(width, height); var i = 0, j = 0, x, y; var Y, K, C, M, R, G, B; switch (this.components.length) { case 1: for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { Y = data[i++]; imageDataArray[j++] = Y; imageDataArray[j++] = Y; imageDataArray[j++] = Y; if (formatAsRGBA) { imageDataArray[j++] = 255; } } } break; case 3: for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { R = data[i++]; G = data[i++]; B = data[i++]; imageDataArray[j++] = R; imageDataArray[j++] = G; imageDataArray[j++] = B; if (formatAsRGBA) { imageDataArray[j++] = 255; } } } break; case 4: for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { C = data[i++]; M = data[i++]; Y = data[i++]; K = data[i++]; R = 255 - clampTo8bit(C * (1 - K / 255) + K); G = 255 - clampTo8bit(M * (1 - K / 255) + K); B = 255 - clampTo8bit(Y * (1 - K / 255) + K); imageDataArray[j++] = R; imageDataArray[j++] = G; imageDataArray[j++] = B; if (formatAsRGBA) { imageDataArray[j++] = 255; } } } break; default: throw new Error("Unsupported color mode"); } } }; var totalBytesAllocated = 0; var maxMemoryUsageBytes = 0; function requestMemoryAllocation(increaseAmount = 0) { var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount; if (totalMemoryImpactBytes > maxMemoryUsageBytes) { var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024); throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`); } totalBytesAllocated = totalMemoryImpactBytes; } constructor.resetMaxMemoryUsage = function(maxMemoryUsageBytes_) { totalBytesAllocated = 0; maxMemoryUsageBytes = maxMemoryUsageBytes_; }; constructor.getBytesAllocated = function() { return totalBytesAllocated; }; constructor.requestMemoryAllocation = requestMemoryAllocation; return constructor; })(); if (typeof module2 !== "undefined") { module2.exports = decode3; } else if (typeof window !== "undefined") { window["jpeg-js"] = window["jpeg-js"] || {}; window["jpeg-js"].decode = decode3; } function decode3(jpegData, userOpts = {}) { var defaultOpts = { // "undefined" means "Choose whether to transform colors based on the image’s color model." colorTransform: void 0, useTArray: false, formatAsRGBA: true, tolerantDecoding: true, maxResolutionInMP: 100, // Don't decode more than 100 megapixels maxMemoryUsageInMB: 512 // Don't decode if memory footprint is more than 512MB }; var opts = { ...defaultOpts, ...userOpts }; var arr = new Uint8Array(jpegData); var decoder = new JpegImage(); decoder.opts = opts; JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024); decoder.parse(arr); var channels = opts.formatAsRGBA ? 4 : 3; var bytesNeeded = decoder.width * decoder.height * channels; try { JpegImage.requestMemoryAllocation(bytesNeeded); var image = { width: decoder.width, height: decoder.height, exifBuffer: decoder.exifBuffer, data: opts.useTArray ? new Uint8Array(bytesNeeded) : Buffer.alloc(bytesNeeded) }; if (decoder.comments.length > 0) { image["comments"] = decoder.comments; } } catch (err) { if (err instanceof RangeError) { throw new Error("Could not allocate enough memory for the image. Required: " + bytesNeeded); } if (err instanceof ReferenceError) { if (err.message === "Buffer is not defined") { throw new Error("Buffer is not globally defined in this environment. Consider setting useTArray to true"); } } throw err; } decoder.copyToImageData(image, opts.formatAsRGBA); return image; } } }); // node_modules/jpeg-js/index.js var require_jpeg_js = __commonJS({ "node_modules/jpeg-js/index.js"(exports2, module2) { var encode3 = require_encoder(); var decode3 = require_decoder(); module2.exports = { encode: encode3, decode: decode3 }; } }); // node_modules/mime/Mime.js var require_Mime = __commonJS({ "node_modules/mime/Mime.js"(exports2, module2) { "use strict"; function Mime() { this._types = /* @__PURE__ */ Object.create(null); this._extensions = /* @__PURE__ */ Object.create(null); for (let i = 0; i < arguments.length; i++) { this.define(arguments[i]); } this.define = this.define.bind(this); this.getType = this.getType.bind(this); this.getExtension = this.getExtension.bind(this); } Mime.prototype.define = function(typeMap, force) { for (let type in typeMap) { let extensions = typeMap[type].map(function(t) { return t.toLowerCase(); }); type = type.toLowerCase(); for (let i = 0; i < extensions.length; i++) { const ext = extensions[i]; if (ext[0] === "*") { continue; } if (!force && ext in this._types) { throw new Error( 'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".' ); } this._types[ext] = type; } if (force || !this._extensions[type]) { const ext = extensions[0]; this._extensions[type] = ext[0] !== "*" ? ext : ext.substr(1); } } }; Mime.prototype.getType = function(path) { path = String(path); let last = path.replace(/^.*[/\\]/, "").toLowerCase(); let ext = last.replace(/^.*\./, "").toLowerCase(); let hasPath = last.length < path.length; let hasDot = ext.length < last.length - 1; return (hasDot || !hasPath) && this._types[ext] || null; }; Mime.prototype.getExtension = function(type) { type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; return type && this._extensions[type.toLowerCase()] || null; }; module2.exports = Mime; } }); // node_modules/mime/types/standard.js var require_standard = __commonJS({ "node_modules/mime/types/standard.js"(exports2, module2) { module2.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] }; } }); // node_modules/mime/types/other.js var require_other = __commonJS({ "node_modules/mime/types/other.js"(exports2, module2) { module2.exports = { "application/prs.cww": ["cww"], "application/vnd.1000minds.decision-model+xml": ["1km"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.keynote": ["key"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.numbers": ["numbers"], "application/vnd.apple.pages": ["pages"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.balsamiq.bmml+xml": ["bmml"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.citationstyles.style+xml": ["csl"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dbf": ["dbf"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mapbox-vector-tile": ["mvt"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["*stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.ac+xml": ["*ac"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openblox.game+xml": ["obgx"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openstreetmap.data+xml": ["osm"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.rar": ["rar"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.software602.filler.form+xml": ["fo"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.syncml.dmddf+xml": ["ddf"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": ["*dmg"], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": ["*bdoc"], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["*deb", "udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": ["*iso"], "application/x-iwork-keynote-sffkey": ["*key"], "application/x-iwork-numbers-sffnumbers": ["*numbers"], "application/x-iwork-pages-sffpages": ["*pages"], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-keepass2": ["kdbx"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": ["*exe"], "application/x-msdownload": ["*exe", "*dll", "com", "bat", "*msi"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["*wmf", "*wmz", "*emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": ["*prc", "*pdb"], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["*rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["*obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["*xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": ["*m4a"], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": ["*ra"], "audio/x-wav": ["*wav"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "image/prs.btif": ["btif"], "image/prs.pti": ["pti"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.airzip.accelerator.azv": ["azv"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": ["*sub"], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.microsoft.icon": ["ico"], "image/vnd.ms-dds": ["dds"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.pco.b16": ["b16"], "image/vnd.tencent.tap": ["tap"], "image/vnd.valve.source.texture": ["vtf"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/vnd.zbrush.pcx": ["pcx"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["*ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": ["*bmp"], "image/x-pcx": ["*pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/vnd.wfa.wsc": ["wsc"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.opengex": ["ogex"], "model/vnd.parasolid.transmit.binary": ["x_b"], "model/vnd.parasolid.transmit.text": ["x_t"], "model/vnd.sap.vds": ["vds"], "model/vnd.usdz+zip": ["usdz"], "model/vnd.valve.source.compiled-map": ["bsp"], "model/vnd.vtu": ["vtu"], "text/prs.lines.tag": ["dsc"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": ["*org"], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] }; } }); // node_modules/mime/index.js var require_mime = __commonJS({ "node_modules/mime/index.js"(exports2, module2) { "use strict"; var Mime = require_Mime(); module2.exports = new Mime(require_standard(), require_other()); } }); // node_modules/concat-map/index.js var require_concat_map = __commonJS({ "node_modules/concat-map/index.js"(exports2, module2) { module2.exports = function(xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function(xs) { return Object.prototype.toString.call(xs) === "[object Array]"; }; } }); // node_modules/balanced-match/index.js var require_balanced_match = __commonJS({ "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 r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[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 i = ai; if (ai >= 0 && bi > 0) { if (a === b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 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, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [left, right]; } } return result; } } }); // node_modules/brace-expansion/index.js var require_brace_expansion = __commonJS({ "node_modules/brace-expansion/index.js"(exports2, module2) { var concatMap = require_concat_map(); 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 m = balanced("{", "}", str); if (!m) return str.split(","); var pre = m.pre; var body = m.body; var post = m.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 expand(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return "{" + str + "}"; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced("{", "}", str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { if (m.post.match(/,(?!,).*\}/)) { str = m.pre + "{" + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : [""]; return post.map(function(p) { return m.pre + n[0] + p; }); } } } var pre = m.pre; var post = m.post.length ? expand(m.post, false) : [""]; var N; if (isSequence) { var x = 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 < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === "\\") c = ""; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z2 = new Array(need + 1).join("0"); if (i < 0) c = "-" + z2 + c.slice(1); else c = z2 + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, 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/minimatch/minimatch.js var require_minimatch = __commonJS({ "node_modules/minimatch/minimatch.js"(exports2, module2) { module2.exports = minimatch2; minimatch2.Minimatch = Minimatch; var path = (function() { try { return require("path"); } catch (e) { } })() || { sep: "/" }; minimatch2.sep = path.sep; var GLOBSTAR = minimatch2.GLOBSTAR = Minimatch.GLOBSTAR = {}; var expand = require_brace_expansion(); var plTypes = { "!": { open: "(?:(?!(?:", close: "))[^/]*?)" }, "?": { open: "(?:", close: ")?" }, "+": { open: "(?:", close: ")+" }, "*": { open: "(?:", close: ")*" }, "@": { open: "(?:", close: ")" } }; var qmark = "[^/]"; var star = qmark + "*?"; var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; var reSpecials = charSet("().*{}+?[]^$\\!"); function charSet(s) { return s.split("").reduce(function(set2, c) { set2[c] = true; return set2; }, {}); } var slashSplit = /\/+/; minimatch2.filter = filter; function filter(pattern, options) { options = options || {}; return function(p, i, list) { return minimatch2(p, pattern, options); }; } function ext(a, b) { b = b || {}; var t = {}; Object.keys(a).forEach(function(k) { t[k] = a[k]; }); Object.keys(b).forEach(function(k) { t[k] = b[k]; }); return t; } minimatch2.defaults = function(def) { if (!def || typeof def !== "object" || !Object.keys(def).length) { return minimatch2; } var orig = minimatch2; var m = function minimatch3(p, pattern, options) { return orig(p, pattern, ext(def, options)); }; m.Minimatch = function Minimatch2(pattern, options) { return new orig.Minimatch(pattern, ext(def, options)); }; m.Minimatch.defaults = function defaults(options) { return orig.defaults(ext(def, options)).Minimatch; }; m.filter = function filter2(pattern, options) { return orig.filter(pattern, ext(def, options)); }; m.defaults = function defaults(options) { return orig.defaults(ext(def, options)); }; m.makeRe = function makeRe2(pattern, options) { return orig.makeRe(pattern, ext(def, options)); }; m.braceExpand = function braceExpand2(pattern, options) { return orig.braceExpand(pattern, ext(def, options)); }; m.match = function(list, pattern, options) { return orig.match(list, pattern, ext(def, options)); }; return m; }; Minimatch.defaults = function(def) { return minimatch2.defaults(def).Minimatch; }; function minimatch2(p, pattern, options) { assertValidPattern(pattern); if (!options) options = {}; if (!options.nocomment && pattern.charAt(0) === "#") { return false; } return new Minimatch(pattern, options).match(p); } function Minimatch(pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options); } assertValidPattern(pattern); if (!options) options = {}; pattern = pattern.trim(); if (!options.allowWindowsEscape && path.sep !== "/") { pattern = pattern.split(path.sep).join("/"); } this.options = options; this.maxGlobstarRecursion = options.maxGlobstarRecursion !== void 0 ? options.maxGlobstarRecursion : 200; this.set = []; this.pattern = pattern; this.regexp = null; this.negate = false; this.comment = false; this.empty = false; this.partial = !!options.partial; this.make(); } Minimatch.prototype.debug = function() { }; Minimatch.prototype.make = make; function make() { var pattern = this.pattern; var options = this.options; if (!options.nocomment && pattern.charAt(0) === "#") { this.comment = true; return; } if (!pattern) { this.empty = true; return; } this.parseNegate(); var set2 = this.globSet = this.braceExpand(); if (options.debug) this.debug = function debug2() { console.error.apply(console, arguments); }; this.debug(this.pattern, set2); set2 = this.globParts = set2.map(function(s) { return s.split(slashSplit); }); this.debug(this.pattern, set2); set2 = set2.map(function(s, si, set3) { return s.map(this.parse, this); }, this); this.debug(this.pattern, set2); set2 = set2.filter(function(s) { return s.indexOf(false) === -1; }); this.debug(this.pattern, set2); this.set = set2; } Minimatch.prototype.parseNegate = parseNegate; function parseNegate() { var pattern = this.pattern; var negate = false; var options = this.options; var negateOffset = 0; if (options.nonegate) return; for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) { negate = !negate; negateOffset++; } if (negateOffset) this.pattern = pattern.substr(negateOffset); this.negate = negate; } minimatch2.braceExpand = function(pattern, options) { return braceExpand(pattern, options); }; Minimatch.prototype.braceExpand = braceExpand; function braceExpand(pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options; } else { options = {}; } } pattern = typeof pattern === "undefined" ? this.pattern : pattern; assertValidPattern(pattern); if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { return [pattern]; } return expand(pattern); } var MAX_PATTERN_LENGTH = 1024 * 64; var assertValidPattern = function(pattern) { if (typeof pattern !== "string") { throw new TypeError("invalid pattern"); } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError("pattern is too long"); } }; Minimatch.prototype.parse = parse3; var SUBPARSE = {}; function parse3(pattern, isSub) { assertValidPattern(pattern); var options = this.options; if (pattern === "**") { if (!options.noglobstar) return GLOBSTAR; else pattern = "*"; } if (pattern === "") return ""; var re = ""; var hasMagic = !!options.nocase; var escaping = false; var patternListStack = []; var negativeLists = []; var stateChar; var inClass = false; var reClassStart = -1; var classStart = -1; var patternStart = pattern.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)"; var self = this; function clearStateChar() { if (stateChar) { switch (stateChar) { case "*": re += star; hasMagic = true; break; case "?": re += qmark; hasMagic = true; break; default: re += "\\" + stateChar; break; } self.debug("clearStateChar %j %j", stateChar, re); stateChar = false; } } for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) { this.debug("%s %s %s %j", pattern, i, re, c); if (escaping && reSpecials[c]) { re += "\\" + c; escaping = false; continue; } switch (c) { /* istanbul ignore next */ case "/": { return false; } case "\\": clearStateChar(); escaping = true; continue; // the various stateChar values // for the "extglob" stuff. case "?": case "*": case "+": case "@": case "!": this.debug("%s %s %s %j <-- stateChar", pattern, i, re, c); if (inClass) { this.debug(" in class"); if (c === "!" && i === classStart + 1) c = "^"; re += c; continue; } if (c === "*" && stateChar === "*") continue; self.debug("call clearStateChar %j", stateChar); clearStateChar(); stateChar = c; if (options.noext) clearStateChar(); continue; case "(": if (inClass) { re += "("; continue; } if (!stateChar) { re += "\\("; continue; } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }); re += stateChar === "!" ? "(?:(?!(?:" : "(?:"; this.debug("plType %j %j", stateChar, re); stateChar = false; continue; case ")": if (inClass || !patternListStack.length) { re += "\\)"; continue; } clearStateChar(); hasMagic = true; var pl = patternListStack.pop(); re += pl.close; if (pl.type === "!") { negativeLists.push(pl); } pl.reEnd = re.length; continue; case "|": if (inClass || !patternListStack.length || escaping) { re += "\\|"; escaping = false; continue; } clearStateChar(); re += "|"; continue; // these are mostly the same in regexp and glob case "[": clearStateChar(); if (inClass) { re += "\\" + c; continue; } inClass = true; classStart = i; reClassStart = re.length; re += c; continue; case "]": if (i === classStart + 1 || !inClass) { re += "\\" + c; escaping = false; continue; } var cs = pattern.substring(classStart + 1, i); try { RegExp("[" + cs + "]"); } catch (er) { var sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + "\\[" + sp[0] + "\\]"; hasMagic = hasMagic || sp[1]; inClass = false; continue; } hasMagic = true; inClass = false; re += c; continue; default: clearStateChar(); if (escaping) { escaping = false; } else if (reSpecials[c] && !(c === "^" && inClass)) { re += "\\"; } re += c; } } if (inClass) { cs = pattern.substr(classStart + 1); sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + "\\[" + sp[0]; hasMagic = hasMagic || sp[1]; } for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length); this.debug("setting tail", re, pl); tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function(_, $1, $2) { if (!$2) { $2 = "\\"; } return $1 + $1 + $2 + "|"; }); this.debug("tail=%j\n %s", tail, tail, pl, re); var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t + "\\(" + tail; } clearStateChar(); if (escaping) { re += "\\\\"; } var addPatternStart = false; switch (re.charAt(0)) { case "[": case ".": case "(": addPatternStart = true; } for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n]; var nlBefore = re.slice(0, nl.reStart); var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); var nlAfter = re.slice(nl.reEnd); nlLast += nlAfter; var openParensBefore = nlBefore.split("(").length - 1; var cleanAfter = nlAfter; for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, ""); } nlAfter = cleanAfter; var dollar = ""; if (nlAfter === "" && isSub !== SUBPARSE) { dollar = "$"; } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; re = newRe; } if (re !== "" && hasMagic) { re = "(?=.)" + re; } if (addPatternStart) { re = patternStart + re; } if (isSub === SUBPARSE) { return [re, hasMagic]; } if (!hasMagic) { return globUnescape(pattern); } var flags = options.nocase ? "i" : ""; try { var regExp = new RegExp("^" + re + "$", flags); } catch (er) { return new RegExp("$."); } regExp._glob = pattern; regExp._src = re; return regExp; } minimatch2.makeRe = function(pattern, options) { return new Minimatch(pattern, options || {}).makeRe(); }; Minimatch.prototype.makeRe = makeRe; function makeRe() { if (this.regexp || this.regexp === false) return this.regexp; var set2 = this.set; if (!set2.length) { this.regexp = false; return this.regexp; } var options = this.options; var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; var flags = options.nocase ? "i" : ""; var re = set2.map(function(pattern) { return pattern.map(function(p) { return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src; }).join("\\/"); }).join("|"); re = "^(?:" + re + ")$"; if (this.negate) re = "^(?!" + re + ").*$"; try { this.regexp = new RegExp(re, flags); } catch (ex) { this.regexp = false; } return this.regexp; } minimatch2.match = function(list, pattern, options) { options = options || {}; var mm = new Minimatch(pattern, options); list = list.filter(function(f) { return mm.match(f); }); if (mm.options.nonull && !list.length) { list.push(pattern); } return list; }; Minimatch.prototype.match = function match(f, partial2) { if (typeof partial2 === "undefined") partial2 = this.partial; this.debug("match", f, this.pattern); if (this.comment) return false; if (this.empty) return f === ""; if (f === "/" && partial2) return true; var options = this.options; if (path.sep !== "/") { f = f.split(path.sep).join("/"); } f = f.split(slashSplit); this.debug(this.pattern, "split", f); var set2 = this.set; this.debug(this.pattern, "set", set2); var filename; var i; for (i = f.length - 1; i >= 0; i--) { filename = f[i]; if (filename) break; } for (i = 0; i < set2.length; i++) { var pattern = set2[i]; var file2 = f; if (options.matchBase && pattern.length === 1) { file2 = [filename]; } var hit = this.matchOne(file2, pattern, partial2); if (hit) { if (options.flipNegate) return true; return !this.negate; } } if (options.flipNegate) return false; return this.negate; }; Minimatch.prototype.matchOne = function(file2, pattern, partial2) { if (pattern.indexOf(GLOBSTAR) !== -1) { return this._matchGlobstar(file2, pattern, partial2, 0, 0); } return this._matchOne(file2, pattern, partial2, 0, 0); }; Minimatch.prototype._matchGlobstar = function(file2, pattern, partial2, fileIndex, patternIndex) { var i; var firstgs = -1; for (i = patternIndex; i < pattern.length; i++) { if (pattern[i] === GLOBSTAR) { firstgs = i; break; } } var lastgs = -1; for (i = pattern.length - 1; i >= 0; i--) { if (pattern[i] === GLOBSTAR) { lastgs = i; break; } } var head = pattern.slice(patternIndex, firstgs); var body = partial2 ? pattern.slice(firstgs + 1) : pattern.slice(firstgs + 1, lastgs); var tail = partial2 ? [] : pattern.slice(lastgs + 1); if (head.length) { var fileHead = file2.slice(fileIndex, fileIndex + head.length); if (!this._matchOne(fileHead, head, partial2, 0, 0)) { return false; } fileIndex += head.length; } var fileTailMatch = 0; if (tail.length) { if (tail.length + fileIndex > file2.length) return false; var tailStart = file2.length - tail.length; if (this._matchOne(file2, tail, partial2, tailStart, 0)) { fileTailMatch = tail.length; } else { if (file2[file2.length - 1] !== "" || fileIndex + tail.length === file2.length) { return false; } tailStart--; if (!this._matchOne(file2, tail, partial2, tailStart, 0)) { return false; } fileTailMatch = tail.length + 1; } } if (!body.length) { var sawSome = !!fileTailMatch; for (i = fileIndex; i < file2.length - fileTailMatch; i++) { var f = String(file2[i]); sawSome = true; if (f === "." || f === ".." || !this.options.dot && f.charAt(0) === ".") { return false; } } return partial2 || sawSome; } var bodySegments = [[[], 0]]; var currentBody = bodySegments[0]; var nonGsParts = 0; var nonGsPartsSums = [0]; for (var bi = 0; bi < body.length; bi++) { var b = body[bi]; if (b === GLOBSTAR) { nonGsPartsSums.push(nonGsParts); currentBody = [[], 0]; bodySegments.push(currentBody); } else { currentBody[0].push(b); nonGsParts++; } } var idx = bodySegments.length - 1; var fileLength = file2.length - fileTailMatch; for (var si = 0; si < bodySegments.length; si++) { bodySegments[si][1] = fileLength - (nonGsPartsSums[idx--] + bodySegments[si][0].length); } return !!this._matchGlobStarBodySections( file2, bodySegments, fileIndex, 0, partial2, 0, !!fileTailMatch ); }; Minimatch.prototype._matchGlobStarBodySections = function(file2, bodySegments, fileIndex, bodyIndex, partial2, globStarDepth, sawTail) { var bs = bodySegments[bodyIndex]; if (!bs) { for (var i = fileIndex; i < file2.length; i++) { sawTail = true; var f = file2[i]; if (f === "." || f === ".." || !this.options.dot && f.charAt(0) === ".") { return false; } } return sawTail; } var body = bs[0]; var after = bs[1]; while (fileIndex <= after) { var m = this._matchOne( file2.slice(0, fileIndex + body.length), body, partial2, fileIndex, 0 ); if (m && globStarDepth < this.maxGlobstarRecursion) { var sub = this._matchGlobStarBodySections( file2, bodySegments, fileIndex + body.length, bodyIndex + 1, partial2, globStarDepth + 1, sawTail ); if (sub !== false) { return sub; } } var f = file2[fileIndex]; if (f === "." || f === ".." || !this.options.dot && f.charAt(0) === ".") { return false; } fileIndex++; } return partial2 || null; }; Minimatch.prototype._matchOne = function(file2, pattern, partial2, fileIndex, patternIndex) { var fi, pi, fl, pl; for (fi = fileIndex, pi = patternIndex, fl = file2.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { this.debug("matchOne loop"); var p = pattern[pi]; var f = file2[fi]; this.debug(pattern, p, f); if (p === false || p === GLOBSTAR) return false; var hit; if (typeof p === "string") { hit = f === p; this.debug("string match", p, f, hit); } else { hit = f.match(p); this.debug("pattern match", p, f, hit); } if (!hit) return false; } if (fi === fl && pi === pl) { return true; } else if (fi === fl) { return partial2; } else if (pi === pl) { return fi === fl - 1 && file2[fi] === ""; } throw new Error("wtf?"); }; function globUnescape(s) { return s.replace(/\\(.)/g, "$1"); } function regExpEscape(s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } } }); // node_modules/is-docker/index.js var require_is_docker = __commonJS({ "node_modules/is-docker/index.js"(exports2, module2) { "use strict"; var fs = require("fs"); var isDocker; function hasDockerEnv() { try { fs.statSync("/.dockerenv"); return true; } catch (_) { return false; } } function hasDockerCGroup() { try { return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker"); } catch (_) { return false; } } module2.exports = () => { if (isDocker === void 0) { isDocker = hasDockerEnv() || hasDockerCGroup(); } return isDocker; }; } }); // node_modules/is-wsl/index.js var require_is_wsl = __commonJS({ "node_modules/is-wsl/index.js"(exports2, module2) { "use strict"; var os = require("os"); var fs = require("fs"); var isDocker = require_is_docker(); var isWsl = () => { if (process.platform !== "linux") { return false; } if (os.release().toLowerCase().includes("microsoft")) { if (isDocker()) { return false; } return true; } try { return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false; } catch (_) { return false; } }; if (process.env.__IS_WSL_TEST__) { module2.exports = isWsl; } else { module2.exports = isWsl(); } } }); // node_modules/define-lazy-prop/index.js var require_define_lazy_prop = __commonJS({ "node_modules/define-lazy-prop/index.js"(exports2, module2) { "use strict"; module2.exports = (object3, propertyName, fn) => { const define = (value) => Object.defineProperty(object3, propertyName, { value, enumerable: true, writable: true }); Object.defineProperty(object3, propertyName, { configurable: true, enumerable: true, get() { const result = fn(); define(result); return result; }, set(value) { define(value); } }); return object3; }; } }); // node_modules/open/index.js var require_open = __commonJS({ "node_modules/open/index.js"(exports2, module2) { var path = require("path"); var childProcess = require("child_process"); var { promises: fs, constants: fsConstants } = require("fs"); var isWsl = require_is_wsl(); var isDocker = require_is_docker(); var defineLazyProperty = require_define_lazy_prop(); var localXdgOpenPath = path.join(__dirname, "xdg-open"); var { platform, arch } = process; var getWslDrivesMountPoint = /* @__PURE__ */ (() => { const defaultMountPoint = "/mnt/"; let mountPoint; return async function() { if (mountPoint) { return mountPoint; } const configFilePath = "/etc/wsl.conf"; let isConfigFileExists = false; try { await fs.access(configFilePath, fsConstants.F_OK); isConfigFileExists = true; } catch { } if (!isConfigFileExists) { return defaultMountPoint; } const configContent = await fs.readFile(configFilePath, { encoding: "utf8" }); const configMountPoint = /(?.*)/g.exec(configContent); if (!configMountPoint) { return defaultMountPoint; } mountPoint = configMountPoint.groups.mountPoint.trim(); mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`; return mountPoint; }; })(); var pTryEach = async (array2, mapper) => { let latestError; for (const item of array2) { try { return await mapper(item); } catch (error48) { latestError = error48; } } throw latestError; }; var baseOpen = async (options) => { options = { wait: false, background: false, newInstance: false, allowNonzeroExitCode: false, ...options }; if (Array.isArray(options.app)) { return pTryEach(options.app, (singleApp) => baseOpen({ ...options, app: singleApp })); } let { name: app, arguments: appArguments = [] } = options.app || {}; appArguments = [...appArguments]; if (Array.isArray(app)) { return pTryEach(app, (appName) => baseOpen({ ...options, app: { name: appName, arguments: appArguments } })); } let command; const cliArguments = []; const childProcessOptions = {}; if (platform === "darwin") { command = "open"; if (options.wait) { cliArguments.push("--wait-apps"); } if (options.background) { cliArguments.push("--background"); } if (options.newInstance) { cliArguments.push("--new"); } if (app) { cliArguments.push("-a", app); } } else if (platform === "win32" || isWsl && !isDocker()) { const mountPoint = await getWslDrivesMountPoint(); command = isWsl ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; cliArguments.push( "-NoProfile", "-NonInteractive", "\u2013ExecutionPolicy", "Bypass", "-EncodedCommand" ); if (!isWsl) { childProcessOptions.windowsVerbatimArguments = true; } const encodedArguments = ["Start"]; if (options.wait) { encodedArguments.push("-Wait"); } if (app) { encodedArguments.push(`"\`"${app}\`""`, "-ArgumentList"); if (options.target) { appArguments.unshift(options.target); } } else if (options.target) { encodedArguments.push(`"${options.target}"`); } if (appArguments.length > 0) { appArguments = appArguments.map((arg) => `"\`"${arg}\`""`); encodedArguments.push(appArguments.join(",")); } options.target = Buffer.from(encodedArguments.join(" "), "utf16le").toString("base64"); } else { if (app) { command = app; } else { const isBundled = !__dirname || __dirname === "/"; let exeLocalXdgOpen = false; try { await fs.access(localXdgOpenPath, fsConstants.X_OK); exeLocalXdgOpen = true; } catch { } const useSystemXdgOpen = process.versions.electron || platform === "android" || isBundled || !exeLocalXdgOpen; command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath; } if (appArguments.length > 0) { cliArguments.push(...appArguments); } if (!options.wait) { childProcessOptions.stdio = "ignore"; childProcessOptions.detached = true; } } if (options.target) { cliArguments.push(options.target); } if (platform === "darwin" && appArguments.length > 0) { cliArguments.push("--args", ...appArguments); } const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); if (options.wait) { return new Promise((resolve, reject) => { subprocess.once("error", reject); subprocess.once("close", (exitCode) => { if (options.allowNonzeroExitCode && exitCode > 0) { reject(new Error(`Exited with code ${exitCode}`)); return; } resolve(subprocess); }); }); } subprocess.unref(); return subprocess; }; var open2 = (target, options) => { if (typeof target !== "string") { throw new TypeError("Expected a `target`"); } return baseOpen({ ...options, target }); }; var openApp = (name, options) => { if (typeof name !== "string") { throw new TypeError("Expected a `name`"); } const { arguments: appArguments = [] } = options || {}; if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) { throw new TypeError("Expected `appArguments` as Array type"); } return baseOpen({ ...options, app: { name, arguments: appArguments } }); }; function detectArchBinary(binary) { if (typeof binary === "string" || Array.isArray(binary)) { return binary; } const { [arch]: archBinary } = binary; if (!archBinary) { throw new Error(`${arch} is not supported`); } return archBinary; } function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) { if (wsl && isWsl) { return detectArchBinary(wsl); } if (!platformBinary) { throw new Error(`${platform} is not supported`); } return detectArchBinary(platformBinary); } var apps = {}; defineLazyProperty(apps, "chrome", () => detectPlatformBinary({ darwin: "google chrome", win32: "chrome", linux: ["google-chrome", "google-chrome-stable", "chromium"] }, { wsl: { ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe", x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"] } })); defineLazyProperty(apps, "firefox", () => detectPlatformBinary({ darwin: "firefox", win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe", linux: "firefox" }, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" })); defineLazyProperty(apps, "edge", () => detectPlatformBinary({ darwin: "microsoft edge", win32: "msedge", linux: ["microsoft-edge", "microsoft-edge-dev"] }, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" })); open2.apps = apps; open2.openApp = openApp; module2.exports = open2; } }); // node_modules/pngjs/lib/chunkstream.js var require_chunkstream = __commonJS({ "node_modules/pngjs/lib/chunkstream.js"(exports2, module2) { "use strict"; var util2 = require("util"); var Stream = require("stream"); var ChunkStream = module2.exports = function() { Stream.call(this); this._buffers = []; this._buffered = 0; this._reads = []; this._paused = false; this._encoding = "utf8"; this.writable = true; }; util2.inherits(ChunkStream, Stream); ChunkStream.prototype.read = function(length, callback) { this._reads.push({ length: Math.abs(length), // if length < 0 then at most this length allowLess: length < 0, func: callback }); process.nextTick( function() { this._process(); if (this._paused && this._reads && this._reads.length > 0) { this._paused = false; this.emit("drain"); } }.bind(this) ); }; ChunkStream.prototype.write = function(data, encoding) { if (!this.writable) { this.emit("error", new Error("Stream not writable")); return false; } let dataBuffer; if (Buffer.isBuffer(data)) { dataBuffer = data; } else { dataBuffer = Buffer.from(data, encoding || this._encoding); } this._buffers.push(dataBuffer); this._buffered += dataBuffer.length; this._process(); if (this._reads && this._reads.length === 0) { this._paused = true; } return this.writable && !this._paused; }; ChunkStream.prototype.end = function(data, encoding) { if (data) { this.write(data, encoding); } this.writable = false; if (!this._buffers) { return; } if (this._buffers.length === 0) { this._end(); } else { this._buffers.push(null); this._process(); } }; ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; ChunkStream.prototype._end = function() { if (this._reads.length > 0) { this.emit("error", new Error("Unexpected end of input")); } this.destroy(); }; ChunkStream.prototype.destroy = function() { if (!this._buffers) { return; } this.writable = false; this._reads = null; this._buffers = null; this.emit("close"); }; ChunkStream.prototype._processReadAllowingLess = function(read) { this._reads.shift(); let smallerBuf = this._buffers[0]; if (smallerBuf.length > read.length) { this._buffered -= read.length; this._buffers[0] = smallerBuf.slice(read.length); read.func.call(this, smallerBuf.slice(0, read.length)); } else { this._buffered -= smallerBuf.length; this._buffers.shift(); read.func.call(this, smallerBuf); } }; ChunkStream.prototype._processRead = function(read) { this._reads.shift(); let pos = 0; let count = 0; let data = Buffer.alloc(read.length); while (pos < read.length) { let buf = this._buffers[count++]; let len = Math.min(buf.length, read.length - pos); buf.copy(data, pos, 0, len); pos += len; if (len !== buf.length) { this._buffers[--count] = buf.slice(len); } } if (count > 0) { this._buffers.splice(0, count); } this._buffered -= read.length; read.func.call(this, data); }; ChunkStream.prototype._process = function() { try { while (this._buffered > 0 && this._reads && this._reads.length > 0) { let read = this._reads[0]; if (read.allowLess) { this._processReadAllowingLess(read); } else if (this._buffered >= read.length) { this._processRead(read); } else { break; } } if (this._buffers && !this.writable) { this._end(); } } catch (ex) { this.emit("error", ex); } }; } }); // node_modules/pngjs/lib/interlace.js var require_interlace = __commonJS({ "node_modules/pngjs/lib/interlace.js"(exports2) { "use strict"; var imagePasses = [ { // pass 1 - 1px x: [0], y: [0] }, { // pass 2 - 1px x: [4], y: [0] }, { // pass 3 - 2px x: [0, 4], y: [4] }, { // pass 4 - 4px x: [2, 6], y: [0, 4] }, { // pass 5 - 8px x: [0, 2, 4, 6], y: [2, 6] }, { // pass 6 - 16px x: [1, 3, 5, 7], y: [0, 2, 4, 6] }, { // pass 7 - 32px x: [0, 1, 2, 3, 4, 5, 6, 7], y: [1, 3, 5, 7] } ]; exports2.getImagePasses = function(width, height) { let images = []; let xLeftOver = width % 8; let yLeftOver = height % 8; let xRepeats = (width - xLeftOver) / 8; let yRepeats = (height - yLeftOver) / 8; for (let i = 0; i < imagePasses.length; i++) { let pass = imagePasses[i]; let passWidth = xRepeats * pass.x.length; let passHeight = yRepeats * pass.y.length; for (let j = 0; j < pass.x.length; j++) { if (pass.x[j] < xLeftOver) { passWidth++; } else { break; } } for (let j = 0; j < pass.y.length; j++) { if (pass.y[j] < yLeftOver) { passHeight++; } else { break; } } if (passWidth > 0 && passHeight > 0) { images.push({ width: passWidth, height: passHeight, index: i }); } } return images; }; exports2.getInterlaceIterator = function(width) { return function(x, y, pass) { let outerXLeftOver = x % imagePasses[pass].x.length; let outerX = (x - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver]; let outerYLeftOver = y % imagePasses[pass].y.length; let outerY = (y - outerYLeftOver) / imagePasses[pass].y.length * 8 + imagePasses[pass].y[outerYLeftOver]; return outerX * 4 + outerY * width * 4; }; }; } }); // node_modules/pngjs/lib/paeth-predictor.js var require_paeth_predictor = __commonJS({ "node_modules/pngjs/lib/paeth-predictor.js"(exports2, module2) { "use strict"; module2.exports = function paethPredictor(left, above, upLeft) { let paeth = left + above - upLeft; let pLeft = Math.abs(paeth - left); let pAbove = Math.abs(paeth - above); let pUpLeft = Math.abs(paeth - upLeft); if (pLeft <= pAbove && pLeft <= pUpLeft) { return left; } if (pAbove <= pUpLeft) { return above; } return upLeft; }; } }); // node_modules/pngjs/lib/filter-parse.js var require_filter_parse = __commonJS({ "node_modules/pngjs/lib/filter-parse.js"(exports2, module2) { "use strict"; var interlaceUtils = require_interlace(); var paethPredictor = require_paeth_predictor(); function getByteWidth(width, bpp, depth) { let byteWidth = width * bpp; if (depth !== 8) { byteWidth = Math.ceil(byteWidth / (8 / depth)); } return byteWidth; } var Filter = module2.exports = function(bitmapInfo, dependencies) { let width = bitmapInfo.width; let height = bitmapInfo.height; let interlace = bitmapInfo.interlace; let bpp = bitmapInfo.bpp; let depth = bitmapInfo.depth; this.read = dependencies.read; this.write = dependencies.write; this.complete = dependencies.complete; this._imageIndex = 0; this._images = []; if (interlace) { let passes = interlaceUtils.getImagePasses(width, height); for (let i = 0; i < passes.length; i++) { this._images.push({ byteWidth: getByteWidth(passes[i].width, bpp, depth), height: passes[i].height, lineIndex: 0 }); } } else { this._images.push({ byteWidth: getByteWidth(width, bpp, depth), height, lineIndex: 0 }); } if (depth === 8) { this._xComparison = bpp; } else if (depth === 16) { this._xComparison = bpp * 2; } else { this._xComparison = 1; } }; Filter.prototype.start = function() { this.read( this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this) ); }; Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) { let xComparison = this._xComparison; let xBiggerThan = xComparison - 1; for (let x = 0; x < byteWidth; x++) { let rawByte = rawData[1 + x]; let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; unfilteredLine[x] = rawByte + f1Left; } }; Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) { let lastLine = this._lastLine; for (let x = 0; x < byteWidth; x++) { let rawByte = rawData[1 + x]; let f2Up = lastLine ? lastLine[x] : 0; unfilteredLine[x] = rawByte + f2Up; } }; Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) { let xComparison = this._xComparison; let xBiggerThan = xComparison - 1; let lastLine = this._lastLine; for (let x = 0; x < byteWidth; x++) { let rawByte = rawData[1 + x]; let f3Up = lastLine ? lastLine[x] : 0; let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; let f3Add = Math.floor((f3Left + f3Up) / 2); unfilteredLine[x] = rawByte + f3Add; } }; Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) { let xComparison = this._xComparison; let xBiggerThan = xComparison - 1; let lastLine = this._lastLine; for (let x = 0; x < byteWidth; x++) { let rawByte = rawData[1 + x]; let f4Up = lastLine ? lastLine[x] : 0; let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); unfilteredLine[x] = rawByte + f4Add; } }; Filter.prototype._reverseFilterLine = function(rawData) { let filter = rawData[0]; let unfilteredLine; let currentImage = this._images[this._imageIndex]; let byteWidth = currentImage.byteWidth; if (filter === 0) { unfilteredLine = rawData.slice(1, byteWidth + 1); } else { unfilteredLine = Buffer.alloc(byteWidth); switch (filter) { case 1: this._unFilterType1(rawData, unfilteredLine, byteWidth); break; case 2: this._unFilterType2(rawData, unfilteredLine, byteWidth); break; case 3: this._unFilterType3(rawData, unfilteredLine, byteWidth); break; case 4: this._unFilterType4(rawData, unfilteredLine, byteWidth); break; default: throw new Error("Unrecognised filter type - " + filter); } } this.write(unfilteredLine); currentImage.lineIndex++; if (currentImage.lineIndex >= currentImage.height) { this._lastLine = null; this._imageIndex++; currentImage = this._images[this._imageIndex]; } else { this._lastLine = unfilteredLine; } if (currentImage) { this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); } else { this._lastLine = null; this.complete(); } }; } }); // node_modules/pngjs/lib/filter-parse-async.js var require_filter_parse_async = __commonJS({ "node_modules/pngjs/lib/filter-parse-async.js"(exports2, module2) { "use strict"; var util2 = require("util"); var ChunkStream = require_chunkstream(); var Filter = require_filter_parse(); var FilterAsync = module2.exports = function(bitmapInfo) { ChunkStream.call(this); let buffers = []; let that = this; this._filter = new Filter(bitmapInfo, { read: this.read.bind(this), write: function(buffer) { buffers.push(buffer); }, complete: function() { that.emit("complete", Buffer.concat(buffers)); } }); this._filter.start(); }; util2.inherits(FilterAsync, ChunkStream); } }); // node_modules/pngjs/lib/constants.js var require_constants = __commonJS({ "node_modules/pngjs/lib/constants.js"(exports2, module2) { "use strict"; module2.exports = { PNG_SIGNATURE: [137, 80, 78, 71, 13, 10, 26, 10], TYPE_IHDR: 1229472850, TYPE_IEND: 1229278788, TYPE_IDAT: 1229209940, TYPE_PLTE: 1347179589, TYPE_tRNS: 1951551059, // eslint-disable-line camelcase TYPE_gAMA: 1732332865, // eslint-disable-line camelcase // color-type bits COLORTYPE_GRAYSCALE: 0, COLORTYPE_PALETTE: 1, COLORTYPE_COLOR: 2, COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha // color-type combinations COLORTYPE_PALETTE_COLOR: 3, COLORTYPE_COLOR_ALPHA: 6, COLORTYPE_TO_BPP_MAP: { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }, GAMMA_DIVISION: 1e5 }; } }); // node_modules/pngjs/lib/crc.js var require_crc = __commonJS({ "node_modules/pngjs/lib/crc.js"(exports2, module2) { "use strict"; var crcTable = []; (function() { for (let i = 0; i < 256; i++) { let currentCrc = i; for (let j = 0; j < 8; j++) { if (currentCrc & 1) { currentCrc = 3988292384 ^ currentCrc >>> 1; } else { currentCrc = currentCrc >>> 1; } } crcTable[i] = currentCrc; } })(); var CrcCalculator = module2.exports = function() { this._crc = -1; }; CrcCalculator.prototype.write = function(data) { for (let i = 0; i < data.length; i++) { this._crc = crcTable[(this._crc ^ data[i]) & 255] ^ this._crc >>> 8; } return true; }; CrcCalculator.prototype.crc32 = function() { return this._crc ^ -1; }; CrcCalculator.crc32 = function(buf) { let crc = -1; for (let i = 0; i < buf.length; i++) { crc = crcTable[(crc ^ buf[i]) & 255] ^ crc >>> 8; } return crc ^ -1; }; } }); // node_modules/pngjs/lib/parser.js var require_parser = __commonJS({ "node_modules/pngjs/lib/parser.js"(exports2, module2) { "use strict"; var constants = require_constants(); var CrcCalculator = require_crc(); var Parser = module2.exports = function(options, dependencies) { this._options = options; options.checkCRC = options.checkCRC !== false; this._hasIHDR = false; this._hasIEND = false; this._emittedHeadersFinished = false; this._palette = []; this._colorType = 0; this._chunks = {}; this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this); this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this); this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this); this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this); this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this); this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this); this.read = dependencies.read; this.error = dependencies.error; this.metadata = dependencies.metadata; this.gamma = dependencies.gamma; this.transColor = dependencies.transColor; this.palette = dependencies.palette; this.parsed = dependencies.parsed; this.inflateData = dependencies.inflateData; this.finished = dependencies.finished; this.simpleTransparency = dependencies.simpleTransparency; this.headersFinished = dependencies.headersFinished || function() { }; }; Parser.prototype.start = function() { this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this)); }; Parser.prototype._parseSignature = function(data) { let signature = constants.PNG_SIGNATURE; for (let i = 0; i < signature.length; i++) { if (data[i] !== signature[i]) { this.error(new Error("Invalid file signature")); return; } } this.read(8, this._parseChunkBegin.bind(this)); }; Parser.prototype._parseChunkBegin = function(data) { let length = data.readUInt32BE(0); let type = data.readUInt32BE(4); let name = ""; for (let i = 4; i < 8; i++) { name += String.fromCharCode(data[i]); } let ancillary = Boolean(data[4] & 32); if (!this._hasIHDR && type !== constants.TYPE_IHDR) { this.error(new Error("Expected IHDR on beggining")); return; } this._crc = new CrcCalculator(); this._crc.write(Buffer.from(name)); if (this._chunks[type]) { return this._chunks[type](length); } if (!ancillary) { this.error(new Error("Unsupported critical chunk type " + name)); return; } this.read(length + 4, this._skipChunk.bind(this)); }; Parser.prototype._skipChunk = function() { this.read(8, this._parseChunkBegin.bind(this)); }; Parser.prototype._handleChunkEnd = function() { this.read(4, this._parseChunkEnd.bind(this)); }; Parser.prototype._parseChunkEnd = function(data) { let fileCrc = data.readInt32BE(0); let calcCrc = this._crc.crc32(); if (this._options.checkCRC && calcCrc !== fileCrc) { this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); return; } if (!this._hasIEND) { this.read(8, this._parseChunkBegin.bind(this)); } }; Parser.prototype._handleIHDR = function(length) { this.read(length, this._parseIHDR.bind(this)); }; Parser.prototype._parseIHDR = function(data) { this._crc.write(data); let width = data.readUInt32BE(0); let height = data.readUInt32BE(4); let depth = data[8]; let colorType = data[9]; let compr = data[10]; let filter = data[11]; let interlace = data[12]; if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) { this.error(new Error("Unsupported bit depth " + depth)); return; } if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) { this.error(new Error("Unsupported color type")); return; } if (compr !== 0) { this.error(new Error("Unsupported compression method")); return; } if (filter !== 0) { this.error(new Error("Unsupported filter method")); return; } if (interlace !== 0 && interlace !== 1) { this.error(new Error("Unsupported interlace method")); return; } this._colorType = colorType; let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; this._hasIHDR = true; this.metadata({ width, height, depth, interlace: Boolean(interlace), palette: Boolean(colorType & constants.COLORTYPE_PALETTE), color: Boolean(colorType & constants.COLORTYPE_COLOR), alpha: Boolean(colorType & constants.COLORTYPE_ALPHA), bpp, colorType }); this._handleChunkEnd(); }; Parser.prototype._handlePLTE = function(length) { this.read(length, this._parsePLTE.bind(this)); }; Parser.prototype._parsePLTE = function(data) { this._crc.write(data); let entries = Math.floor(data.length / 3); for (let i = 0; i < entries; i++) { this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 255]); } this.palette(this._palette); this._handleChunkEnd(); }; Parser.prototype._handleTRNS = function(length) { this.simpleTransparency(); this.read(length, this._parseTRNS.bind(this)); }; Parser.prototype._parseTRNS = function(data) { this._crc.write(data); if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) { if (this._palette.length === 0) { this.error(new Error("Transparency chunk must be after palette")); return; } if (data.length > this._palette.length) { this.error(new Error("More transparent colors than palette size")); return; } for (let i = 0; i < data.length; i++) { this._palette[i][3] = data[i]; } this.palette(this._palette); } if (this._colorType === constants.COLORTYPE_GRAYSCALE) { this.transColor([data.readUInt16BE(0)]); } if (this._colorType === constants.COLORTYPE_COLOR) { this.transColor([ data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4) ]); } this._handleChunkEnd(); }; Parser.prototype._handleGAMA = function(length) { this.read(length, this._parseGAMA.bind(this)); }; Parser.prototype._parseGAMA = function(data) { this._crc.write(data); this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); this._handleChunkEnd(); }; Parser.prototype._handleIDAT = function(length) { if (!this._emittedHeadersFinished) { this._emittedHeadersFinished = true; this.headersFinished(); } this.read(-length, this._parseIDAT.bind(this, length)); }; Parser.prototype._parseIDAT = function(length, data) { this._crc.write(data); if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) { throw new Error("Expected palette not found"); } this.inflateData(data); let leftOverLength = length - data.length; if (leftOverLength > 0) { this._handleIDAT(leftOverLength); } else { this._handleChunkEnd(); } }; Parser.prototype._handleIEND = function(length) { this.read(length, this._parseIEND.bind(this)); }; Parser.prototype._parseIEND = function(data) { this._crc.write(data); this._hasIEND = true; this._handleChunkEnd(); if (this.finished) { this.finished(); } }; } }); // node_modules/pngjs/lib/bitmapper.js var require_bitmapper = __commonJS({ "node_modules/pngjs/lib/bitmapper.js"(exports2) { "use strict"; var interlaceUtils = require_interlace(); var pixelBppMapper = [ // 0 - dummy entry function() { }, // 1 - L // 0: 0, 1: 0, 2: 0, 3: 0xff function(pxData, data, pxPos, rawPos) { if (rawPos === data.length) { throw new Error("Ran out of data"); } let pixel = data[rawPos]; pxData[pxPos] = pixel; pxData[pxPos + 1] = pixel; pxData[pxPos + 2] = pixel; pxData[pxPos + 3] = 255; }, // 2 - LA // 0: 0, 1: 0, 2: 0, 3: 1 function(pxData, data, pxPos, rawPos) { if (rawPos + 1 >= data.length) { throw new Error("Ran out of data"); } let pixel = data[rawPos]; pxData[pxPos] = pixel; pxData[pxPos + 1] = pixel; pxData[pxPos + 2] = pixel; pxData[pxPos + 3] = data[rawPos + 1]; }, // 3 - RGB // 0: 0, 1: 1, 2: 2, 3: 0xff function(pxData, data, pxPos, rawPos) { if (rawPos + 2 >= data.length) { throw new Error("Ran out of data"); } pxData[pxPos] = data[rawPos]; pxData[pxPos + 1] = data[rawPos + 1]; pxData[pxPos + 2] = data[rawPos + 2]; pxData[pxPos + 3] = 255; }, // 4 - RGBA // 0: 0, 1: 1, 2: 2, 3: 3 function(pxData, data, pxPos, rawPos) { if (rawPos + 3 >= data.length) { throw new Error("Ran out of data"); } pxData[pxPos] = data[rawPos]; pxData[pxPos + 1] = data[rawPos + 1]; pxData[pxPos + 2] = data[rawPos + 2]; pxData[pxPos + 3] = data[rawPos + 3]; } ]; var pixelBppCustomMapper = [ // 0 - dummy entry function() { }, // 1 - L // 0: 0, 1: 0, 2: 0, 3: 0xff function(pxData, pixelData, pxPos, maxBit) { let pixel = pixelData[0]; pxData[pxPos] = pixel; pxData[pxPos + 1] = pixel; pxData[pxPos + 2] = pixel; pxData[pxPos + 3] = maxBit; }, // 2 - LA // 0: 0, 1: 0, 2: 0, 3: 1 function(pxData, pixelData, pxPos) { let pixel = pixelData[0]; pxData[pxPos] = pixel; pxData[pxPos + 1] = pixel; pxData[pxPos + 2] = pixel; pxData[pxPos + 3] = pixelData[1]; }, // 3 - RGB // 0: 0, 1: 1, 2: 2, 3: 0xff function(pxData, pixelData, pxPos, maxBit) { pxData[pxPos] = pixelData[0]; pxData[pxPos + 1] = pixelData[1]; pxData[pxPos + 2] = pixelData[2]; pxData[pxPos + 3] = maxBit; }, // 4 - RGBA // 0: 0, 1: 1, 2: 2, 3: 3 function(pxData, pixelData, pxPos) { pxData[pxPos] = pixelData[0]; pxData[pxPos + 1] = pixelData[1]; pxData[pxPos + 2] = pixelData[2]; pxData[pxPos + 3] = pixelData[3]; } ]; function bitRetriever(data, depth) { let leftOver = []; let i = 0; function split() { if (i === data.length) { throw new Error("Ran out of data"); } let byte = data[i]; i++; let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; switch (depth) { default: throw new Error("unrecognised depth"); case 16: byte2 = data[i]; i++; leftOver.push((byte << 8) + byte2); break; case 4: byte2 = byte & 15; byte1 = byte >> 4; leftOver.push(byte1, byte2); break; case 2: byte4 = byte & 3; byte3 = byte >> 2 & 3; byte2 = byte >> 4 & 3; byte1 = byte >> 6 & 3; leftOver.push(byte1, byte2, byte3, byte4); break; case 1: byte8 = byte & 1; byte7 = byte >> 1 & 1; byte6 = byte >> 2 & 1; byte5 = byte >> 3 & 1; byte4 = byte >> 4 & 1; byte3 = byte >> 5 & 1; byte2 = byte >> 6 & 1; byte1 = byte >> 7 & 1; leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); break; } } return { get: function(count) { while (leftOver.length < count) { split(); } let returner = leftOver.slice(0, count); leftOver = leftOver.slice(count); return returner; }, resetAfterLine: function() { leftOver.length = 0; }, end: function() { if (i !== data.length) { throw new Error("extra data found"); } } }; } function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { let imageWidth = image.width; let imageHeight = image.height; let imagePass = image.index; for (let y = 0; y < imageHeight; y++) { for (let x = 0; x < imageWidth; x++) { let pxPos = getPxPos(x, y, imagePass); pixelBppMapper[bpp](pxData, data, pxPos, rawPos); rawPos += bpp; } } return rawPos; } function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { let imageWidth = image.width; let imageHeight = image.height; let imagePass = image.index; for (let y = 0; y < imageHeight; y++) { for (let x = 0; x < imageWidth; x++) { let pixelData = bits.get(bpp); let pxPos = getPxPos(x, y, imagePass); pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); } bits.resetAfterLine(); } } exports2.dataToBitMap = function(data, bitmapInfo) { let width = bitmapInfo.width; let height = bitmapInfo.height; let depth = bitmapInfo.depth; let bpp = bitmapInfo.bpp; let interlace = bitmapInfo.interlace; let bits; if (depth !== 8) { bits = bitRetriever(data, depth); } let pxData; if (depth <= 8) { pxData = Buffer.alloc(width * height * 4); } else { pxData = new Uint16Array(width * height * 4); } let maxBit = Math.pow(2, depth) - 1; let rawPos = 0; let images; let getPxPos; if (interlace) { images = interlaceUtils.getImagePasses(width, height); getPxPos = interlaceUtils.getInterlaceIterator(width, height); } else { let nonInterlacedPxPos = 0; getPxPos = function() { let returner = nonInterlacedPxPos; nonInterlacedPxPos += 4; return returner; }; images = [{ width, height }]; } for (let imageIndex = 0; imageIndex < images.length; imageIndex++) { if (depth === 8) { rawPos = mapImage8Bit( images[imageIndex], pxData, getPxPos, bpp, data, rawPos ); } else { mapImageCustomBit( images[imageIndex], pxData, getPxPos, bpp, bits, maxBit ); } } if (depth === 8) { if (rawPos !== data.length) { throw new Error("extra data found"); } } else { bits.end(); } return pxData; }; } }); // node_modules/pngjs/lib/format-normaliser.js var require_format_normaliser = __commonJS({ "node_modules/pngjs/lib/format-normaliser.js"(exports2, module2) { "use strict"; function dePalette(indata, outdata, width, height, palette) { let pxPos = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let color = palette[indata[pxPos]]; if (!color) { throw new Error("index " + indata[pxPos] + " not in palette"); } for (let i = 0; i < 4; i++) { outdata[pxPos + i] = color[i]; } pxPos += 4; } } } function replaceTransparentColor(indata, outdata, width, height, transColor) { let pxPos = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let makeTrans = false; if (transColor.length === 1) { if (transColor[0] === indata[pxPos]) { makeTrans = true; } } else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) { makeTrans = true; } if (makeTrans) { for (let i = 0; i < 4; i++) { outdata[pxPos + i] = 0; } } pxPos += 4; } } } function scaleDepth(indata, outdata, width, height, depth) { let maxOutSample = 255; let maxInSample = Math.pow(2, depth) - 1; let pxPos = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { for (let i = 0; i < 4; i++) { outdata[pxPos + i] = Math.floor( indata[pxPos + i] * maxOutSample / maxInSample + 0.5 ); } pxPos += 4; } } } module2.exports = function(indata, imageData, skipRescale = false) { let depth = imageData.depth; let width = imageData.width; let height = imageData.height; let colorType = imageData.colorType; let transColor = imageData.transColor; let palette = imageData.palette; let outdata = indata; if (colorType === 3) { dePalette(indata, outdata, width, height, palette); } else { if (transColor) { replaceTransparentColor(indata, outdata, width, height, transColor); } if (depth !== 8 && !skipRescale) { if (depth === 16) { outdata = Buffer.alloc(width * height * 4); } scaleDepth(indata, outdata, width, height, depth); } } return outdata; }; } }); // node_modules/pngjs/lib/parser-async.js var require_parser_async = __commonJS({ "node_modules/pngjs/lib/parser-async.js"(exports2, module2) { "use strict"; var util2 = require("util"); var zlib = require("zlib"); var ChunkStream = require_chunkstream(); var FilterAsync = require_filter_parse_async(); var Parser = require_parser(); var bitmapper = require_bitmapper(); var formatNormaliser = require_format_normaliser(); var ParserAsync = module2.exports = function(options) { ChunkStream.call(this); this._parser = new Parser(options, { read: this.read.bind(this), error: this._handleError.bind(this), metadata: this._handleMetaData.bind(this), gamma: this.emit.bind(this, "gamma"), palette: this._handlePalette.bind(this), transColor: this._handleTransColor.bind(this), finished: this._finished.bind(this), inflateData: this._inflateData.bind(this), simpleTransparency: this._simpleTransparency.bind(this), headersFinished: this._headersFinished.bind(this) }); this._options = options; this.writable = true; this._parser.start(); }; util2.inherits(ParserAsync, ChunkStream); ParserAsync.prototype._handleError = function(err) { this.emit("error", err); this.writable = false; this.destroy(); if (this._inflate && this._inflate.destroy) { this._inflate.destroy(); } if (this._filter) { this._filter.destroy(); this._filter.on("error", function() { }); } this.errord = true; }; ParserAsync.prototype._inflateData = function(data) { if (!this._inflate) { if (this._bitmapInfo.interlace) { this._inflate = zlib.createInflate(); this._inflate.on("error", this.emit.bind(this, "error")); this._filter.on("complete", this._complete.bind(this)); this._inflate.pipe(this._filter); } else { let rowSize = (this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7 >> 3) + 1; let imageSize = rowSize * this._bitmapInfo.height; let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); this._inflate = zlib.createInflate({ chunkSize }); let leftToInflate = imageSize; let emitError = this.emit.bind(this, "error"); this._inflate.on("error", function(err) { if (!leftToInflate) { return; } emitError(err); }); this._filter.on("complete", this._complete.bind(this)); let filterWrite = this._filter.write.bind(this._filter); this._inflate.on("data", function(chunk) { if (!leftToInflate) { return; } if (chunk.length > leftToInflate) { chunk = chunk.slice(0, leftToInflate); } leftToInflate -= chunk.length; filterWrite(chunk); }); this._inflate.on("end", this._filter.end.bind(this._filter)); } } this._inflate.write(data); }; ParserAsync.prototype._handleMetaData = function(metaData) { this._metaData = metaData; this._bitmapInfo = Object.create(metaData); this._filter = new FilterAsync(this._bitmapInfo); }; ParserAsync.prototype._handleTransColor = function(transColor) { this._bitmapInfo.transColor = transColor; }; ParserAsync.prototype._handlePalette = function(palette) { this._bitmapInfo.palette = palette; }; ParserAsync.prototype._simpleTransparency = function() { this._metaData.alpha = true; }; ParserAsync.prototype._headersFinished = function() { this.emit("metadata", this._metaData); }; ParserAsync.prototype._finished = function() { if (this.errord) { return; } if (!this._inflate) { this.emit("error", "No Inflate block"); } else { this._inflate.end(); } }; ParserAsync.prototype._complete = function(filteredData) { if (this.errord) { return; } let normalisedBitmapData; try { let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); normalisedBitmapData = formatNormaliser( bitmapData, this._bitmapInfo, this._options.skipRescale ); bitmapData = null; } catch (ex) { this._handleError(ex); return; } this.emit("parsed", normalisedBitmapData); }; } }); // node_modules/pngjs/lib/bitpacker.js var require_bitpacker = __commonJS({ "node_modules/pngjs/lib/bitpacker.js"(exports2, module2) { "use strict"; var constants = require_constants(); module2.exports = function(dataIn, width, height, options) { let outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf( options.colorType ) !== -1; if (options.colorType === options.inputColorType) { let bigEndian = (function() { let buffer = new ArrayBuffer(2); new DataView(buffer).setInt16( 0, 256, true /* littleEndian */ ); return new Int16Array(buffer)[0] !== 256; })(); if (options.bitDepth === 8 || options.bitDepth === 16 && bigEndian) { return dataIn; } } let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); let maxValue = 255; let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; if (inBpp === 4 && !options.inputHasAlpha) { inBpp = 3; } let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; if (options.bitDepth === 16) { maxValue = 65535; outBpp *= 2; } let outData = Buffer.alloc(width * height * outBpp); let inIndex = 0; let outIndex = 0; let bgColor = options.bgColor || {}; if (bgColor.red === void 0) { bgColor.red = maxValue; } if (bgColor.green === void 0) { bgColor.green = maxValue; } if (bgColor.blue === void 0) { bgColor.blue = maxValue; } function getRGBA() { let red; let green; let blue; let alpha = maxValue; switch (options.inputColorType) { case constants.COLORTYPE_COLOR_ALPHA: alpha = data[inIndex + 3]; red = data[inIndex]; green = data[inIndex + 1]; blue = data[inIndex + 2]; break; case constants.COLORTYPE_COLOR: red = data[inIndex]; green = data[inIndex + 1]; blue = data[inIndex + 2]; break; case constants.COLORTYPE_ALPHA: alpha = data[inIndex + 1]; red = data[inIndex]; green = red; blue = red; break; case constants.COLORTYPE_GRAYSCALE: red = data[inIndex]; green = red; blue = red; break; default: throw new Error( "input color type:" + options.inputColorType + " is not supported at present" ); } if (options.inputHasAlpha) { if (!outHasAlpha) { alpha /= maxValue; red = Math.min( Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue ); green = Math.min( Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue ); blue = Math.min( Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue ); } } return { red, green, blue, alpha }; } for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let rgba = getRGBA(data, inIndex); switch (options.colorType) { case constants.COLORTYPE_COLOR_ALPHA: case constants.COLORTYPE_COLOR: if (options.bitDepth === 8) { outData[outIndex] = rgba.red; outData[outIndex + 1] = rgba.green; outData[outIndex + 2] = rgba.blue; if (outHasAlpha) { outData[outIndex + 3] = rgba.alpha; } } else { outData.writeUInt16BE(rgba.red, outIndex); outData.writeUInt16BE(rgba.green, outIndex + 2); outData.writeUInt16BE(rgba.blue, outIndex + 4); if (outHasAlpha) { outData.writeUInt16BE(rgba.alpha, outIndex + 6); } } break; case constants.COLORTYPE_ALPHA: case constants.COLORTYPE_GRAYSCALE: { let grayscale = (rgba.red + rgba.green + rgba.blue) / 3; if (options.bitDepth === 8) { outData[outIndex] = grayscale; if (outHasAlpha) { outData[outIndex + 1] = rgba.alpha; } } else { outData.writeUInt16BE(grayscale, outIndex); if (outHasAlpha) { outData.writeUInt16BE(rgba.alpha, outIndex + 2); } } break; } default: throw new Error("unrecognised color Type " + options.colorType); } inIndex += inBpp; outIndex += outBpp; } } return outData; }; } }); // node_modules/pngjs/lib/filter-pack.js var require_filter_pack = __commonJS({ "node_modules/pngjs/lib/filter-pack.js"(exports2, module2) { "use strict"; var paethPredictor = require_paeth_predictor(); function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { for (let x = 0; x < byteWidth; x++) { rawData[rawPos + x] = pxData[pxPos + x]; } } function filterSumNone(pxData, pxPos, byteWidth) { let sum = 0; let length = pxPos + byteWidth; for (let i = pxPos; i < length; i++) { sum += Math.abs(pxData[i]); } return sum; } function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { for (let x = 0; x < byteWidth; x++) { let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; let val = pxData[pxPos + x] - left; rawData[rawPos + x] = val; } } function filterSumSub(pxData, pxPos, byteWidth, bpp) { let sum = 0; for (let x = 0; x < byteWidth; x++) { let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; let val = pxData[pxPos + x] - left; sum += Math.abs(val); } return sum; } function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { for (let x = 0; x < byteWidth; x++) { let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; let val = pxData[pxPos + x] - up; rawData[rawPos + x] = val; } } function filterSumUp(pxData, pxPos, byteWidth) { let sum = 0; let length = pxPos + byteWidth; for (let x = pxPos; x < length; x++) { let up = pxPos > 0 ? pxData[x - byteWidth] : 0; let val = pxData[x] - up; sum += Math.abs(val); } return sum; } function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { for (let x = 0; x < byteWidth; x++) { let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; let val = pxData[pxPos + x] - (left + up >> 1); rawData[rawPos + x] = val; } } function filterSumAvg(pxData, pxPos, byteWidth, bpp) { let sum = 0; for (let x = 0; x < byteWidth; x++) { let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; let val = pxData[pxPos + x] - (left + up >> 1); sum += Math.abs(val); } return sum; } function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { for (let x = 0; x < byteWidth; x++) { let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); rawData[rawPos + x] = val; } } function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { let sum = 0; for (let x = 0; x < byteWidth; x++) { let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; let upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); sum += Math.abs(val); } return sum; } var filters = { 0: filterNone, 1: filterSub, 2: filterUp, 3: filterAvg, 4: filterPaeth }; var filterSums = { 0: filterSumNone, 1: filterSumSub, 2: filterSumUp, 3: filterSumAvg, 4: filterSumPaeth }; module2.exports = function(pxData, width, height, options, bpp) { let filterTypes; if (!("filterType" in options) || options.filterType === -1) { filterTypes = [0, 1, 2, 3, 4]; } else if (typeof options.filterType === "number") { filterTypes = [options.filterType]; } else { throw new Error("unrecognised filter types"); } if (options.bitDepth === 16) { bpp *= 2; } let byteWidth = width * bpp; let rawPos = 0; let pxPos = 0; let rawData = Buffer.alloc((byteWidth + 1) * height); let sel = filterTypes[0]; for (let y = 0; y < height; y++) { if (filterTypes.length > 1) { let min = Infinity; for (let i = 0; i < filterTypes.length; i++) { let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); if (sum < min) { sel = filterTypes[i]; min = sum; } } } rawData[rawPos] = sel; rawPos++; filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); rawPos += byteWidth; pxPos += byteWidth; } return rawData; }; } }); // node_modules/pngjs/lib/packer.js var require_packer = __commonJS({ "node_modules/pngjs/lib/packer.js"(exports2, module2) { "use strict"; var constants = require_constants(); var CrcStream = require_crc(); var bitPacker = require_bitpacker(); var filter = require_filter_pack(); var zlib = require("zlib"); var Packer = module2.exports = function(options) { this._options = options; options.deflateChunkSize = options.deflateChunkSize || 32 * 1024; options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9; options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3; options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true; options.deflateFactory = options.deflateFactory || zlib.createDeflate; options.bitDepth = options.bitDepth || 8; options.colorType = typeof options.colorType === "number" ? options.colorType : constants.COLORTYPE_COLOR_ALPHA; options.inputColorType = typeof options.inputColorType === "number" ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA; if ([ constants.COLORTYPE_GRAYSCALE, constants.COLORTYPE_COLOR, constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA ].indexOf(options.colorType) === -1) { throw new Error( "option color type:" + options.colorType + " is not supported at present" ); } if ([ constants.COLORTYPE_GRAYSCALE, constants.COLORTYPE_COLOR, constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA ].indexOf(options.inputColorType) === -1) { throw new Error( "option input color type:" + options.inputColorType + " is not supported at present" ); } if (options.bitDepth !== 8 && options.bitDepth !== 16) { throw new Error( "option bit depth:" + options.bitDepth + " is not supported at present" ); } }; Packer.prototype.getDeflateOptions = function() { return { chunkSize: this._options.deflateChunkSize, level: this._options.deflateLevel, strategy: this._options.deflateStrategy }; }; Packer.prototype.createDeflate = function() { return this._options.deflateFactory(this.getDeflateOptions()); }; Packer.prototype.filterData = function(data, width, height) { let packedData = bitPacker(data, width, height, this._options); let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; let filteredData = filter(packedData, width, height, this._options, bpp); return filteredData; }; Packer.prototype._packChunk = function(type, data) { let len = data ? data.length : 0; let buf = Buffer.alloc(len + 12); buf.writeUInt32BE(len, 0); buf.writeUInt32BE(type, 4); if (data) { data.copy(buf, 8); } buf.writeInt32BE( CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4 ); return buf; }; Packer.prototype.packGAMA = function(gamma) { let buf = Buffer.alloc(4); buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); return this._packChunk(constants.TYPE_gAMA, buf); }; Packer.prototype.packIHDR = function(width, height) { let buf = Buffer.alloc(13); buf.writeUInt32BE(width, 0); buf.writeUInt32BE(height, 4); buf[8] = this._options.bitDepth; buf[9] = this._options.colorType; buf[10] = 0; buf[11] = 0; buf[12] = 0; return this._packChunk(constants.TYPE_IHDR, buf); }; Packer.prototype.packIDAT = function(data) { return this._packChunk(constants.TYPE_IDAT, data); }; Packer.prototype.packIEND = function() { return this._packChunk(constants.TYPE_IEND, null); }; } }); // node_modules/pngjs/lib/packer-async.js var require_packer_async = __commonJS({ "node_modules/pngjs/lib/packer-async.js"(exports2, module2) { "use strict"; var util2 = require("util"); var Stream = require("stream"); var constants = require_constants(); var Packer = require_packer(); var PackerAsync = module2.exports = function(opt) { Stream.call(this); let options = opt || {}; this._packer = new Packer(options); this._deflate = this._packer.createDeflate(); this.readable = true; }; util2.inherits(PackerAsync, Stream); PackerAsync.prototype.pack = function(data, width, height, gamma) { this.emit("data", Buffer.from(constants.PNG_SIGNATURE)); this.emit("data", this._packer.packIHDR(width, height)); if (gamma) { this.emit("data", this._packer.packGAMA(gamma)); } let filteredData = this._packer.filterData(data, width, height); this._deflate.on("error", this.emit.bind(this, "error")); this._deflate.on( "data", function(compressedData) { this.emit("data", this._packer.packIDAT(compressedData)); }.bind(this) ); this._deflate.on( "end", function() { this.emit("data", this._packer.packIEND()); this.emit("end"); }.bind(this) ); this._deflate.end(filteredData); }; } }); // node_modules/pngjs/lib/sync-inflate.js var require_sync_inflate = __commonJS({ "node_modules/pngjs/lib/sync-inflate.js"(exports2, module2) { "use strict"; var assert2 = require("assert").ok; var zlib = require("zlib"); var util2 = require("util"); var kMaxLength = require("buffer").kMaxLength; function Inflate(opts) { if (!(this instanceof Inflate)) { return new Inflate(opts); } if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { opts.chunkSize = zlib.Z_MIN_CHUNK; } zlib.Inflate.call(this, opts); this._offset = this._offset === void 0 ? this._outOffset : this._offset; this._buffer = this._buffer || this._outBuffer; if (opts && opts.maxLength != null) { this._maxLength = opts.maxLength; } } function createInflate(opts) { return new Inflate(opts); } function _close(engine, callback) { if (callback) { process.nextTick(callback); } if (!engine._handle) { return; } engine._handle.close(); engine._handle = null; } Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) { if (typeof asyncCb === "function") { return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); } let self = this; let availInBefore = chunk && chunk.length; let availOutBefore = this._chunkSize - this._offset; let leftToInflate = this._maxLength; let inOff = 0; let buffers = []; let nread = 0; let error48; this.on("error", function(err) { error48 = err; }); function handleChunk(availInAfter, availOutAfter) { if (self._hadError) { return; } let have = availOutBefore - availOutAfter; assert2(have >= 0, "have should not go down"); if (have > 0) { let out = self._buffer.slice(self._offset, self._offset + have); self._offset += have; if (out.length > leftToInflate) { out = out.slice(0, leftToInflate); } buffers.push(out); nread += out.length; leftToInflate -= out.length; if (leftToInflate === 0) { return false; } } if (availOutAfter === 0 || self._offset >= self._chunkSize) { availOutBefore = self._chunkSize; self._offset = 0; self._buffer = Buffer.allocUnsafe(self._chunkSize); } if (availOutAfter === 0) { inOff += availInBefore - availInAfter; availInBefore = availInAfter; return true; } return false; } assert2(this._handle, "zlib binding closed"); let res; do { res = this._handle.writeSync( flushFlag, chunk, // in inOff, // in_off availInBefore, // in_len this._buffer, // out this._offset, //out_off availOutBefore ); res = res || this._writeState; } while (!this._hadError && handleChunk(res[0], res[1])); if (this._hadError) { throw error48; } if (nread >= kMaxLength) { _close(this); throw new RangeError( "Cannot create final Buffer. It would be larger than 0x" + kMaxLength.toString(16) + " bytes" ); } let buf = Buffer.concat(buffers, nread); _close(this); return buf; }; util2.inherits(Inflate, zlib.Inflate); function zlibBufferSync(engine, buffer) { if (typeof buffer === "string") { buffer = Buffer.from(buffer); } if (!(buffer instanceof Buffer)) { throw new TypeError("Not a string or buffer"); } let flushFlag = engine._finishFlushFlag; if (flushFlag == null) { flushFlag = zlib.Z_FINISH; } return engine._processChunk(buffer, flushFlag); } function inflateSync(buffer, opts) { return zlibBufferSync(new Inflate(opts), buffer); } module2.exports = exports2 = inflateSync; exports2.Inflate = Inflate; exports2.createInflate = createInflate; exports2.inflateSync = inflateSync; } }); // node_modules/pngjs/lib/sync-reader.js var require_sync_reader = __commonJS({ "node_modules/pngjs/lib/sync-reader.js"(exports2, module2) { "use strict"; var SyncReader = module2.exports = function(buffer) { this._buffer = buffer; this._reads = []; }; SyncReader.prototype.read = function(length, callback) { this._reads.push({ length: Math.abs(length), // if length < 0 then at most this length allowLess: length < 0, func: callback }); }; SyncReader.prototype.process = function() { while (this._reads.length > 0 && this._buffer.length) { let read = this._reads[0]; if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) { this._reads.shift(); let buf = this._buffer; this._buffer = buf.slice(read.length); read.func.call(this, buf.slice(0, read.length)); } else { break; } } if (this._reads.length > 0) { throw new Error("There are some read requests waitng on finished stream"); } if (this._buffer.length > 0) { throw new Error("unrecognised content at end of stream"); } }; } }); // node_modules/pngjs/lib/filter-parse-sync.js var require_filter_parse_sync = __commonJS({ "node_modules/pngjs/lib/filter-parse-sync.js"(exports2) { "use strict"; var SyncReader = require_sync_reader(); var Filter = require_filter_parse(); exports2.process = function(inBuffer, bitmapInfo) { let outBuffers = []; let reader = new SyncReader(inBuffer); let filter = new Filter(bitmapInfo, { read: reader.read.bind(reader), write: function(bufferPart) { outBuffers.push(bufferPart); }, complete: function() { } }); filter.start(); reader.process(); return Buffer.concat(outBuffers); }; } }); // node_modules/pngjs/lib/parser-sync.js var require_parser_sync = __commonJS({ "node_modules/pngjs/lib/parser-sync.js"(exports2, module2) { "use strict"; var hasSyncZlib = true; var zlib = require("zlib"); var inflateSync = require_sync_inflate(); if (!zlib.deflateSync) { hasSyncZlib = false; } var SyncReader = require_sync_reader(); var FilterSync = require_filter_parse_sync(); var Parser = require_parser(); var bitmapper = require_bitmapper(); var formatNormaliser = require_format_normaliser(); module2.exports = function(buffer, options) { if (!hasSyncZlib) { throw new Error( "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" ); } let err; function handleError(_err_) { err = _err_; } let metaData; function handleMetaData(_metaData_) { metaData = _metaData_; } function handleTransColor(transColor) { metaData.transColor = transColor; } function handlePalette(palette) { metaData.palette = palette; } function handleSimpleTransparency() { metaData.alpha = true; } let gamma; function handleGamma(_gamma_) { gamma = _gamma_; } let inflateDataList = []; function handleInflateData(inflatedData2) { inflateDataList.push(inflatedData2); } let reader = new SyncReader(buffer); let parser = new Parser(options, { read: reader.read.bind(reader), error: handleError, metadata: handleMetaData, gamma: handleGamma, palette: handlePalette, transColor: handleTransColor, inflateData: handleInflateData, simpleTransparency: handleSimpleTransparency }); parser.start(); reader.process(); if (err) { throw err; } let inflateData = Buffer.concat(inflateDataList); inflateDataList.length = 0; let inflatedData; if (metaData.interlace) { inflatedData = zlib.inflateSync(inflateData); } else { let rowSize = (metaData.width * metaData.bpp * metaData.depth + 7 >> 3) + 1; let imageSize = rowSize * metaData.height; inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize }); } inflateData = null; if (!inflatedData || !inflatedData.length) { throw new Error("bad png - invalid inflate data response"); } let unfilteredData = FilterSync.process(inflatedData, metaData); inflateData = null; let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); unfilteredData = null; let normalisedBitmapData = formatNormaliser( bitmapData, metaData, options.skipRescale ); metaData.data = normalisedBitmapData; metaData.gamma = gamma || 0; return metaData; }; } }); // node_modules/pngjs/lib/packer-sync.js var require_packer_sync = __commonJS({ "node_modules/pngjs/lib/packer-sync.js"(exports2, module2) { "use strict"; var hasSyncZlib = true; var zlib = require("zlib"); if (!zlib.deflateSync) { hasSyncZlib = false; } var constants = require_constants(); var Packer = require_packer(); module2.exports = function(metaData, opt) { if (!hasSyncZlib) { throw new Error( "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" ); } let options = opt || {}; let packer = new Packer(options); let chunks = []; chunks.push(Buffer.from(constants.PNG_SIGNATURE)); chunks.push(packer.packIHDR(metaData.width, metaData.height)); if (metaData.gamma) { chunks.push(packer.packGAMA(metaData.gamma)); } let filteredData = packer.filterData( metaData.data, metaData.width, metaData.height ); let compressedData = zlib.deflateSync( filteredData, packer.getDeflateOptions() ); filteredData = null; if (!compressedData || !compressedData.length) { throw new Error("bad png - invalid compressed data response"); } chunks.push(packer.packIDAT(compressedData)); chunks.push(packer.packIEND()); return Buffer.concat(chunks); }; } }); // node_modules/pngjs/lib/png-sync.js var require_png_sync = __commonJS({ "node_modules/pngjs/lib/png-sync.js"(exports2) { "use strict"; var parse3 = require_parser_sync(); var pack = require_packer_sync(); exports2.read = function(buffer, options) { return parse3(buffer, options || {}); }; exports2.write = function(png, options) { return pack(png, options); }; } }); // node_modules/pngjs/lib/png.js var require_png = __commonJS({ "node_modules/pngjs/lib/png.js"(exports2) { "use strict"; var util2 = require("util"); var Stream = require("stream"); var Parser = require_parser_async(); var Packer = require_packer_async(); var PNGSync = require_png_sync(); var PNG2 = exports2.PNG = function(options) { Stream.call(this); options = options || {}; this.width = options.width | 0; this.height = options.height | 0; this.data = this.width > 0 && this.height > 0 ? Buffer.alloc(4 * this.width * this.height) : null; if (options.fill && this.data) { this.data.fill(0); } this.gamma = 0; this.readable = this.writable = true; this._parser = new Parser(options); this._parser.on("error", this.emit.bind(this, "error")); this._parser.on("close", this._handleClose.bind(this)); this._parser.on("metadata", this._metadata.bind(this)); this._parser.on("gamma", this._gamma.bind(this)); this._parser.on( "parsed", function(data) { this.data = data; this.emit("parsed", data); }.bind(this) ); this._packer = new Packer(options); this._packer.on("data", this.emit.bind(this, "data")); this._packer.on("end", this.emit.bind(this, "end")); this._parser.on("close", this._handleClose.bind(this)); this._packer.on("error", this.emit.bind(this, "error")); }; util2.inherits(PNG2, Stream); PNG2.sync = PNGSync; PNG2.prototype.pack = function() { if (!this.data || !this.data.length) { this.emit("error", "No data provided"); return this; } process.nextTick( function() { this._packer.pack(this.data, this.width, this.height, this.gamma); }.bind(this) ); return this; }; PNG2.prototype.parse = function(data, callback) { if (callback) { let onParsed, onError; onParsed = function(parsedData) { this.removeListener("error", onError); this.data = parsedData; callback(null, this); }.bind(this); onError = function(err) { this.removeListener("parsed", onParsed); callback(err, null); }.bind(this); this.once("parsed", onParsed); this.once("error", onError); } this.end(data); return this; }; PNG2.prototype.write = function(data) { this._parser.write(data); return true; }; PNG2.prototype.end = function(data) { this._parser.end(data); }; PNG2.prototype._metadata = function(metadata) { this.width = metadata.width; this.height = metadata.height; this.emit("metadata", metadata); }; PNG2.prototype._gamma = function(gamma) { this.gamma = gamma; }; PNG2.prototype._handleClose = function() { if (!this._parser.writable && !this._packer.readable) { this.emit("close"); } }; PNG2.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { srcX |= 0; srcY |= 0; width |= 0; height |= 0; deltaX |= 0; deltaY |= 0; if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) { throw new Error("bitblt reading outside image"); } if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) { throw new Error("bitblt writing outside image"); } for (let y = 0; y < height; y++) { src.data.copy( dst.data, (deltaY + y) * dst.width + deltaX << 2, (srcY + y) * src.width + srcX << 2, (srcY + y) * src.width + srcX + width << 2 ); } }; PNG2.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { PNG2.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); return this; }; PNG2.adjustGamma = function(src) { if (src.gamma) { for (let y = 0; y < src.height; y++) { for (let x = 0; x < src.width; x++) { let idx = src.width * y + x << 2; for (let i = 0; i < 3; i++) { let sample = src.data[idx + i] / 255; sample = Math.pow(sample, 1 / 2.2 / src.gamma); src.data[idx + i] = Math.round(sample * 255); } } } src.gamma = 0; } }; PNG2.prototype.adjustGamma = function() { PNG2.adjustGamma(this); }; } }); // node_modules/commander/lib/error.js var require_error = __commonJS({ "node_modules/commander/lib/error.js"(exports2) { var CommanderError2 = class extends Error { /** * Constructs the CommanderError class * @param {number} exitCode suggested exit code which could be used with process.exit * @param {string} code an id string representing the error * @param {string} message human-readable description of the error */ constructor(exitCode, code, message) { super(message); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.code = code; this.exitCode = exitCode; this.nestedError = void 0; } }; var InvalidArgumentError2 = class extends CommanderError2 { /** * Constructs the InvalidArgumentError class * @param {string} [message] explanation of why argument is invalid */ constructor(message) { super(1, "commander.invalidArgument", message); Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; } }; exports2.CommanderError = CommanderError2; exports2.InvalidArgumentError = InvalidArgumentError2; } }); // node_modules/commander/lib/argument.js var require_argument = __commonJS({ "node_modules/commander/lib/argument.js"(exports2) { var { InvalidArgumentError: InvalidArgumentError2 } = require_error(); var Argument2 = class { /** * Initialize a new command argument with the given name and description. * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. * * @param {string} name * @param {string} [description] */ constructor(name, description) { this.description = description || ""; this.variadic = false; this.parseArg = void 0; this.defaultValue = void 0; this.defaultValueDescription = void 0; this.argChoices = void 0; switch (name[0]) { case "<": this.required = true; this._name = name.slice(1, -1); break; case "[": this.required = false; this._name = name.slice(1, -1); break; default: this.required = true; this._name = name; break; } if (this._name.length > 3 && this._name.slice(-3) === "...") { this.variadic = true; this._name = this._name.slice(0, -3); } } /** * Return argument name. * * @return {string} */ name() { return this._name; } /** * @package */ _concatValue(value, previous) { if (previous === this.defaultValue || !Array.isArray(previous)) { return [value]; } return previous.concat(value); } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {*} value * @param {string} [description] * @return {Argument} */ default(value, description) { this.defaultValue = value; this.defaultValueDescription = description; return this; } /** * Set the custom handler for processing CLI command arguments into argument values. * * @param {Function} [fn] * @return {Argument} */ argParser(fn) { this.parseArg = fn; return this; } /** * Only allow argument value to be one of choices. * * @param {string[]} values * @return {Argument} */ choices(values) { this.argChoices = values.slice(); this.parseArg = (arg, previous) => { if (!this.argChoices.includes(arg)) { throw new InvalidArgumentError2( `Allowed choices are ${this.argChoices.join(", ")}.` ); } if (this.variadic) { return this._concatValue(arg, previous); } return arg; }; return this; } /** * Make argument required. * * @returns {Argument} */ argRequired() { this.required = true; return this; } /** * Make argument optional. * * @returns {Argument} */ argOptional() { this.required = false; return this; } }; function humanReadableArgName(arg) { const nameOutput = arg.name() + (arg.variadic === true ? "..." : ""); return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]"; } exports2.Argument = Argument2; exports2.humanReadableArgName = humanReadableArgName; } }); // node_modules/commander/lib/help.js var require_help = __commonJS({ "node_modules/commander/lib/help.js"(exports2) { var { humanReadableArgName } = require_argument(); var Help2 = class { constructor() { this.helpWidth = void 0; this.minWidthToWrap = 40; this.sortSubcommands = false; this.sortOptions = false; this.showGlobalOptions = false; } /** * prepareContext is called by Commander after applying overrides from `Command.configureHelp()` * and just before calling `formatHelp()`. * * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses. * * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions */ prepareContext(contextOptions) { this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80; } /** * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. * * @param {Command} cmd * @returns {Command[]} */ visibleCommands(cmd) { const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden); const helpCommand = cmd._getHelpCommand(); if (helpCommand && !helpCommand._hidden) { visibleCommands.push(helpCommand); } if (this.sortSubcommands) { visibleCommands.sort((a, b) => { return a.name().localeCompare(b.name()); }); } return visibleCommands; } /** * Compare options for sort. * * @param {Option} a * @param {Option} b * @returns {number} */ compareOptions(a, b) { const getSortKey = (option) => { return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, ""); }; return getSortKey(a).localeCompare(getSortKey(b)); } /** * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. * * @param {Command} cmd * @returns {Option[]} */ visibleOptions(cmd) { const visibleOptions = cmd.options.filter((option) => !option.hidden); const helpOption = cmd._getHelpOption(); if (helpOption && !helpOption.hidden) { const removeShort = helpOption.short && cmd._findOption(helpOption.short); const removeLong = helpOption.long && cmd._findOption(helpOption.long); if (!removeShort && !removeLong) { visibleOptions.push(helpOption); } else if (helpOption.long && !removeLong) { visibleOptions.push( cmd.createOption(helpOption.long, helpOption.description) ); } else if (helpOption.short && !removeShort) { visibleOptions.push( cmd.createOption(helpOption.short, helpOption.description) ); } } if (this.sortOptions) { visibleOptions.sort(this.compareOptions); } return visibleOptions; } /** * Get an array of the visible global options. (Not including help.) * * @param {Command} cmd * @returns {Option[]} */ visibleGlobalOptions(cmd) { if (!this.showGlobalOptions) return []; const globalOptions = []; for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) { const visibleOptions = ancestorCmd.options.filter( (option) => !option.hidden ); globalOptions.push(...visibleOptions); } if (this.sortOptions) { globalOptions.sort(this.compareOptions); } return globalOptions; } /** * Get an array of the arguments if any have a description. * * @param {Command} cmd * @returns {Argument[]} */ visibleArguments(cmd) { if (cmd._argsDescription) { cmd.registeredArguments.forEach((argument) => { argument.description = argument.description || cmd._argsDescription[argument.name()] || ""; }); } if (cmd.registeredArguments.find((argument) => argument.description)) { return cmd.registeredArguments; } return []; } /** * Get the command term to show in the list of subcommands. * * @param {Command} cmd * @returns {string} */ subcommandTerm(cmd) { const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" "); return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option (args ? " " + args : ""); } /** * Get the option term to show in the list of options. * * @param {Option} option * @returns {string} */ optionTerm(option) { return option.flags; } /** * Get the argument term to show in the list of arguments. * * @param {Argument} argument * @returns {string} */ argumentTerm(argument) { return argument.name(); } /** * Get the longest command term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestSubcommandTermLength(cmd, helper) { return helper.visibleCommands(cmd).reduce((max, command) => { return Math.max( max, this.displayWidth( helper.styleSubcommandTerm(helper.subcommandTerm(command)) ) ); }, 0); } /** * Get the longest option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestOptionTermLength(cmd, helper) { return helper.visibleOptions(cmd).reduce((max, option) => { return Math.max( max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))) ); }, 0); } /** * Get the longest global option term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestGlobalOptionTermLength(cmd, helper) { return helper.visibleGlobalOptions(cmd).reduce((max, option) => { return Math.max( max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))) ); }, 0); } /** * Get the longest argument term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ longestArgumentTermLength(cmd, helper) { return helper.visibleArguments(cmd).reduce((max, argument) => { return Math.max( max, this.displayWidth( helper.styleArgumentTerm(helper.argumentTerm(argument)) ) ); }, 0); } /** * Get the command usage to be displayed at the top of the built-in help. * * @param {Command} cmd * @returns {string} */ commandUsage(cmd) { let cmdName = cmd._name; if (cmd._aliases[0]) { cmdName = cmdName + "|" + cmd._aliases[0]; } let ancestorCmdNames = ""; for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) { ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames; } return ancestorCmdNames + cmdName + " " + cmd.usage(); } /** * Get the description for the command. * * @param {Command} cmd * @returns {string} */ commandDescription(cmd) { return cmd.description(); } /** * Get the subcommand summary to show in the list of subcommands. * (Fallback to description for backwards compatibility.) * * @param {Command} cmd * @returns {string} */ subcommandDescription(cmd) { return cmd.summary() || cmd.description(); } /** * Get the option description to show in the list of options. * * @param {Option} option * @return {string} */ optionDescription(option) { const extraInfo = []; if (option.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}` ); } if (option.defaultValue !== void 0) { const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean"; if (showDefault) { extraInfo.push( `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}` ); } } if (option.presetArg !== void 0 && option.optional) { extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); } if (option.envVar !== void 0) { extraInfo.push(`env: ${option.envVar}`); } if (extraInfo.length > 0) { return `${option.description} (${extraInfo.join(", ")})`; } return option.description; } /** * Get the argument description to show in the list of arguments. * * @param {Argument} argument * @return {string} */ argumentDescription(argument) { const extraInfo = []; if (argument.argChoices) { extraInfo.push( // use stringify to match the display of the default value `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}` ); } if (argument.defaultValue !== void 0) { extraInfo.push( `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}` ); } if (extraInfo.length > 0) { const extraDescription = `(${extraInfo.join(", ")})`; if (argument.description) { return `${argument.description} ${extraDescription}`; } return extraDescription; } return argument.description; } /** * Generate the built-in help text. * * @param {Command} cmd * @param {Help} helper * @returns {string} */ formatHelp(cmd, helper) { const termWidth = helper.padWidth(cmd, helper); const helpWidth = helper.helpWidth ?? 80; function callFormatItem(term, description) { return helper.formatItem(term, termWidth, description, helper); } let output = [ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, "" ]; const commandDescription = helper.commandDescription(cmd); if (commandDescription.length > 0) { output = output.concat([ helper.boxWrap( helper.styleCommandDescription(commandDescription), helpWidth ), "" ]); } const argumentList = helper.visibleArguments(cmd).map((argument) => { return callFormatItem( helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)) ); }); if (argumentList.length > 0) { output = output.concat([ helper.styleTitle("Arguments:"), ...argumentList, "" ]); } const optionList = helper.visibleOptions(cmd).map((option) => { return callFormatItem( helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)) ); }); if (optionList.length > 0) { output = output.concat([ helper.styleTitle("Options:"), ...optionList, "" ]); } if (helper.showGlobalOptions) { const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => { return callFormatItem( helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)) ); }); if (globalOptionList.length > 0) { output = output.concat([ helper.styleTitle("Global Options:"), ...globalOptionList, "" ]); } } const commandList = helper.visibleCommands(cmd).map((cmd2) => { return callFormatItem( helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)), helper.styleSubcommandDescription(helper.subcommandDescription(cmd2)) ); }); if (commandList.length > 0) { output = output.concat([ helper.styleTitle("Commands:"), ...commandList, "" ]); } return output.join("\n"); } /** * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. * * @param {string} str * @returns {number} */ displayWidth(str) { return stripColor(str).length; } /** * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc. * * @param {string} str * @returns {string} */ styleTitle(str) { return str; } styleUsage(str) { return str.split(" ").map((word) => { if (word === "[options]") return this.styleOptionText(word); if (word === "[command]") return this.styleSubcommandText(word); if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word); return this.styleCommandText(word); }).join(" "); } styleCommandDescription(str) { return this.styleDescriptionText(str); } styleOptionDescription(str) { return this.styleDescriptionText(str); } styleSubcommandDescription(str) { return this.styleDescriptionText(str); } styleArgumentDescription(str) { return this.styleDescriptionText(str); } styleDescriptionText(str) { return str; } styleOptionTerm(str) { return this.styleOptionText(str); } styleSubcommandTerm(str) { return str.split(" ").map((word) => { if (word === "[options]") return this.styleOptionText(word); if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word); return this.styleSubcommandText(word); }).join(" "); } styleArgumentTerm(str) { return this.styleArgumentText(str); } styleOptionText(str) { return str; } styleArgumentText(str) { return str; } styleSubcommandText(str) { return str; } styleCommandText(str) { return str; } /** * Calculate the pad width from the maximum term length. * * @param {Command} cmd * @param {Help} helper * @returns {number} */ padWidth(cmd, helper) { return Math.max( helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper) ); } /** * Detect manually wrapped and indented strings by checking for line break followed by whitespace. * * @param {string} str * @returns {boolean} */ preformatted(str) { return /\n[^\S\r\n]/.test(str); } /** * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines. * * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so: * TTT DDD DDDD * DD DDD * * @param {string} term * @param {number} termWidth * @param {string} description * @param {Help} helper * @returns {string} */ formatItem(term, termWidth, description, helper) { const itemIndent = 2; const itemIndentStr = " ".repeat(itemIndent); if (!description) return itemIndentStr + term; const paddedTerm = term.padEnd( termWidth + term.length - helper.displayWidth(term) ); const spacerWidth = 2; const helpWidth = this.helpWidth ?? 80; const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent; let formattedDescription; if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) { formattedDescription = description; } else { const wrappedDescription = helper.boxWrap(description, remainingWidth); formattedDescription = wrappedDescription.replace( /\n/g, "\n" + " ".repeat(termWidth + spacerWidth) ); } return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, ` ${itemIndentStr}`); } /** * Wrap a string at whitespace, preserving existing line breaks. * Wrapping is skipped if the width is less than `minWidthToWrap`. * * @param {string} str * @param {number} width * @returns {string} */ boxWrap(str, width) { if (width < this.minWidthToWrap) return str; const rawLines = str.split(/\r\n|\n/); const chunkPattern = /[\s]*[^\s]+/g; const wrappedLines = []; rawLines.forEach((line) => { const chunks = line.match(chunkPattern); if (chunks === null) { wrappedLines.push(""); return; } let sumChunks = [chunks.shift()]; let sumWidth = this.displayWidth(sumChunks[0]); chunks.forEach((chunk) => { const visibleWidth = this.displayWidth(chunk); if (sumWidth + visibleWidth <= width) { sumChunks.push(chunk); sumWidth += visibleWidth; return; } wrappedLines.push(sumChunks.join("")); const nextChunk = chunk.trimStart(); sumChunks = [nextChunk]; sumWidth = this.displayWidth(nextChunk); }); wrappedLines.push(sumChunks.join("")); }); return wrappedLines.join("\n"); } }; function stripColor(str) { const sgrPattern = /\x1b\[\d*(;\d*)*m/g; return str.replace(sgrPattern, ""); } exports2.Help = Help2; exports2.stripColor = stripColor; } }); // node_modules/commander/lib/option.js var require_option = __commonJS({ "node_modules/commander/lib/option.js"(exports2) { var { InvalidArgumentError: InvalidArgumentError2 } = require_error(); var Option2 = class { /** * Initialize a new `Option` with the given `flags` and `description`. * * @param {string} flags * @param {string} [description] */ constructor(flags, description) { this.flags = flags; this.description = description || ""; this.required = flags.includes("<"); this.optional = flags.includes("["); this.variadic = /\w\.\.\.[>\]]$/.test(flags); this.mandatory = false; const optionFlags = splitOptionFlags(flags); this.short = optionFlags.shortFlag; this.long = optionFlags.longFlag; this.negate = false; if (this.long) { this.negate = this.long.startsWith("--no-"); } this.defaultValue = void 0; this.defaultValueDescription = void 0; this.presetArg = void 0; this.envVar = void 0; this.parseArg = void 0; this.hidden = false; this.argChoices = void 0; this.conflictsWith = []; this.implied = void 0; } /** * Set the default value, and optionally supply the description to be displayed in the help. * * @param {*} value * @param {string} [description] * @return {Option} */ default(value, description) { this.defaultValue = value; this.defaultValueDescription = description; return this; } /** * Preset to use when option used without option-argument, especially optional but also boolean and negated. * The custom processing (parseArg) is called. * * @example * new Option('--color').default('GREYSCALE').preset('RGB'); * new Option('--donate [amount]').preset('20').argParser(parseFloat); * * @param {*} arg * @return {Option} */ preset(arg) { this.presetArg = arg; return this; } /** * Add option name(s) that conflict with this option. * An error will be displayed if conflicting options are found during parsing. * * @example * new Option('--rgb').conflicts('cmyk'); * new Option('--js').conflicts(['ts', 'jsx']); * * @param {(string | string[])} names * @return {Option} */ conflicts(names) { this.conflictsWith = this.conflictsWith.concat(names); return this; } /** * Specify implied option values for when this option is set and the implied options are not. * * The custom processing (parseArg) is not called on the implied values. * * @example * program * .addOption(new Option('--log', 'write logging information to file')) * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); * * @param {object} impliedOptionValues * @return {Option} */ implies(impliedOptionValues) { let newImplied = impliedOptionValues; if (typeof impliedOptionValues === "string") { newImplied = { [impliedOptionValues]: true }; } this.implied = Object.assign(this.implied || {}, newImplied); return this; } /** * Set environment variable to check for option value. * * An environment variable is only used if when processed the current option value is * undefined, or the source of the current value is 'default' or 'config' or 'env'. * * @param {string} name * @return {Option} */ env(name) { this.envVar = name; return this; } /** * Set the custom handler for processing CLI option arguments into option values. * * @param {Function} [fn] * @return {Option} */ argParser(fn) { this.parseArg = fn; return this; } /** * Whether the option is mandatory and must have a value after parsing. * * @param {boolean} [mandatory=true] * @return {Option} */ makeOptionMandatory(mandatory = true) { this.mandatory = !!mandatory; return this; } /** * Hide option in help. * * @param {boolean} [hide=true] * @return {Option} */ hideHelp(hide = true) { this.hidden = !!hide; return this; } /** * @package */ _concatValue(value, previous) { if (previous === this.defaultValue || !Array.isArray(previous)) { return [value]; } return previous.concat(value); } /** * Only allow option value to be one of choices. * * @param {string[]} values * @return {Option} */ choices(values) { this.argChoices = values.slice(); this.parseArg = (arg, previous) => { if (!this.argChoices.includes(arg)) { throw new InvalidArgumentError2( `Allowed choices are ${this.argChoices.join(", ")}.` ); } if (this.variadic) { return this._concatValue(arg, previous); } return arg; }; return this; } /** * Return option name. * * @return {string} */ name() { if (this.long) { return this.long.replace(/^--/, ""); } return this.short.replace(/^-/, ""); } /** * Return option name, in a camelcase format that can be used * as an object attribute key. * * @return {string} */ attributeName() { if (this.negate) { return camelcase(this.name().replace(/^no-/, "")); } return camelcase(this.name()); } /** * Check if `arg` matches the short or long flag. * * @param {string} arg * @return {boolean} * @package */ is(arg) { return this.short === arg || this.long === arg; } /** * Return whether a boolean option. * * Options are one of boolean, negated, required argument, or optional argument. * * @return {boolean} * @package */ isBoolean() { return !this.required && !this.optional && !this.negate; } }; var DualOptions = class { /** * @param {Option[]} options */ constructor(options) { this.positiveOptions = /* @__PURE__ */ new Map(); this.negativeOptions = /* @__PURE__ */ new Map(); this.dualOptions = /* @__PURE__ */ new Set(); options.forEach((option) => { if (option.negate) { this.negativeOptions.set(option.attributeName(), option); } else { this.positiveOptions.set(option.attributeName(), option); } }); this.negativeOptions.forEach((value, key) => { if (this.positiveOptions.has(key)) { this.dualOptions.add(key); } }); } /** * Did the value come from the option, and not from possible matching dual option? * * @param {*} value * @param {Option} option * @returns {boolean} */ valueFromOption(value, option) { const optionKey = option.attributeName(); if (!this.dualOptions.has(optionKey)) return true; const preset = this.negativeOptions.get(optionKey).presetArg; const negativeValue = preset !== void 0 ? preset : false; return option.negate === (negativeValue === value); } }; function camelcase(str) { return str.split("-").reduce((str2, word) => { return str2 + word[0].toUpperCase() + word.slice(1); }); } function splitOptionFlags(flags) { let shortFlag; let longFlag; const shortFlagExp = /^-[^-]$/; const longFlagExp = /^--[^-]/; const flagParts = flags.split(/[ |,]+/).concat("guard"); if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift(); if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift(); if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift(); if (!shortFlag && longFlagExp.test(flagParts[0])) { shortFlag = longFlag; longFlag = flagParts.shift(); } if (flagParts[0].startsWith("-")) { const unsupportedFlag = flagParts[0]; const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`; if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error( `${baseError} - a short flag is a single dash and a single character - either use a single dash and a single character (for a short flag) - or use a double dash for a long option (and can have two, like '--ws, --workspace')` ); if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError} - too many short flags`); if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError} - too many long flags`); throw new Error(`${baseError} - unrecognised flag format`); } if (shortFlag === void 0 && longFlag === void 0) throw new Error( `option creation failed due to no flags found in '${flags}'.` ); return { shortFlag, longFlag }; } exports2.Option = Option2; exports2.DualOptions = DualOptions; } }); // node_modules/commander/lib/suggestSimilar.js var require_suggestSimilar = __commonJS({ "node_modules/commander/lib/suggestSimilar.js"(exports2) { var maxDistance = 3; function editDistance(a, b) { if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length); const d = []; for (let i = 0; i <= a.length; i++) { d[i] = [i]; } for (let j = 0; j <= b.length; j++) { d[0][j] = j; } for (let j = 1; j <= b.length; j++) { for (let i = 1; i <= a.length; i++) { let cost = 1; if (a[i - 1] === b[j - 1]) { cost = 0; } else { cost = 1; } d[i][j] = Math.min( d[i - 1][j] + 1, // deletion d[i][j - 1] + 1, // insertion d[i - 1][j - 1] + cost // substitution ); if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); } } } return d[a.length][b.length]; } function suggestSimilar(word, candidates) { if (!candidates || candidates.length === 0) return ""; candidates = Array.from(new Set(candidates)); const searchingOptions = word.startsWith("--"); if (searchingOptions) { word = word.slice(2); candidates = candidates.map((candidate) => candidate.slice(2)); } let similar = []; let bestDistance = maxDistance; const minSimilarity = 0.4; candidates.forEach((candidate) => { if (candidate.length <= 1) return; const distance = editDistance(word, candidate); const length = Math.max(word.length, candidate.length); const similarity = (length - distance) / length; if (similarity > minSimilarity) { if (distance < bestDistance) { bestDistance = distance; similar = [candidate]; } else if (distance === bestDistance) { similar.push(candidate); } } }); similar.sort((a, b) => a.localeCompare(b)); if (searchingOptions) { similar = similar.map((candidate) => `--${candidate}`); } if (similar.length > 1) { return ` (Did you mean one of ${similar.join(", ")}?)`; } if (similar.length === 1) { return ` (Did you mean ${similar[0]}?)`; } return ""; } exports2.suggestSimilar = suggestSimilar; } }); // node_modules/commander/lib/command.js var require_command = __commonJS({ "node_modules/commander/lib/command.js"(exports2) { var EventEmitter = require("node:events").EventEmitter; var childProcess = require("node:child_process"); var path = require("node:path"); var fs = require("node:fs"); var process5 = require("node:process"); var { Argument: Argument2, humanReadableArgName } = require_argument(); var { CommanderError: CommanderError2 } = require_error(); var { Help: Help2, stripColor } = require_help(); var { Option: Option2, DualOptions } = require_option(); var { suggestSimilar } = require_suggestSimilar(); var Command2 = class _Command extends EventEmitter { /** * Initialize a new `Command`. * * @param {string} [name] */ constructor(name) { super(); this.commands = []; this.options = []; this.parent = null; this._allowUnknownOption = false; this._allowExcessArguments = false; this.registeredArguments = []; this._args = this.registeredArguments; this.args = []; this.rawArgs = []; this.processedArgs = []; this._scriptPath = null; this._name = name || ""; this._optionValues = {}; this._optionValueSources = {}; this._storeOptionsAsProperties = false; this._actionHandler = null; this._executableHandler = false; this._executableFile = null; this._executableDir = null; this._defaultCommandName = null; this._exitCallback = null; this._aliases = []; this._combineFlagAndOptionalValue = true; this._description = ""; this._summary = ""; this._argsDescription = void 0; this._enablePositionalOptions = false; this._passThroughOptions = false; this._lifeCycleHooks = {}; this._showHelpAfterError = false; this._showSuggestionAfterError = true; this._savedState = null; this._outputConfiguration = { writeOut: (str) => process5.stdout.write(str), writeErr: (str) => process5.stderr.write(str), outputError: (str, write) => write(str), getOutHelpWidth: () => process5.stdout.isTTY ? process5.stdout.columns : void 0, getErrHelpWidth: () => process5.stderr.isTTY ? process5.stderr.columns : void 0, getOutHasColors: () => useColor() ?? (process5.stdout.isTTY && process5.stdout.hasColors?.()), getErrHasColors: () => useColor() ?? (process5.stderr.isTTY && process5.stderr.hasColors?.()), stripColor: (str) => stripColor(str) }; this._hidden = false; this._helpOption = void 0; this._addImplicitHelpCommand = void 0; this._helpCommand = void 0; this._helpConfiguration = {}; } /** * Copy settings that are useful to have in common across root command and subcommands. * * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) * * @param {Command} sourceCommand * @return {Command} `this` command for chaining */ copyInheritedSettings(sourceCommand) { this._outputConfiguration = sourceCommand._outputConfiguration; this._helpOption = sourceCommand._helpOption; this._helpCommand = sourceCommand._helpCommand; this._helpConfiguration = sourceCommand._helpConfiguration; this._exitCallback = sourceCommand._exitCallback; this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties; this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue; this._allowExcessArguments = sourceCommand._allowExcessArguments; this._enablePositionalOptions = sourceCommand._enablePositionalOptions; this._showHelpAfterError = sourceCommand._showHelpAfterError; this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError; return this; } /** * @returns {Command[]} * @private */ _getCommandAndAncestors() { const result = []; for (let command = this; command; command = command.parent) { result.push(command); } return result; } /** * Define a command. * * There are two styles of command: pay attention to where to put the description. * * @example * // Command implemented using action handler (description is supplied separately to `.command`) * program * .command('clone [destination]') * .description('clone a repository into a newly created directory') * .action((source, destination) => { * console.log('clone command called'); * }); * * // Command implemented using separate executable file (description is second parameter to `.command`) * program * .command('start ', 'start named service') * .command('stop [service]', 'stop named service, or all if no name supplied'); * * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) * @param {object} [execOpts] - configuration options (for executable) * @return {Command} returns new command for action handler, or `this` for executable command */ command(nameAndArgs, actionOptsOrExecDesc, execOpts) { let desc = actionOptsOrExecDesc; let opts = execOpts; if (typeof desc === "object" && desc !== null) { opts = desc; desc = null; } opts = opts || {}; const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); const cmd = this.createCommand(name); if (desc) { cmd.description(desc); cmd._executableHandler = true; } if (opts.isDefault) this._defaultCommandName = cmd._name; cmd._hidden = !!(opts.noHelp || opts.hidden); cmd._executableFile = opts.executableFile || null; if (args) cmd.arguments(args); this._registerCommand(cmd); cmd.parent = this; cmd.copyInheritedSettings(this); if (desc) return this; return cmd; } /** * Factory routine to create a new unattached command. * * See .command() for creating an attached subcommand, which uses this routine to * create the command. You can override createCommand to customise subcommands. * * @param {string} [name] * @return {Command} new command */ createCommand(name) { return new _Command(name); } /** * You can customise the help with a subclass of Help by overriding createHelp, * or by overriding Help properties using configureHelp(). * * @return {Help} */ createHelp() { return Object.assign(new Help2(), this.configureHelp()); } /** * You can customise the help by overriding Help properties using configureHelp(), * or with a subclass of Help by overriding createHelp(). * * @param {object} [configuration] - configuration options * @return {(Command | object)} `this` command for chaining, or stored configuration */ configureHelp(configuration) { if (configuration === void 0) return this._helpConfiguration; this._helpConfiguration = configuration; return this; } /** * The default output goes to stdout and stderr. You can customise this for special * applications. You can also customise the display of errors by overriding outputError. * * The configuration properties are all functions: * * // change how output being written, defaults to stdout and stderr * writeOut(str) * writeErr(str) * // change how output being written for errors, defaults to writeErr * outputError(str, write) // used for displaying errors and not used for displaying help * // specify width for wrapping help * getOutHelpWidth() * getErrHelpWidth() * // color support, currently only used with Help * getOutHasColors() * getErrHasColors() * stripColor() // used to remove ANSI escape codes if output does not have colors * * @param {object} [configuration] - configuration options * @return {(Command | object)} `this` command for chaining, or stored configuration */ configureOutput(configuration) { if (configuration === void 0) return this._outputConfiguration; Object.assign(this._outputConfiguration, configuration); return this; } /** * Display the help or a custom message after an error occurs. * * @param {(boolean|string)} [displayHelp] * @return {Command} `this` command for chaining */ showHelpAfterError(displayHelp = true) { if (typeof displayHelp !== "string") displayHelp = !!displayHelp; this._showHelpAfterError = displayHelp; return this; } /** * Display suggestion of similar commands for unknown commands, or options for unknown options. * * @param {boolean} [displaySuggestion] * @return {Command} `this` command for chaining */ showSuggestionAfterError(displaySuggestion = true) { this._showSuggestionAfterError = !!displaySuggestion; return this; } /** * Add a prepared subcommand. * * See .command() for creating an attached subcommand which inherits settings from its parent. * * @param {Command} cmd - new subcommand * @param {object} [opts] - configuration options * @return {Command} `this` command for chaining */ addCommand(cmd, opts) { if (!cmd._name) { throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`); } opts = opts || {}; if (opts.isDefault) this._defaultCommandName = cmd._name; if (opts.noHelp || opts.hidden) cmd._hidden = true; this._registerCommand(cmd); cmd.parent = this; cmd._checkForBrokenPassThrough(); return this; } /** * Factory routine to create a new unattached argument. * * See .argument() for creating an attached argument, which uses this routine to * create the argument. You can override createArgument to return a custom argument. * * @param {string} name * @param {string} [description] * @return {Argument} new argument */ createArgument(name, description) { return new Argument2(name, description); } /** * Define argument syntax for command. * * The default is that the argument is required, and you can explicitly * indicate this with <> around the name. Put [] around the name for an optional argument. * * @example * program.argument(''); * program.argument('[output-file]'); * * @param {string} name * @param {string} [description] * @param {(Function|*)} [fn] - custom argument processing function * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ argument(name, description, fn, defaultValue) { const argument = this.createArgument(name, description); if (typeof fn === "function") { argument.default(defaultValue).argParser(fn); } else { argument.default(fn); } this.addArgument(argument); return this; } /** * Define argument syntax for command, adding multiple at once (without descriptions). * * See also .argument(). * * @example * program.arguments(' [env]'); * * @param {string} names * @return {Command} `this` command for chaining */ arguments(names) { names.trim().split(/ +/).forEach((detail) => { this.argument(detail); }); return this; } /** * Define argument syntax for command, adding a prepared argument. * * @param {Argument} argument * @return {Command} `this` command for chaining */ addArgument(argument) { const previousArgument = this.registeredArguments.slice(-1)[0]; if (previousArgument && previousArgument.variadic) { throw new Error( `only the last argument can be variadic '${previousArgument.name()}'` ); } if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) { throw new Error( `a default value for a required argument is never used: '${argument.name()}'` ); } this.registeredArguments.push(argument); return this; } /** * Customise or override default help command. By default a help command is automatically added if your command has subcommands. * * @example * program.helpCommand('help [cmd]'); * program.helpCommand('help [cmd]', 'show help'); * program.helpCommand(false); // suppress default help command * program.helpCommand(true); // add help command even if no subcommands * * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added * @param {string} [description] - custom description * @return {Command} `this` command for chaining */ helpCommand(enableOrNameAndArgs, description) { if (typeof enableOrNameAndArgs === "boolean") { this._addImplicitHelpCommand = enableOrNameAndArgs; return this; } enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]"; const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/); const helpDescription = description ?? "display help for command"; const helpCommand = this.createCommand(helpName); helpCommand.helpOption(false); if (helpArgs) helpCommand.arguments(helpArgs); if (helpDescription) helpCommand.description(helpDescription); this._addImplicitHelpCommand = true; this._helpCommand = helpCommand; return this; } /** * Add prepared custom help command. * * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()` * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only * @return {Command} `this` command for chaining */ addHelpCommand(helpCommand, deprecatedDescription) { if (typeof helpCommand !== "object") { this.helpCommand(helpCommand, deprecatedDescription); return this; } this._addImplicitHelpCommand = true; this._helpCommand = helpCommand; return this; } /** * Lazy create help command. * * @return {(Command|null)} * @package */ _getHelpCommand() { const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help")); if (hasImplicitHelpCommand) { if (this._helpCommand === void 0) { this.helpCommand(void 0, void 0); } return this._helpCommand; } return null; } /** * Add hook for life cycle event. * * @param {string} event * @param {Function} listener * @return {Command} `this` command for chaining */ hook(event, listener) { const allowedValues = ["preSubcommand", "preAction", "postAction"]; if (!allowedValues.includes(event)) { throw new Error(`Unexpected value for event passed to hook : '${event}'. Expecting one of '${allowedValues.join("', '")}'`); } if (this._lifeCycleHooks[event]) { this._lifeCycleHooks[event].push(listener); } else { this._lifeCycleHooks[event] = [listener]; } return this; } /** * Register callback to use as replacement for calling process.exit. * * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing * @return {Command} `this` command for chaining */ exitOverride(fn) { if (fn) { this._exitCallback = fn; } else { this._exitCallback = (err) => { if (err.code !== "commander.executeSubCommandAsync") { throw err; } else { } }; } return this; } /** * Call process.exit, and _exitCallback if defined. * * @param {number} exitCode exit code for using with process.exit * @param {string} code an id string representing the error * @param {string} message human-readable description of the error * @return never * @private */ _exit(exitCode, code, message) { if (this._exitCallback) { this._exitCallback(new CommanderError2(exitCode, code, message)); } process5.exit(exitCode); } /** * Register callback `fn` for the command. * * @example * program * .command('serve') * .description('start service') * .action(function() { * // do work here * }); * * @param {Function} fn * @return {Command} `this` command for chaining */ action(fn) { const listener = (args) => { const expectedArgsCount = this.registeredArguments.length; const actionArgs = args.slice(0, expectedArgsCount); if (this._storeOptionsAsProperties) { actionArgs[expectedArgsCount] = this; } else { actionArgs[expectedArgsCount] = this.opts(); } actionArgs.push(this); return fn.apply(this, actionArgs); }; this._actionHandler = listener; return this; } /** * Factory routine to create a new unattached option. * * See .option() for creating an attached option, which uses this routine to * create the option. You can override createOption to return a custom option. * * @param {string} flags * @param {string} [description] * @return {Option} new option */ createOption(flags, description) { return new Option2(flags, description); } /** * Wrap parseArgs to catch 'commander.invalidArgument'. * * @param {(Option | Argument)} target * @param {string} value * @param {*} previous * @param {string} invalidArgumentMessage * @private */ _callParseArg(target, value, previous, invalidArgumentMessage) { try { return target.parseArg(value, previous); } catch (err) { if (err.code === "commander.invalidArgument") { const message = `${invalidArgumentMessage} ${err.message}`; this.error(message, { exitCode: err.exitCode, code: err.code }); } throw err; } } /** * Check for option flag conflicts. * Register option if no conflicts found, or throw on conflict. * * @param {Option} option * @private */ _registerOption(option) { const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long); if (matchingOption) { const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short; throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}' - already used by option '${matchingOption.flags}'`); } this.options.push(option); } /** * Check for command name and alias conflicts with existing commands. * Register command if no conflicts found, or throw on conflict. * * @param {Command} command * @private */ _registerCommand(command) { const knownBy = (cmd) => { return [cmd.name()].concat(cmd.aliases()); }; const alreadyUsed = knownBy(command).find( (name) => this._findCommand(name) ); if (alreadyUsed) { const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|"); const newCmd = knownBy(command).join("|"); throw new Error( `cannot add command '${newCmd}' as already have command '${existingCmd}'` ); } this.commands.push(command); } /** * Add an option. * * @param {Option} option * @return {Command} `this` command for chaining */ addOption(option) { this._registerOption(option); const oname = option.name(); const name = option.attributeName(); if (option.negate) { const positiveLongFlag = option.long.replace(/^--no-/, "--"); if (!this._findOption(positiveLongFlag)) { this.setOptionValueWithSource( name, option.defaultValue === void 0 ? true : option.defaultValue, "default" ); } } else if (option.defaultValue !== void 0) { this.setOptionValueWithSource(name, option.defaultValue, "default"); } const handleOptionValue = (val, invalidValueMessage, valueSource) => { if (val == null && option.presetArg !== void 0) { val = option.presetArg; } const oldValue = this.getOptionValue(name); if (val !== null && option.parseArg) { val = this._callParseArg(option, val, oldValue, invalidValueMessage); } else if (val !== null && option.variadic) { val = option._concatValue(val, oldValue); } if (val == null) { if (option.negate) { val = false; } else if (option.isBoolean() || option.optional) { val = true; } else { val = ""; } } this.setOptionValueWithSource(name, val, valueSource); }; this.on("option:" + oname, (val) => { const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`; handleOptionValue(val, invalidValueMessage, "cli"); }); if (option.envVar) { this.on("optionEnv:" + oname, (val) => { const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`; handleOptionValue(val, invalidValueMessage, "env"); }); } return this; } /** * Internal implementation shared by .option() and .requiredOption() * * @return {Command} `this` command for chaining * @private */ _optionEx(config2, flags, description, fn, defaultValue) { if (typeof flags === "object" && flags instanceof Option2) { throw new Error( "To add an Option object use addOption() instead of option() or requiredOption()" ); } const option = this.createOption(flags, description); option.makeOptionMandatory(!!config2.mandatory); if (typeof fn === "function") { option.default(defaultValue).argParser(fn); } else if (fn instanceof RegExp) { const regex = fn; fn = (val, def) => { const m = regex.exec(val); return m ? m[0] : def; }; option.default(defaultValue).argParser(fn); } else { option.default(fn); } return this.addOption(option); } /** * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. * * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required * option-argument is indicated by `<>` and an optional option-argument by `[]`. * * See the README for more details, and see also addOption() and requiredOption(). * * @example * program * .option('-p, --pepper', 'add pepper') * .option('--pt, --pizza-type ', 'type of pizza') // required option-argument * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default * .option('-t, --tip ', 'add tip to purchase cost', parseFloat) // custom parse function * * @param {string} flags * @param {string} [description] * @param {(Function|*)} [parseArg] - custom option processing function or default value * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ option(flags, description, parseArg, defaultValue) { return this._optionEx({}, flags, description, parseArg, defaultValue); } /** * Add a required option which must have a value after parsing. This usually means * the option must be specified on the command line. (Otherwise the same as .option().) * * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. * * @param {string} flags * @param {string} [description] * @param {(Function|*)} [parseArg] - custom option processing function or default value * @param {*} [defaultValue] * @return {Command} `this` command for chaining */ requiredOption(flags, description, parseArg, defaultValue) { return this._optionEx( { mandatory: true }, flags, description, parseArg, defaultValue ); } /** * Alter parsing of short flags with optional values. * * @example * // for `.option('-f,--flag [value]'): * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` * * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag. * @return {Command} `this` command for chaining */ combineFlagAndOptionalValue(combine = true) { this._combineFlagAndOptionalValue = !!combine; return this; } /** * Allow unknown options on the command line. * * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options. * @return {Command} `this` command for chaining */ allowUnknownOption(allowUnknown = true) { this._allowUnknownOption = !!allowUnknown; return this; } /** * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. * * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments. * @return {Command} `this` command for chaining */ allowExcessArguments(allowExcess = true) { this._allowExcessArguments = !!allowExcess; return this; } /** * Enable positional options. Positional means global options are specified before subcommands which lets * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. * The default behaviour is non-positional and global options may appear anywhere on the command line. * * @param {boolean} [positional] * @return {Command} `this` command for chaining */ enablePositionalOptions(positional = true) { this._enablePositionalOptions = !!positional; return this; } /** * Pass through options that come after command-arguments rather than treat them as command-options, * so actual command-options come before command-arguments. Turning this on for a subcommand requires * positional options to have been enabled on the program (parent commands). * The default behaviour is non-positional and options may appear before or after command-arguments. * * @param {boolean} [passThrough] for unknown options. * @return {Command} `this` command for chaining */ passThroughOptions(passThrough = true) { this._passThroughOptions = !!passThrough; this._checkForBrokenPassThrough(); return this; } /** * @private */ _checkForBrokenPassThrough() { if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) { throw new Error( `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)` ); } } /** * Whether to store option values as properties on command object, * or store separately (specify false). In both cases the option values can be accessed using .opts(). * * @param {boolean} [storeAsProperties=true] * @return {Command} `this` command for chaining */ storeOptionsAsProperties(storeAsProperties = true) { if (this.options.length) { throw new Error("call .storeOptionsAsProperties() before adding options"); } if (Object.keys(this._optionValues).length) { throw new Error( "call .storeOptionsAsProperties() before setting option values" ); } this._storeOptionsAsProperties = !!storeAsProperties; return this; } /** * Retrieve option value. * * @param {string} key * @return {object} value */ getOptionValue(key) { if (this._storeOptionsAsProperties) { return this[key]; } return this._optionValues[key]; } /** * Store option value. * * @param {string} key * @param {object} value * @return {Command} `this` command for chaining */ setOptionValue(key, value) { return this.setOptionValueWithSource(key, value, void 0); } /** * Store option value and where the value came from. * * @param {string} key * @param {object} value * @param {string} source - expected values are default/config/env/cli/implied * @return {Command} `this` command for chaining */ setOptionValueWithSource(key, value, source) { if (this._storeOptionsAsProperties) { this[key] = value; } else { this._optionValues[key] = value; } this._optionValueSources[key] = source; return this; } /** * Get source of option value. * Expected values are default | config | env | cli | implied * * @param {string} key * @return {string} */ getOptionValueSource(key) { return this._optionValueSources[key]; } /** * Get source of option value. See also .optsWithGlobals(). * Expected values are default | config | env | cli | implied * * @param {string} key * @return {string} */ getOptionValueSourceWithGlobals(key) { let source; this._getCommandAndAncestors().forEach((cmd) => { if (cmd.getOptionValueSource(key) !== void 0) { source = cmd.getOptionValueSource(key); } }); return source; } /** * Get user arguments from implied or explicit arguments. * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. * * @private */ _prepareUserArgs(argv, parseOptions) { if (argv !== void 0 && !Array.isArray(argv)) { throw new Error("first parameter to parse must be array or undefined"); } parseOptions = parseOptions || {}; if (argv === void 0 && parseOptions.from === void 0) { if (process5.versions?.electron) { parseOptions.from = "electron"; } const execArgv = process5.execArgv ?? []; if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) { parseOptions.from = "eval"; } } if (argv === void 0) { argv = process5.argv; } this.rawArgs = argv.slice(); let userArgs; switch (parseOptions.from) { case void 0: case "node": this._scriptPath = argv[1]; userArgs = argv.slice(2); break; case "electron": if (process5.defaultApp) { this._scriptPath = argv[1]; userArgs = argv.slice(2); } else { userArgs = argv.slice(1); } break; case "user": userArgs = argv.slice(0); break; case "eval": userArgs = argv.slice(1); break; default: throw new Error( `unexpected parse option { from: '${parseOptions.from}' }` ); } if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath); this._name = this._name || "program"; return userArgs; } /** * Parse `argv`, setting options and invoking commands when defined. * * Use parseAsync instead of parse if any of your action handlers are async. * * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! * * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged * - `'user'`: just user arguments * * @example * program.parse(); // parse process.argv and auto-detect electron and special node flags * program.parse(process.argv); // assume argv[0] is app and argv[1] is script * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * * @param {string[]} [argv] - optional, defaults to process.argv * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' * @return {Command} `this` command for chaining */ parse(argv, parseOptions) { this._prepareForParse(); const userArgs = this._prepareUserArgs(argv, parseOptions); this._parseCommand([], userArgs); return this; } /** * Parse `argv`, setting options and invoking commands when defined. * * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! * * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged * - `'user'`: just user arguments * * @example * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] * * @param {string[]} [argv] * @param {object} [parseOptions] * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' * @return {Promise} */ async parseAsync(argv, parseOptions) { this._prepareForParse(); const userArgs = this._prepareUserArgs(argv, parseOptions); await this._parseCommand([], userArgs); return this; } _prepareForParse() { if (this._savedState === null) { this.saveStateBeforeParse(); } else { this.restoreStateBeforeParse(); } } /** * Called the first time parse is called to save state and allow a restore before subsequent calls to parse. * Not usually called directly, but available for subclasses to save their custom state. * * This is called in a lazy way. Only commands used in parsing chain will have state saved. */ saveStateBeforeParse() { this._savedState = { // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing _name: this._name, // option values before parse have default values (including false for negated options) // shallow clones _optionValues: { ...this._optionValues }, _optionValueSources: { ...this._optionValueSources } }; } /** * Restore state before parse for calls after the first. * Not usually called directly, but available for subclasses to save their custom state. * * This is called in a lazy way. Only commands used in parsing chain will have state restored. */ restoreStateBeforeParse() { if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true. - either make a new Command for each call to parse, or stop storing options as properties`); this._name = this._savedState._name; this._scriptPath = null; this.rawArgs = []; this._optionValues = { ...this._savedState._optionValues }; this._optionValueSources = { ...this._savedState._optionValueSources }; this.args = []; this.processedArgs = []; } /** * Throw if expected executable is missing. Add lots of help for author. * * @param {string} executableFile * @param {string} executableDir * @param {string} subcommandName */ _checkForMissingExecutable(executableFile, executableDir, subcommandName) { if (fs.existsSync(executableFile)) return; const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"; const executableMissing = `'${executableFile}' does not exist - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - ${executableDirMessage}`; throw new Error(executableMissing); } /** * Execute a sub-command executable. * * @private */ _executeSubCommand(subcommand, args) { args = args.slice(); let launchWithNode = false; const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"]; function findFile(baseDir, baseName) { const localBin = path.resolve(baseDir, baseName); if (fs.existsSync(localBin)) return localBin; if (sourceExt.includes(path.extname(baseName))) return void 0; const foundExt = sourceExt.find( (ext) => fs.existsSync(`${localBin}${ext}`) ); if (foundExt) return `${localBin}${foundExt}`; return void 0; } this._checkForMissingMandatoryOptions(); this._checkForConflictingOptions(); let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`; let executableDir = this._executableDir || ""; if (this._scriptPath) { let resolvedScriptPath; try { resolvedScriptPath = fs.realpathSync(this._scriptPath); } catch { resolvedScriptPath = this._scriptPath; } executableDir = path.resolve( path.dirname(resolvedScriptPath), executableDir ); } if (executableDir) { let localFile = findFile(executableDir, executableFile); if (!localFile && !subcommand._executableFile && this._scriptPath) { const legacyName = path.basename( this._scriptPath, path.extname(this._scriptPath) ); if (legacyName !== this._name) { localFile = findFile( executableDir, `${legacyName}-${subcommand._name}` ); } } executableFile = localFile || executableFile; } launchWithNode = sourceExt.includes(path.extname(executableFile)); let proc; if (process5.platform !== "win32") { if (launchWithNode) { args.unshift(executableFile); args = incrementNodeInspectorPort(process5.execArgv).concat(args); proc = childProcess.spawn(process5.argv[0], args, { stdio: "inherit" }); } else { proc = childProcess.spawn(executableFile, args, { stdio: "inherit" }); } } else { this._checkForMissingExecutable( executableFile, executableDir, subcommand._name ); args.unshift(executableFile); args = incrementNodeInspectorPort(process5.execArgv).concat(args); proc = childProcess.spawn(process5.execPath, args, { stdio: "inherit" }); } if (!proc.killed) { const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"]; signals.forEach((signal) => { process5.on(signal, () => { if (proc.killed === false && proc.exitCode === null) { proc.kill(signal); } }); }); } const exitCallback = this._exitCallback; proc.on("close", (code) => { code = code ?? 1; if (!exitCallback) { process5.exit(code); } else { exitCallback( new CommanderError2( code, "commander.executeSubCommandAsync", "(close)" ) ); } }); proc.on("error", (err) => { if (err.code === "ENOENT") { this._checkForMissingExecutable( executableFile, executableDir, subcommand._name ); } else if (err.code === "EACCES") { throw new Error(`'${executableFile}' not executable`); } if (!exitCallback) { process5.exit(1); } else { const wrappedError = new CommanderError2( 1, "commander.executeSubCommandAsync", "(error)" ); wrappedError.nestedError = err; exitCallback(wrappedError); } }); this.runningCommand = proc; } /** * @private */ _dispatchSubcommand(commandName, operands, unknown2) { const subCommand = this._findCommand(commandName); if (!subCommand) this.help({ error: true }); subCommand._prepareForParse(); let promiseChain; promiseChain = this._chainOrCallSubCommandHook( promiseChain, subCommand, "preSubcommand" ); promiseChain = this._chainOrCall(promiseChain, () => { if (subCommand._executableHandler) { this._executeSubCommand(subCommand, operands.concat(unknown2)); } else { return subCommand._parseCommand(operands, unknown2); } }); return promiseChain; } /** * Invoke help directly if possible, or dispatch if necessary. * e.g. help foo * * @private */ _dispatchHelpCommand(subcommandName) { if (!subcommandName) { this.help(); } const subCommand = this._findCommand(subcommandName); if (subCommand && !subCommand._executableHandler) { subCommand.help(); } return this._dispatchSubcommand( subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"] ); } /** * Check this.args against expected this.registeredArguments. * * @private */ _checkNumberOfArguments() { this.registeredArguments.forEach((arg, i) => { if (arg.required && this.args[i] == null) { this.missingArgument(arg.name()); } }); if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) { return; } if (this.args.length > this.registeredArguments.length) { this._excessArguments(this.args); } } /** * Process this.args using this.registeredArguments and save as this.processedArgs! * * @private */ _processArguments() { const myParseArg = (argument, value, previous) => { let parsedValue = value; if (value !== null && argument.parseArg) { const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`; parsedValue = this._callParseArg( argument, value, previous, invalidValueMessage ); } return parsedValue; }; this._checkNumberOfArguments(); const processedArgs = []; this.registeredArguments.forEach((declaredArg, index) => { let value = declaredArg.defaultValue; if (declaredArg.variadic) { if (index < this.args.length) { value = this.args.slice(index); if (declaredArg.parseArg) { value = value.reduce((processed, v) => { return myParseArg(declaredArg, v, processed); }, declaredArg.defaultValue); } } else if (value === void 0) { value = []; } } else if (index < this.args.length) { value = this.args[index]; if (declaredArg.parseArg) { value = myParseArg(declaredArg, value, declaredArg.defaultValue); } } processedArgs[index] = value; }); this.processedArgs = processedArgs; } /** * Once we have a promise we chain, but call synchronously until then. * * @param {(Promise|undefined)} promise * @param {Function} fn * @return {(Promise|undefined)} * @private */ _chainOrCall(promise2, fn) { if (promise2 && promise2.then && typeof promise2.then === "function") { return promise2.then(() => fn()); } return fn(); } /** * * @param {(Promise|undefined)} promise * @param {string} event * @return {(Promise|undefined)} * @private */ _chainOrCallHooks(promise2, event) { let result = promise2; const hooks = []; this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => { hookedCommand._lifeCycleHooks[event].forEach((callback) => { hooks.push({ hookedCommand, callback }); }); }); if (event === "postAction") { hooks.reverse(); } hooks.forEach((hookDetail) => { result = this._chainOrCall(result, () => { return hookDetail.callback(hookDetail.hookedCommand, this); }); }); return result; } /** * * @param {(Promise|undefined)} promise * @param {Command} subCommand * @param {string} event * @return {(Promise|undefined)} * @private */ _chainOrCallSubCommandHook(promise2, subCommand, event) { let result = promise2; if (this._lifeCycleHooks[event] !== void 0) { this._lifeCycleHooks[event].forEach((hook) => { result = this._chainOrCall(result, () => { return hook(this, subCommand); }); }); } return result; } /** * Process arguments in context of this command. * Returns action result, in case it is a promise. * * @private */ _parseCommand(operands, unknown2) { const parsed = this.parseOptions(unknown2); this._parseOptionsEnv(); this._parseOptionsImplied(); operands = operands.concat(parsed.operands); unknown2 = parsed.unknown; this.args = operands.concat(unknown2); if (operands && this._findCommand(operands[0])) { return this._dispatchSubcommand(operands[0], operands.slice(1), unknown2); } if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) { return this._dispatchHelpCommand(operands[1]); } if (this._defaultCommandName) { this._outputHelpIfRequested(unknown2); return this._dispatchSubcommand( this._defaultCommandName, operands, unknown2 ); } if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { this.help({ error: true }); } this._outputHelpIfRequested(parsed.unknown); this._checkForMissingMandatoryOptions(); this._checkForConflictingOptions(); const checkForUnknownOptions = () => { if (parsed.unknown.length > 0) { this.unknownOption(parsed.unknown[0]); } }; const commandEvent = `command:${this.name()}`; if (this._actionHandler) { checkForUnknownOptions(); this._processArguments(); let promiseChain; promiseChain = this._chainOrCallHooks(promiseChain, "preAction"); promiseChain = this._chainOrCall( promiseChain, () => this._actionHandler(this.processedArgs) ); if (this.parent) { promiseChain = this._chainOrCall(promiseChain, () => { this.parent.emit(commandEvent, operands, unknown2); }); } promiseChain = this._chainOrCallHooks(promiseChain, "postAction"); return promiseChain; } if (this.parent && this.parent.listenerCount(commandEvent)) { checkForUnknownOptions(); this._processArguments(); this.parent.emit(commandEvent, operands, unknown2); } else if (operands.length) { if (this._findCommand("*")) { return this._dispatchSubcommand("*", operands, unknown2); } if (this.listenerCount("command:*")) { this.emit("command:*", operands, unknown2); } else if (this.commands.length) { this.unknownCommand(); } else { checkForUnknownOptions(); this._processArguments(); } } else if (this.commands.length) { checkForUnknownOptions(); this.help({ error: true }); } else { checkForUnknownOptions(); this._processArguments(); } } /** * Find matching command. * * @private * @return {Command | undefined} */ _findCommand(name) { if (!name) return void 0; return this.commands.find( (cmd) => cmd._name === name || cmd._aliases.includes(name) ); } /** * Return an option matching `arg` if any. * * @param {string} arg * @return {Option} * @package */ _findOption(arg) { return this.options.find((option) => option.is(arg)); } /** * Display an error message if a mandatory option does not have a value. * Called after checking for help flags in leaf subcommand. * * @private */ _checkForMissingMandatoryOptions() { this._getCommandAndAncestors().forEach((cmd) => { cmd.options.forEach((anOption) => { if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) { cmd.missingMandatoryOptionValue(anOption); } }); }); } /** * Display an error message if conflicting options are used together in this. * * @private */ _checkForConflictingLocalOptions() { const definedNonDefaultOptions = this.options.filter((option) => { const optionKey = option.attributeName(); if (this.getOptionValue(optionKey) === void 0) { return false; } return this.getOptionValueSource(optionKey) !== "default"; }); const optionsWithConflicting = definedNonDefaultOptions.filter( (option) => option.conflictsWith.length > 0 ); optionsWithConflicting.forEach((option) => { const conflictingAndDefined = definedNonDefaultOptions.find( (defined) => option.conflictsWith.includes(defined.attributeName()) ); if (conflictingAndDefined) { this._conflictingOption(option, conflictingAndDefined); } }); } /** * Display an error message if conflicting options are used together. * Called after checking for help flags in leaf subcommand. * * @private */ _checkForConflictingOptions() { this._getCommandAndAncestors().forEach((cmd) => { cmd._checkForConflictingLocalOptions(); }); } /** * Parse options from `argv` removing known options, * and return argv split into operands and unknown arguments. * * Side effects: modifies command by storing options. Does not reset state if called again. * * Examples: * * argv => operands, unknown * --known kkk op => [op], [] * op --known kkk => [op], [] * sub --unknown uuu op => [sub], [--unknown uuu op] * sub -- --unknown uuu op => [sub --unknown uuu op], [] * * @param {string[]} argv * @return {{operands: string[], unknown: string[]}} */ parseOptions(argv) { const operands = []; const unknown2 = []; let dest = operands; const args = argv.slice(); function maybeOption(arg) { return arg.length > 1 && arg[0] === "-"; } let activeVariadicOption = null; while (args.length) { const arg = args.shift(); if (arg === "--") { if (dest === unknown2) dest.push(arg); dest.push(...args); break; } if (activeVariadicOption && !maybeOption(arg)) { this.emit(`option:${activeVariadicOption.name()}`, arg); continue; } activeVariadicOption = null; if (maybeOption(arg)) { const option = this._findOption(arg); if (option) { if (option.required) { const value = args.shift(); if (value === void 0) this.optionMissingArgument(option); this.emit(`option:${option.name()}`, value); } else if (option.optional) { let value = null; if (args.length > 0 && !maybeOption(args[0])) { value = args.shift(); } this.emit(`option:${option.name()}`, value); } else { this.emit(`option:${option.name()}`); } activeVariadicOption = option.variadic ? option : null; continue; } } if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") { const option = this._findOption(`-${arg[1]}`); if (option) { if (option.required || option.optional && this._combineFlagAndOptionalValue) { this.emit(`option:${option.name()}`, arg.slice(2)); } else { this.emit(`option:${option.name()}`); args.unshift(`-${arg.slice(2)}`); } continue; } } if (/^--[^=]+=/.test(arg)) { const index = arg.indexOf("="); const option = this._findOption(arg.slice(0, index)); if (option && (option.required || option.optional)) { this.emit(`option:${option.name()}`, arg.slice(index + 1)); continue; } } if (maybeOption(arg)) { dest = unknown2; } if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown2.length === 0) { if (this._findCommand(arg)) { operands.push(arg); if (args.length > 0) unknown2.push(...args); break; } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) { operands.push(arg); if (args.length > 0) operands.push(...args); break; } else if (this._defaultCommandName) { unknown2.push(arg); if (args.length > 0) unknown2.push(...args); break; } } if (this._passThroughOptions) { dest.push(arg); if (args.length > 0) dest.push(...args); break; } dest.push(arg); } return { operands, unknown: unknown2 }; } /** * Return an object containing local option values as key-value pairs. * * @return {object} */ opts() { if (this._storeOptionsAsProperties) { const result = {}; const len = this.options.length; for (let i = 0; i < len; i++) { const key = this.options[i].attributeName(); result[key] = key === this._versionOptionName ? this._version : this[key]; } return result; } return this._optionValues; } /** * Return an object containing merged local and global option values as key-value pairs. * * @return {object} */ optsWithGlobals() { return this._getCommandAndAncestors().reduce( (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {} ); } /** * Display error message and exit (or call exitOverride). * * @param {string} message * @param {object} [errorOptions] * @param {string} [errorOptions.code] - an id string representing the error * @param {number} [errorOptions.exitCode] - used with process.exit */ error(message, errorOptions) { this._outputConfiguration.outputError( `${message} `, this._outputConfiguration.writeErr ); if (typeof this._showHelpAfterError === "string") { this._outputConfiguration.writeErr(`${this._showHelpAfterError} `); } else if (this._showHelpAfterError) { this._outputConfiguration.writeErr("\n"); this.outputHelp({ error: true }); } const config2 = errorOptions || {}; const exitCode = config2.exitCode || 1; const code = config2.code || "commander.error"; this._exit(exitCode, code, message); } /** * Apply any option related environment variables, if option does * not have a value from cli or client code. * * @private */ _parseOptionsEnv() { this.options.forEach((option) => { if (option.envVar && option.envVar in process5.env) { const optionKey = option.attributeName(); if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes( this.getOptionValueSource(optionKey) )) { if (option.required || option.optional) { this.emit(`optionEnv:${option.name()}`, process5.env[option.envVar]); } else { this.emit(`optionEnv:${option.name()}`); } } } }); } /** * Apply any implied option values, if option is undefined or default value. * * @private */ _parseOptionsImplied() { const dualHelper = new DualOptions(this.options); const hasCustomOptionValue = (optionKey) => { return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey)); }; this.options.filter( (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption( this.getOptionValue(option.attributeName()), option ) ).forEach((option) => { Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => { this.setOptionValueWithSource( impliedKey, option.implied[impliedKey], "implied" ); }); }); } /** * Argument `name` is missing. * * @param {string} name * @private */ missingArgument(name) { const message = `error: missing required argument '${name}'`; this.error(message, { code: "commander.missingArgument" }); } /** * `Option` is missing an argument. * * @param {Option} option * @private */ optionMissingArgument(option) { const message = `error: option '${option.flags}' argument missing`; this.error(message, { code: "commander.optionMissingArgument" }); } /** * `Option` does not have a value, and is a mandatory option. * * @param {Option} option * @private */ missingMandatoryOptionValue(option) { const message = `error: required option '${option.flags}' not specified`; this.error(message, { code: "commander.missingMandatoryOptionValue" }); } /** * `Option` conflicts with another option. * * @param {Option} option * @param {Option} conflictingOption * @private */ _conflictingOption(option, conflictingOption) { const findBestOptionFromValue = (option2) => { const optionKey = option2.attributeName(); const optionValue = this.getOptionValue(optionKey); const negativeOption = this.options.find( (target) => target.negate && optionKey === target.attributeName() ); const positiveOption = this.options.find( (target) => !target.negate && optionKey === target.attributeName() ); if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) { return negativeOption; } return positiveOption || option2; }; const getErrorMessage = (option2) => { const bestOption = findBestOptionFromValue(option2); const optionKey = bestOption.attributeName(); const source = this.getOptionValueSource(optionKey); if (source === "env") { return `environment variable '${bestOption.envVar}'`; } return `option '${bestOption.flags}'`; }; const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`; this.error(message, { code: "commander.conflictingOption" }); } /** * Unknown option `flag`. * * @param {string} flag * @private */ unknownOption(flag) { if (this._allowUnknownOption) return; let suggestion = ""; if (flag.startsWith("--") && this._showSuggestionAfterError) { let candidateFlags = []; let command = this; do { const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long); candidateFlags = candidateFlags.concat(moreFlags); command = command.parent; } while (command && !command._enablePositionalOptions); suggestion = suggestSimilar(flag, candidateFlags); } const message = `error: unknown option '${flag}'${suggestion}`; this.error(message, { code: "commander.unknownOption" }); } /** * Excess arguments, more than expected. * * @param {string[]} receivedArgs * @private */ _excessArguments(receivedArgs) { if (this._allowExcessArguments) return; const expected = this.registeredArguments.length; const s = expected === 1 ? "" : "s"; const forSubcommand = this.parent ? ` for '${this.name()}'` : ""; const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; this.error(message, { code: "commander.excessArguments" }); } /** * Unknown command. * * @private */ unknownCommand() { const unknownName = this.args[0]; let suggestion = ""; if (this._showSuggestionAfterError) { const candidateNames = []; this.createHelp().visibleCommands(this).forEach((command) => { candidateNames.push(command.name()); if (command.alias()) candidateNames.push(command.alias()); }); suggestion = suggestSimilar(unknownName, candidateNames); } const message = `error: unknown command '${unknownName}'${suggestion}`; this.error(message, { code: "commander.unknownCommand" }); } /** * Get or set the program version. * * This method auto-registers the "-V, --version" option which will print the version number. * * You can optionally supply the flags and description to override the defaults. * * @param {string} [str] * @param {string} [flags] * @param {string} [description] * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments */ version(str, flags, description) { if (str === void 0) return this._version; this._version = str; flags = flags || "-V, --version"; description = description || "output the version number"; const versionOption = this.createOption(flags, description); this._versionOptionName = versionOption.attributeName(); this._registerOption(versionOption); this.on("option:" + versionOption.name(), () => { this._outputConfiguration.writeOut(`${str} `); this._exit(0, "commander.version", str); }); return this; } /** * Set the description. * * @param {string} [str] * @param {object} [argsDescription] * @return {(string|Command)} */ description(str, argsDescription) { if (str === void 0 && argsDescription === void 0) return this._description; this._description = str; if (argsDescription) { this._argsDescription = argsDescription; } return this; } /** * Set the summary. Used when listed as subcommand of parent. * * @param {string} [str] * @return {(string|Command)} */ summary(str) { if (str === void 0) return this._summary; this._summary = str; return this; } /** * Set an alias for the command. * * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. * * @param {string} [alias] * @return {(string|Command)} */ alias(alias) { if (alias === void 0) return this._aliases[0]; let command = this; if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { command = this.commands[this.commands.length - 1]; } if (alias === command._name) throw new Error("Command alias can't be the same as its name"); const matchingCommand = this.parent?._findCommand(alias); if (matchingCommand) { const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|"); throw new Error( `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'` ); } command._aliases.push(alias); return this; } /** * Set aliases for the command. * * Only the first alias is shown in the auto-generated help. * * @param {string[]} [aliases] * @return {(string[]|Command)} */ aliases(aliases) { if (aliases === void 0) return this._aliases; aliases.forEach((alias) => this.alias(alias)); return this; } /** * Set / get the command usage `str`. * * @param {string} [str] * @return {(string|Command)} */ usage(str) { if (str === void 0) { if (this._usage) return this._usage; const args = this.registeredArguments.map((arg) => { return humanReadableArgName(arg); }); return [].concat( this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : [] ).join(" "); } this._usage = str; return this; } /** * Get or set the name of the command. * * @param {string} [str] * @return {(string|Command)} */ name(str) { if (str === void 0) return this._name; this._name = str; return this; } /** * Set the name of the command from script filename, such as process.argv[1], * or require.main.filename, or __filename. * * (Used internally and public although not documented in README.) * * @example * program.nameFromFilename(require.main.filename); * * @param {string} filename * @return {Command} */ nameFromFilename(filename) { this._name = path.basename(filename, path.extname(filename)); return this; } /** * Get or set the directory for searching for executable subcommands of this command. * * @example * program.executableDir(__dirname); * // or * program.executableDir('subcommands'); * * @param {string} [path] * @return {(string|null|Command)} */ executableDir(path2) { if (path2 === void 0) return this._executableDir; this._executableDir = path2; return this; } /** * Return program help documentation. * * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout * @return {string} */ helpInformation(contextOptions) { const helper = this.createHelp(); const context = this._getOutputContext(contextOptions); helper.prepareContext({ error: context.error, helpWidth: context.helpWidth, outputHasColors: context.hasColors }); const text = helper.formatHelp(this, helper); if (context.hasColors) return text; return this._outputConfiguration.stripColor(text); } /** * @typedef HelpContext * @type {object} * @property {boolean} error * @property {number} helpWidth * @property {boolean} hasColors * @property {function} write - includes stripColor if needed * * @returns {HelpContext} * @private */ _getOutputContext(contextOptions) { contextOptions = contextOptions || {}; const error48 = !!contextOptions.error; let baseWrite; let hasColors; let helpWidth; if (error48) { baseWrite = (str) => this._outputConfiguration.writeErr(str); hasColors = this._outputConfiguration.getErrHasColors(); helpWidth = this._outputConfiguration.getErrHelpWidth(); } else { baseWrite = (str) => this._outputConfiguration.writeOut(str); hasColors = this._outputConfiguration.getOutHasColors(); helpWidth = this._outputConfiguration.getOutHelpWidth(); } const write = (str) => { if (!hasColors) str = this._outputConfiguration.stripColor(str); return baseWrite(str); }; return { error: error48, write, hasColors, helpWidth }; } /** * Output help information for this command. * * Outputs built-in help, and custom text added using `.addHelpText()`. * * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout */ outputHelp(contextOptions) { let deprecatedCallback; if (typeof contextOptions === "function") { deprecatedCallback = contextOptions; contextOptions = void 0; } const outputContext = this._getOutputContext(contextOptions); const eventContext = { error: outputContext.error, write: outputContext.write, command: this }; this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext)); this.emit("beforeHelp", eventContext); let helpInformation = this.helpInformation({ error: outputContext.error }); if (deprecatedCallback) { helpInformation = deprecatedCallback(helpInformation); if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) { throw new Error("outputHelp callback must return a string or a Buffer"); } } outputContext.write(helpInformation); if (this._getHelpOption()?.long) { this.emit(this._getHelpOption().long); } this.emit("afterHelp", eventContext); this._getCommandAndAncestors().forEach( (command) => command.emit("afterAllHelp", eventContext) ); } /** * You can pass in flags and a description to customise the built-in help option. * Pass in false to disable the built-in help option. * * @example * program.helpOption('-?, --help' 'show help'); // customise * program.helpOption(false); // disable * * @param {(string | boolean)} flags * @param {string} [description] * @return {Command} `this` command for chaining */ helpOption(flags, description) { if (typeof flags === "boolean") { if (flags) { this._helpOption = this._helpOption ?? void 0; } else { this._helpOption = null; } return this; } flags = flags ?? "-h, --help"; description = description ?? "display help for command"; this._helpOption = this.createOption(flags, description); return this; } /** * Lazy create help option. * Returns null if has been disabled with .helpOption(false). * * @returns {(Option | null)} the help option * @package */ _getHelpOption() { if (this._helpOption === void 0) { this.helpOption(void 0, void 0); } return this._helpOption; } /** * Supply your own option to use for the built-in help option. * This is an alternative to using helpOption() to customise the flags and description etc. * * @param {Option} option * @return {Command} `this` command for chaining */ addHelpOption(option) { this._helpOption = option; return this; } /** * Output help information and exit. * * Outputs built-in help, and custom text added using `.addHelpText()`. * * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout */ help(contextOptions) { this.outputHelp(contextOptions); let exitCode = Number(process5.exitCode ?? 0); if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) { exitCode = 1; } this._exit(exitCode, "commander.help", "(outputHelp)"); } /** * // Do a little typing to coordinate emit and listener for the help text events. * @typedef HelpTextEventContext * @type {object} * @property {boolean} error * @property {Command} command * @property {function} write */ /** * Add additional text to be displayed with the built-in help. * * Position is 'before' or 'after' to affect just this command, * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. * * @param {string} position - before or after built-in help * @param {(string | Function)} text - string to add, or a function returning a string * @return {Command} `this` command for chaining */ addHelpText(position, text) { const allowedValues = ["beforeAll", "before", "after", "afterAll"]; if (!allowedValues.includes(position)) { throw new Error(`Unexpected value for position to addHelpText. Expecting one of '${allowedValues.join("', '")}'`); } const helpEvent = `${position}Help`; this.on(helpEvent, (context) => { let helpStr; if (typeof text === "function") { helpStr = text({ error: context.error, command: context.command }); } else { helpStr = text; } if (helpStr) { context.write(`${helpStr} `); } }); return this; } /** * Output help information if help flags specified * * @param {Array} args - array of options to search for help flags * @private */ _outputHelpIfRequested(args) { const helpOption = this._getHelpOption(); const helpRequested = helpOption && args.find((arg) => helpOption.is(arg)); if (helpRequested) { this.outputHelp(); this._exit(0, "commander.helpDisplayed", "(outputHelp)"); } } }; function incrementNodeInspectorPort(args) { return args.map((arg) => { if (!arg.startsWith("--inspect")) { return arg; } let debugOption; let debugHost = "127.0.0.1"; let debugPort = "9229"; let match; if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { debugOption = match[1]; } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { debugOption = match[1]; if (/^\d+$/.test(match[3])) { debugPort = match[3]; } else { debugHost = match[3]; } } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { debugOption = match[1]; debugHost = match[3]; debugPort = match[4]; } if (debugOption && debugPort !== "0") { return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; } return arg; }); } function useColor() { if (process5.env.NO_COLOR || process5.env.FORCE_COLOR === "0" || process5.env.FORCE_COLOR === "false") return false; if (process5.env.FORCE_COLOR || process5.env.CLICOLOR_FORCE !== void 0) return true; return void 0; } exports2.Command = Command2; exports2.useColor = useColor; } }); // node_modules/commander/index.js var require_commander = __commonJS({ "node_modules/commander/index.js"(exports2) { var { Argument: Argument2 } = require_argument(); var { Command: Command2 } = require_command(); var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error(); var { Help: Help2 } = require_help(); var { Option: Option2 } = require_option(); exports2.program = new Command2(); exports2.createCommand = (name) => new Command2(name); exports2.createOption = (flags, description) => new Option2(flags, description); exports2.createArgument = (name, description) => new Argument2(name, description); exports2.Command = Command2; exports2.Option = Option2; exports2.Argument = Argument2; exports2.Help = Help2; exports2.CommanderError = CommanderError2; exports2.InvalidArgumentError = InvalidArgumentError2; exports2.InvalidOptionArgumentError = InvalidArgumentError2; } }); // node_modules/progress/lib/node-progress.js var require_node_progress = __commonJS({ "node_modules/progress/lib/node-progress.js"(exports2, module2) { exports2 = module2.exports = ProgressBar; function ProgressBar(fmt, options) { this.stream = options.stream || process.stderr; if (typeof options == "number") { var total = options; options = {}; options.total = total; } else { options = options || {}; if ("string" != typeof fmt) throw new Error("format required"); if ("number" != typeof options.total) throw new Error("total required"); } this.fmt = fmt; this.curr = options.curr || 0; this.total = options.total; this.width = options.width || this.total; this.clear = options.clear; this.chars = { complete: options.complete || "=", incomplete: options.incomplete || "-", head: options.head || (options.complete || "=") }; this.renderThrottle = options.renderThrottle !== 0 ? options.renderThrottle || 16 : 0; this.lastRender = -Infinity; this.callback = options.callback || function() { }; this.tokens = {}; this.lastDraw = ""; } ProgressBar.prototype.tick = function(len, tokens) { if (len !== 0) len = len || 1; if ("object" == typeof len) tokens = len, len = 1; if (tokens) this.tokens = tokens; if (0 == this.curr) this.start = /* @__PURE__ */ new Date(); this.curr += len; this.render(); if (this.curr >= this.total) { this.render(void 0, true); this.complete = true; this.terminate(); this.callback(this); return; } }; ProgressBar.prototype.render = function(tokens, force) { force = force !== void 0 ? force : false; if (tokens) this.tokens = tokens; if (!this.stream.isTTY) return; var now = Date.now(); var delta = now - this.lastRender; if (!force && delta < this.renderThrottle) { return; } else { this.lastRender = now; } var ratio = this.curr / this.total; ratio = Math.min(Math.max(ratio, 0), 1); var percent = Math.floor(ratio * 100); var incomplete, complete, completeLength; var elapsed = /* @__PURE__ */ new Date() - this.start; var eta = percent == 100 ? 0 : elapsed * (this.total / this.curr - 1); var rate = this.curr / (elapsed / 1e3); var str = this.fmt.replace(":current", this.curr).replace(":total", this.total).replace(":elapsed", isNaN(elapsed) ? "0.0" : (elapsed / 1e3).toFixed(1)).replace(":eta", isNaN(eta) || !isFinite(eta) ? "0.0" : (eta / 1e3).toFixed(1)).replace(":percent", percent.toFixed(0) + "%").replace(":rate", Math.round(rate)); var availableSpace = Math.max(0, this.stream.columns - str.replace(":bar", "").length); if (availableSpace && process.platform === "win32") { availableSpace = availableSpace - 1; } var width = Math.min(this.width, availableSpace); completeLength = Math.round(width * ratio); complete = Array(Math.max(0, completeLength + 1)).join(this.chars.complete); incomplete = Array(Math.max(0, width - completeLength + 1)).join(this.chars.incomplete); if (completeLength > 0) complete = complete.slice(0, -1) + this.chars.head; str = str.replace(":bar", complete + incomplete); if (this.tokens) for (var key in this.tokens) str = str.replace(":" + key, this.tokens[key]); if (this.lastDraw !== str) { this.stream.cursorTo(0); this.stream.write(str); this.stream.clearLine(1); this.lastDraw = str; } }; ProgressBar.prototype.update = function(ratio, tokens) { var goal = Math.floor(ratio * this.total); var delta = goal - this.curr; this.tick(delta, tokens); }; ProgressBar.prototype.interrupt = function(message) { this.stream.clearLine(); this.stream.cursorTo(0); this.stream.write(message); this.stream.write("\n"); this.stream.write(this.lastDraw); }; ProgressBar.prototype.terminate = function() { if (this.clear) { if (this.stream.clearLine) { this.stream.clearLine(); this.stream.cursorTo(0); } } else { this.stream.write("\n"); } }; } }); // node_modules/progress/index.js var require_progress = __commonJS({ "node_modules/progress/index.js"(exports2, module2) { module2.exports = require_node_progress(); } }); // node_modules/smart-buffer/build/utils.js var require_utils = __commonJS({ "node_modules/smart-buffer/build/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var buffer_1 = require("buffer"); var ERRORS = { INVALID_ENCODING: "Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.", INVALID_SMARTBUFFER_SIZE: "Invalid size provided. Size must be a valid integer greater than zero.", INVALID_SMARTBUFFER_BUFFER: "Invalid Buffer provided in SmartBufferOptions.", INVALID_SMARTBUFFER_OBJECT: "Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.", INVALID_OFFSET: "An invalid offset value was provided.", INVALID_OFFSET_NON_NUMBER: "An invalid offset value was provided. A numeric value is required.", INVALID_LENGTH: "An invalid length value was provided.", INVALID_LENGTH_NON_NUMBER: "An invalid length value was provived. A numeric value is required.", INVALID_TARGET_OFFSET: "Target offset is beyond the bounds of the internal SmartBuffer data.", INVALID_TARGET_LENGTH: "Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.", INVALID_READ_BEYOND_BOUNDS: "Attempted to read beyond the bounds of the managed data.", INVALID_WRITE_BEYOND_BOUNDS: "Attempted to write beyond the bounds of the managed data." }; exports2.ERRORS = ERRORS; function checkEncoding(encoding) { if (!buffer_1.Buffer.isEncoding(encoding)) { throw new Error(ERRORS.INVALID_ENCODING); } } exports2.checkEncoding = checkEncoding; function isFiniteInteger(value) { return typeof value === "number" && isFinite(value) && isInteger(value); } exports2.isFiniteInteger = isFiniteInteger; function checkOffsetOrLengthValue(value, offset) { if (typeof value === "number") { if (!isFiniteInteger(value) || value < 0) { throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); } } else { throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); } } function checkLengthValue(length) { checkOffsetOrLengthValue(length, false); } exports2.checkLengthValue = checkLengthValue; function checkOffsetValue(offset) { checkOffsetOrLengthValue(offset, true); } exports2.checkOffsetValue = checkOffsetValue; function checkTargetOffset(offset, buff) { if (offset < 0 || offset > buff.length) { throw new Error(ERRORS.INVALID_TARGET_OFFSET); } } exports2.checkTargetOffset = checkTargetOffset; function isInteger(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; } function bigIntAndBufferInt64Check(bufferMethod) { if (typeof BigInt === "undefined") { throw new Error("Platform does not support JS BigInt type."); } if (typeof buffer_1.Buffer.prototype[bufferMethod] === "undefined") { throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`); } } exports2.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check; } }); // node_modules/smart-buffer/build/smartbuffer.js var require_smartbuffer = __commonJS({ "node_modules/smart-buffer/build/smartbuffer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var utils_1 = require_utils(); var DEFAULT_SMARTBUFFER_SIZE = 4096; var DEFAULT_SMARTBUFFER_ENCODING = "utf8"; var SmartBuffer = class _SmartBuffer { /** * Creates a new SmartBuffer instance. * * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. */ constructor(options) { this.length = 0; this._encoding = DEFAULT_SMARTBUFFER_ENCODING; this._writeOffset = 0; this._readOffset = 0; if (_SmartBuffer.isSmartBufferOptions(options)) { if (options.encoding) { utils_1.checkEncoding(options.encoding); this._encoding = options.encoding; } if (options.size) { if (utils_1.isFiniteInteger(options.size) && options.size > 0) { this._buff = Buffer.allocUnsafe(options.size); } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); } } else if (options.buff) { if (Buffer.isBuffer(options.buff)) { this._buff = options.buff; this.length = options.buff.length; } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); } } else { this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } else { if (typeof options !== "undefined") { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); } this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } /** * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. * * @param size { Number } The size of the internal Buffer. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromSize(size, encoding) { return new this({ size, encoding }); } /** * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. * * @param buffer { Buffer } The Buffer to use as the internal Buffer value. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromBuffer(buff, encoding) { return new this({ buff, encoding }); } /** * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. * * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. */ static fromOptions(options) { return new this(options); } /** * Type checking function that determines if an object is a SmartBufferOptions object. */ static isSmartBufferOptions(options) { const castOptions = options; return castOptions && (castOptions.encoding !== void 0 || castOptions.size !== void 0 || castOptions.buff !== void 0); } // Signed integers /** * Reads an Int8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt8(offset) { return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); } /** * Reads an Int16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); } /** * Reads an Int16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); } /** * Reads an Int32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); } /** * Reads an Int32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); } /** * Reads a BigInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64BE(offset) { utils_1.bigIntAndBufferInt64Check("readBigInt64BE"); return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); } /** * Reads a BigInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64LE(offset) { utils_1.bigIntAndBufferInt64Check("readBigInt64LE"); return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); } /** * Writes an Int8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt8(value, offset) { this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); return this; } /** * Inserts an Int8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); } /** * Writes an Int16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Inserts an Int16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Writes an Int16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Inserts an Int16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Writes an Int32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Inserts an Int32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Writes an Int32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Inserts an Int32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Writes a BigInt64BE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"); return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Inserts a BigInt64BE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"); return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Writes a BigInt64LE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"); return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } /** * Inserts a Int64LE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"); return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } // Unsigned Integers /** * Reads an UInt8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt8(offset) { return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); } /** * Reads an UInt16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); } /** * Reads an UInt16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); } /** * Reads an UInt32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); } /** * Reads an UInt32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); } /** * Reads a BigUInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64BE(offset) { utils_1.bigIntAndBufferInt64Check("readBigUInt64BE"); return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); } /** * Reads a BigUInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64LE(offset) { utils_1.bigIntAndBufferInt64Check("readBigUInt64LE"); return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); } /** * Writes an UInt8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt8(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Inserts an UInt8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Writes an UInt16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Inserts an UInt16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Writes an UInt16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Inserts an UInt16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Writes an UInt32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Inserts an UInt32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Writes an UInt32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Inserts an UInt32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Writes a BigUInt64BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"); return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Inserts a BigUInt64BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"); return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Writes a BigUInt64LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"); return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } /** * Inserts a BigUInt64LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"); return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } // Floating Point /** * Reads an FloatBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatBE(offset) { return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset); } /** * Reads an FloatLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatLE(offset) { return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset); } /** * Writes a FloatBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Inserts a FloatBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Writes a FloatLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } /** * Inserts a FloatLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } // Double Floating Point /** * Reads an DoublEBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleBE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset); } /** * Reads an DoubleLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleLE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset); } /** * Writes a DoubleBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Inserts a DoubleBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Writes a DoubleLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } /** * Inserts a DoubleLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } // Strings /** * Reads a String from the current read position. * * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for * the string (Defaults to instance level encoding). * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readString(arg1, encoding) { let lengthVal; if (typeof arg1 === "number") { utils_1.checkLengthValue(arg1); lengthVal = Math.min(arg1, this.length - this._readOffset); } else { encoding = arg1; lengthVal = this.length - this._readOffset; } if (typeof encoding !== "undefined") { utils_1.checkEncoding(encoding); } const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding); this._readOffset += lengthVal; return value; } /** * Inserts a String * * @param value { String } The String value to insert. * @param offset { Number } The offset to insert the string at. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertString(value, offset, encoding) { utils_1.checkOffsetValue(offset); return this._handleString(value, true, offset, encoding); } /** * Writes a String * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeString(value, arg2, encoding) { return this._handleString(value, false, arg2, encoding); } /** * Reads a null-terminated String from the current read position. * * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readStringNT(encoding) { if (typeof encoding !== "undefined") { utils_1.checkEncoding(encoding); } let nullPos = this.length; for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0) { nullPos = i; break; } } const value = this._buff.slice(this._readOffset, nullPos); this._readOffset = nullPos + 1; return value.toString(encoding || this._encoding); } /** * Inserts a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertStringNT(value, offset, encoding) { utils_1.checkOffsetValue(offset); this.insertString(value, offset, encoding); this.insertUInt8(0, offset + value.length); return this; } /** * Writes a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeStringNT(value, arg2, encoding) { this.writeString(value, arg2, encoding); this.writeUInt8(0, typeof arg2 === "number" ? arg2 + value.length : this.writeOffset); return this; } // Buffers /** * Reads a Buffer from the internal read position. * * @param length { Number } The length of data to read as a Buffer. * * @return { Buffer } */ readBuffer(length) { if (typeof length !== "undefined") { utils_1.checkLengthValue(length); } const lengthVal = typeof length === "number" ? length : this.length; const endPoint = Math.min(this.length, this._readOffset + lengthVal); const value = this._buff.slice(this._readOffset, endPoint); this._readOffset = endPoint; return value; } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBuffer(value, offset) { utils_1.checkOffsetValue(offset); return this._handleBuffer(value, true, offset); } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBuffer(value, offset) { return this._handleBuffer(value, false, offset); } /** * Reads a null-terminated Buffer from the current read poisiton. * * @return { Buffer } */ readBufferNT() { let nullPos = this.length; for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0) { nullPos = i; break; } } const value = this._buff.slice(this._readOffset, nullPos); this._readOffset = nullPos + 1; return value; } /** * Inserts a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBufferNT(value, offset) { utils_1.checkOffsetValue(offset); this.insertBuffer(value, offset); this.insertUInt8(0, offset + value.length); return this; } /** * Writes a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBufferNT(value, offset) { if (typeof offset !== "undefined") { utils_1.checkOffsetValue(offset); } this.writeBuffer(value, offset); this.writeUInt8(0, typeof offset === "number" ? offset + value.length : this._writeOffset); return this; } /** * Clears the SmartBuffer instance to its original empty state. */ clear() { this._writeOffset = 0; this._readOffset = 0; this.length = 0; return this; } /** * Gets the remaining data left to be read from the SmartBuffer instance. * * @return { Number } */ remaining() { return this.length - this._readOffset; } /** * Gets the current read offset value of the SmartBuffer instance. * * @return { Number } */ get readOffset() { return this._readOffset; } /** * Sets the read offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set readOffset(offset) { utils_1.checkOffsetValue(offset); utils_1.checkTargetOffset(offset, this); this._readOffset = offset; } /** * Gets the current write offset value of the SmartBuffer instance. * * @return { Number } */ get writeOffset() { return this._writeOffset; } /** * Sets the write offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set writeOffset(offset) { utils_1.checkOffsetValue(offset); utils_1.checkTargetOffset(offset, this); this._writeOffset = offset; } /** * Gets the currently set string encoding of the SmartBuffer instance. * * @return { BufferEncoding } The string Buffer encoding currently set. */ get encoding() { return this._encoding; } /** * Sets the string encoding of the SmartBuffer instance. * * @param encoding { BufferEncoding } The string Buffer encoding to set. */ set encoding(encoding) { utils_1.checkEncoding(encoding); this._encoding = encoding; } /** * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) * * @return { Buffer } The Buffer value. */ get internalBuffer() { return this._buff; } /** * Gets the value of the internal managed Buffer (Includes managed data only) * * @param { Buffer } */ toBuffer() { return this._buff.slice(0, this.length); } /** * Gets the String value of the internal managed Buffer * * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding). */ toString(encoding) { const encodingVal = typeof encoding === "string" ? encoding : this._encoding; utils_1.checkEncoding(encodingVal); return this._buff.toString(encodingVal, 0, this.length); } /** * Destroys the SmartBuffer instance. */ destroy() { this.clear(); return this; } /** * Handles inserting and writing strings. * * @param value { String } The String value to insert. * @param isInsert { Boolean } True if inserting a string, false if writing. * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). */ _handleString(value, isInsert, arg3, encoding) { let offsetVal = this._writeOffset; let encodingVal = this._encoding; if (typeof arg3 === "number") { offsetVal = arg3; } else if (typeof arg3 === "string") { utils_1.checkEncoding(arg3); encodingVal = arg3; } if (typeof encoding === "string") { utils_1.checkEncoding(encoding); encodingVal = encoding; } const byteLength = Buffer.byteLength(value, encodingVal); if (isInsert) { this.ensureInsertable(byteLength, offsetVal); } else { this._ensureWriteable(byteLength, offsetVal); } this._buff.write(value, offsetVal, byteLength, encodingVal); if (isInsert) { this._writeOffset += byteLength; } else { if (typeof arg3 === "number") { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength); } else { this._writeOffset += byteLength; } } return this; } /** * Handles writing or insert of a Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. */ _handleBuffer(value, isInsert, offset) { const offsetVal = typeof offset === "number" ? offset : this._writeOffset; if (isInsert) { this.ensureInsertable(value.length, offsetVal); } else { this._ensureWriteable(value.length, offsetVal); } value.copy(this._buff, offsetVal); if (isInsert) { this._writeOffset += value.length; } else { if (typeof offset === "number") { this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length); } else { this._writeOffset += value.length; } } return this; } /** * Ensures that the internal Buffer is large enough to read data. * * @param length { Number } The length of the data that needs to be read. * @param offset { Number } The offset of the data that needs to be read. */ ensureReadable(length, offset) { let offsetVal = this._readOffset; if (typeof offset !== "undefined") { utils_1.checkOffsetValue(offset); offsetVal = offset; } if (offsetVal < 0 || offsetVal + length > this.length) { throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS); } } /** * Ensures that the internal Buffer is large enough to insert data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written. */ ensureInsertable(dataLength, offset) { utils_1.checkOffsetValue(offset); this._ensureCapacity(this.length + dataLength); if (offset < this.length) { this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length); } if (offset + dataLength > this.length) { this.length = offset + dataLength; } else { this.length += dataLength; } } /** * Ensures that the internal Buffer is large enough to write data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written (defaults to writeOffset). */ _ensureWriteable(dataLength, offset) { const offsetVal = typeof offset === "number" ? offset : this._writeOffset; this._ensureCapacity(offsetVal + dataLength); if (offsetVal + dataLength > this.length) { this.length = offsetVal + dataLength; } } /** * Ensures that the internal Buffer is large enough to write at least the given amount of data. * * @param minLength { Number } The minimum length of the data needs to be written. */ _ensureCapacity(minLength) { const oldLength = this._buff.length; if (minLength > oldLength) { let data = this._buff; let newLength = oldLength * 3 / 2 + 1; if (newLength < minLength) { newLength = minLength; } this._buff = Buffer.allocUnsafe(newLength); data.copy(this._buff, 0, 0, oldLength); } } /** * Reads a numeric number value using the provided function. * * @typeparam T { number | bigint } The type of the value to be read * * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with. * @param byteSize { Number } The number of bytes read. * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead. * * @returns { T } the number value */ _readNumberValue(func, byteSize, offset) { this.ensureReadable(byteSize, offset); const value = func.call(this._buff, typeof offset === "number" ? offset : this._readOffset); if (typeof offset === "undefined") { this._readOffset += byteSize; } return value; } /** * Inserts a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _insertNumberValue(func, byteSize, value, offset) { utils_1.checkOffsetValue(offset); this.ensureInsertable(byteSize, offset); func.call(this._buff, value, offset); this._writeOffset += byteSize; return this; } /** * Writes a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _writeNumberValue(func, byteSize, value, offset) { if (typeof offset === "number") { if (offset < 0) { throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS); } utils_1.checkOffsetValue(offset); } const offsetVal = typeof offset === "number" ? offset : this._writeOffset; this._ensureWriteable(byteSize, offsetVal); func.call(this._buff, value, offsetVal); if (typeof offset === "number") { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize); } else { this._writeOffset += byteSize; } return this; } }; exports2.SmartBuffer = SmartBuffer; } }); // node_modules/socks/build/common/constants.js var require_constants2 = __commonJS({ "node_modules/socks/build/common/constants.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SOCKS5_NO_ACCEPTABLE_AUTH = exports2.SOCKS5_CUSTOM_AUTH_END = exports2.SOCKS5_CUSTOM_AUTH_START = exports2.SOCKS_INCOMING_PACKET_SIZES = exports2.SocksClientState = exports2.Socks5Response = exports2.Socks5HostType = exports2.Socks5Auth = exports2.Socks4Response = exports2.SocksCommand = exports2.ERRORS = exports2.DEFAULT_TIMEOUT = void 0; var DEFAULT_TIMEOUT = 3e4; exports2.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; var ERRORS = { InvalidSocksCommand: "An invalid SOCKS command was provided. Valid options are connect, bind, and associate.", InvalidSocksCommandForOperation: "An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.", InvalidSocksCommandChain: "An invalid SOCKS command was provided. Chaining currently only supports the connect command.", InvalidSocksClientOptionsDestination: "An invalid destination host was provided.", InvalidSocksClientOptionsExistingSocket: "An invalid existing socket was provided. This should be an instance of stream.Duplex.", InvalidSocksClientOptionsProxy: "Invalid SOCKS proxy details were provided.", InvalidSocksClientOptionsTimeout: "An invalid timeout value was provided. Please enter a value above 0 (in ms).", InvalidSocksClientOptionsProxiesLength: "At least two socks proxies must be provided for chaining.", InvalidSocksClientOptionsCustomAuthRange: "Custom auth must be a value between 0x80 and 0xFE.", InvalidSocksClientOptionsCustomAuthOptions: "When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.", NegotiationError: "Negotiation error", SocketClosed: "Socket closed", ProxyConnectionTimedOut: "Proxy connection timed out", InternalError: "SocksClient internal error (this should not happen)", InvalidSocks4HandshakeResponse: "Received invalid Socks4 handshake response", Socks4ProxyRejectedConnection: "Socks4 Proxy rejected connection", InvalidSocks4IncomingConnectionResponse: "Socks4 invalid incoming connection response", Socks4ProxyRejectedIncomingBoundConnection: "Socks4 Proxy rejected incoming bound connection", InvalidSocks5InitialHandshakeResponse: "Received invalid Socks5 initial handshake response", InvalidSocks5IntiailHandshakeSocksVersion: "Received invalid Socks5 initial handshake (invalid socks version)", InvalidSocks5InitialHandshakeNoAcceptedAuthType: "Received invalid Socks5 initial handshake (no accepted authentication type)", InvalidSocks5InitialHandshakeUnknownAuthType: "Received invalid Socks5 initial handshake (unknown authentication type)", Socks5AuthenticationFailed: "Socks5 Authentication failed", InvalidSocks5FinalHandshake: "Received invalid Socks5 final handshake response", InvalidSocks5FinalHandshakeRejected: "Socks5 proxy rejected connection", InvalidSocks5IncomingConnectionResponse: "Received invalid Socks5 incoming connection response", Socks5ProxyRejectedIncomingBoundConnection: "Socks5 Proxy rejected incoming bound connection" }; exports2.ERRORS = ERRORS; var SOCKS_INCOMING_PACKET_SIZES = { Socks5InitialHandshakeResponse: 2, Socks5UserPassAuthenticationResponse: 2, // Command response + incoming connection (bind) Socks5ResponseHeader: 5, // We need at least 5 to read the hostname length, then we wait for the address+port information. Socks5ResponseIPv4: 10, // 4 header + 4 ip + 2 port Socks5ResponseIPv6: 22, // 4 header + 16 ip + 2 port Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7, // 4 header + 1 host length + host + 2 port // Command response + incoming connection (bind) Socks4Response: 8 // 2 header + 2 port + 4 ip }; exports2.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES; var SocksCommand; (function(SocksCommand2) { SocksCommand2[SocksCommand2["connect"] = 1] = "connect"; SocksCommand2[SocksCommand2["bind"] = 2] = "bind"; SocksCommand2[SocksCommand2["associate"] = 3] = "associate"; })(SocksCommand || (exports2.SocksCommand = SocksCommand = {})); var Socks4Response; (function(Socks4Response2) { Socks4Response2[Socks4Response2["Granted"] = 90] = "Granted"; Socks4Response2[Socks4Response2["Failed"] = 91] = "Failed"; Socks4Response2[Socks4Response2["Rejected"] = 92] = "Rejected"; Socks4Response2[Socks4Response2["RejectedIdent"] = 93] = "RejectedIdent"; })(Socks4Response || (exports2.Socks4Response = Socks4Response = {})); var Socks5Auth; (function(Socks5Auth2) { Socks5Auth2[Socks5Auth2["NoAuth"] = 0] = "NoAuth"; Socks5Auth2[Socks5Auth2["GSSApi"] = 1] = "GSSApi"; Socks5Auth2[Socks5Auth2["UserPass"] = 2] = "UserPass"; })(Socks5Auth || (exports2.Socks5Auth = Socks5Auth = {})); var SOCKS5_CUSTOM_AUTH_START = 128; exports2.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START; var SOCKS5_CUSTOM_AUTH_END = 254; exports2.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END; var SOCKS5_NO_ACCEPTABLE_AUTH = 255; exports2.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH; var Socks5Response; (function(Socks5Response2) { Socks5Response2[Socks5Response2["Granted"] = 0] = "Granted"; Socks5Response2[Socks5Response2["Failure"] = 1] = "Failure"; Socks5Response2[Socks5Response2["NotAllowed"] = 2] = "NotAllowed"; Socks5Response2[Socks5Response2["NetworkUnreachable"] = 3] = "NetworkUnreachable"; Socks5Response2[Socks5Response2["HostUnreachable"] = 4] = "HostUnreachable"; Socks5Response2[Socks5Response2["ConnectionRefused"] = 5] = "ConnectionRefused"; Socks5Response2[Socks5Response2["TTLExpired"] = 6] = "TTLExpired"; Socks5Response2[Socks5Response2["CommandNotSupported"] = 7] = "CommandNotSupported"; Socks5Response2[Socks5Response2["AddressNotSupported"] = 8] = "AddressNotSupported"; })(Socks5Response || (exports2.Socks5Response = Socks5Response = {})); var Socks5HostType; (function(Socks5HostType2) { Socks5HostType2[Socks5HostType2["IPv4"] = 1] = "IPv4"; Socks5HostType2[Socks5HostType2["Hostname"] = 3] = "Hostname"; Socks5HostType2[Socks5HostType2["IPv6"] = 4] = "IPv6"; })(Socks5HostType || (exports2.Socks5HostType = Socks5HostType = {})); var SocksClientState; (function(SocksClientState2) { SocksClientState2[SocksClientState2["Created"] = 0] = "Created"; SocksClientState2[SocksClientState2["Connecting"] = 1] = "Connecting"; SocksClientState2[SocksClientState2["Connected"] = 2] = "Connected"; SocksClientState2[SocksClientState2["SentInitialHandshake"] = 3] = "SentInitialHandshake"; SocksClientState2[SocksClientState2["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse"; SocksClientState2[SocksClientState2["SentAuthentication"] = 5] = "SentAuthentication"; SocksClientState2[SocksClientState2["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse"; SocksClientState2[SocksClientState2["SentFinalHandshake"] = 7] = "SentFinalHandshake"; SocksClientState2[SocksClientState2["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse"; SocksClientState2[SocksClientState2["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection"; SocksClientState2[SocksClientState2["Established"] = 10] = "Established"; SocksClientState2[SocksClientState2["Disconnected"] = 11] = "Disconnected"; SocksClientState2[SocksClientState2["Error"] = 99] = "Error"; })(SocksClientState || (exports2.SocksClientState = SocksClientState = {})); } }); // node_modules/socks/build/common/util.js var require_util = __commonJS({ "node_modules/socks/build/common/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.shuffleArray = exports2.SocksClientError = void 0; var SocksClientError = class extends Error { constructor(message, options) { super(message); this.options = options; } }; exports2.SocksClientError = SocksClientError; function shuffleArray(array2) { for (let i = array2.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array2[i], array2[j]] = [array2[j], array2[i]]; } } exports2.shuffleArray = shuffleArray; } }); // node_modules/ip-address/dist/address-error.js var require_address_error = __commonJS({ "node_modules/ip-address/dist/address-error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.AddressError = void 0; var AddressError = class extends Error { constructor(message, parseMessage) { super(message); this.name = "AddressError"; this.parseMessage = parseMessage; } }; exports2.AddressError = AddressError; } }); // node_modules/ip-address/dist/common.js var require_common2 = __commonJS({ "node_modules/ip-address/dist/common.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.isInSubnet = isInSubnet; exports2.isCorrect = isCorrect; exports2.prefixLengthFromMask = prefixLengthFromMask; exports2.numberToPaddedHex = numberToPaddedHex; exports2.stringToPaddedHex = stringToPaddedHex; exports2.testBit = testBit; var address_error_1 = require_address_error(); function isInSubnet(address) { if (this.subnetMask < address.subnetMask) { return false; } if (this.mask(address.subnetMask) === address.mask()) { return true; } return false; } function isCorrect(defaultBits) { return function() { if (this.addressMinusSuffix !== this.correctForm()) { return false; } if (this.subnetMask === defaultBits && !this.parsedSubnet) { return true; } return this.parsedSubnet === String(this.subnetMask); }; } function prefixLengthFromMask(value, totalBits) { const binary = value.toString(2).padStart(totalBits, "0"); if (binary.length > totalBits) { throw new address_error_1.AddressError("Invalid subnet mask."); } const firstZero = binary.indexOf("0"); if (firstZero === -1) { return totalBits; } if (binary.slice(firstZero).includes("1")) { throw new address_error_1.AddressError("Invalid subnet mask."); } return firstZero; } function numberToPaddedHex(number4) { return number4.toString(16).padStart(2, "0"); } function stringToPaddedHex(numberString) { return numberToPaddedHex(parseInt(numberString, 10)); } function testBit(binaryValue, position) { const { length } = binaryValue; if (position > length) { return false; } const positionInString = length - position; return binaryValue.substring(positionInString, positionInString + 1) === "1"; } } }); // node_modules/ip-address/dist/v4/constants.js var require_constants3 = __commonJS({ "node_modules/ip-address/dist/v4/constants.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RE_SUBNET_STRING = exports2.RE_ADDRESS = exports2.GROUPS = exports2.BITS = void 0; exports2.BITS = 32; exports2.GROUPS = 4; exports2.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; exports2.RE_SUBNET_STRING = /\/\d{1,2}$/; } }); // node_modules/ip-address/dist/ipv4.js var require_ipv4 = __commonJS({ "node_modules/ip-address/dist/ipv4.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Address4 = void 0; var common = __importStar(require_common2()); var constants = __importStar(require_constants3()); var address_error_1 = require_address_error(); var isCorrect4 = common.isCorrect(constants.BITS); var Address4 = class _Address4 { constructor(address) { this.groups = constants.GROUPS; this.parsedAddress = []; this.parsedSubnet = ""; this.subnet = "/32"; this.subnetMask = 32; this.v4 = true; this.isCorrect = isCorrect4; this.isInSubnet = common.isInSubnet; this.address = address; const subnet = constants.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace("/", ""); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { throw new address_error_1.AddressError("Invalid subnet mask."); } address = address.replace(constants.RE_SUBNET_STRING, ""); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(address); } /** * Returns true if the given string is a valid IPv4 address (with optional * CIDR subnet), false otherwise. Host bits in the subnet portion are * allowed (e.g. `192.168.1.5/24` is valid); for strict network-address * validation compare `correctForm()` to `startAddress().correctForm()`, * or use `networkForm()`. */ static isValid(address) { try { new _Address4(address); return true; } catch (e) { return false; } } /** * Parses an IPv4 address string into its four octet groups and stores the * result on `this.parsedAddress`. Called automatically by the constructor; * you typically don't need to call it directly. Throws `AddressError` if * the input is not a valid IPv4 address. */ parse(address) { const groups = address.split("."); if (!address.match(constants.RE_ADDRESS)) { throw new address_error_1.AddressError("Invalid IPv4 address."); } return groups; } /** * Returns the address in correct form: octets joined with `.` and any * leading zeros stripped (e.g. `192.168.1.1`). For IPv4 this matches the * canonical dotted-decimal representation. */ correctForm() { return this.parsedAddress.map((part) => parseInt(part, 10)).join("."); } /** * Construct an `Address4` from an address and a dotted-decimal subnet * mask given as separate strings (e.g. as returned by Node's * `os.networkInterfaces()`). Throws `AddressError` if the mask is * non-contiguous (e.g. `255.0.255.0`). * @example * var address = Address4.fromAddressAndMask('192.168.1.1', '255.255.255.0'); * address.subnetMask; // 24 */ static fromAddressAndMask(address, mask) { const bits = common.prefixLengthFromMask(new _Address4(mask).bigInt(), constants.BITS); return new _Address4(`${address}/${bits}`); } /** * Construct an `Address4` from an address and a Cisco-style wildcard mask * given as separate strings (e.g. `0.0.0.255` for a `/24`). The wildcard * mask is the bitwise inverse of the subnet mask. Throws `AddressError` * if the mask is non-contiguous (e.g. `0.255.0.255`). * @example * var address = Address4.fromAddressAndWildcardMask('10.0.0.1', '0.0.0.255'); * address.subnetMask; // 24 */ static fromAddressAndWildcardMask(address, wildcardMask) { const wildcard = new _Address4(wildcardMask).bigInt(); const allOnes = (BigInt(1) << BigInt(constants.BITS)) - BigInt(1); const mask = wildcard ^ allOnes; const bits = common.prefixLengthFromMask(mask, constants.BITS); return new _Address4(`${address}/${bits}`); } /** * Construct an `Address4` from a wildcard pattern with trailing `*` * octets. The number of trailing wildcards determines the prefix * length: each `*` represents 8 bits. * * Only trailing whole-octet wildcards are supported. Partial-octet * wildcards (e.g. `192.168.0.1*`) and interior wildcards (e.g. * `192.*.0.1`) throw `AddressError`. * @example * Address4.fromWildcard('192.168.0.*').subnet; // '/24' * Address4.fromWildcard('192.168.*.*').subnet; // '/16' * Address4.fromWildcard('*.*.*.*').subnet; // '/0' */ static fromWildcard(input) { const groups = input.split("."); if (groups.length !== constants.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } let firstWildcard = -1; for (let i = 0; i < groups.length; i++) { if (groups[i] === "*") { if (firstWildcard === -1) { firstWildcard = i; } } else if (firstWildcard !== -1) { throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)"); } } const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard; const replaced = groups.map((g) => g === "*" ? "0" : g); const subnetBits = constants.BITS - trailing * 8; return new _Address4(`${replaced.join(".")}/${subnetBits}`); } /** * Converts a hex string to an IPv4 address object. Accepts 8 hex digits * with optional `:` separators (e.g. `'7f000001'` or `'7f:00:00:01'`). * Throws `AddressError` for any other length or for non-hex characters. * @param {string} hex - a hex string to convert * @returns {Address4} */ static fromHex(hex3) { const stripped = hex3.replace(/:/g, ""); if (!/^[0-9a-fA-F]{8}$/.test(stripped)) { throw new address_error_1.AddressError("IPv4 hex must be exactly 8 hex digits"); } const groups = []; for (let i = 0; i < 8; i += 2) { groups.push(parseInt(stripped.slice(i, i + 2), 16)); } return new _Address4(groups.join(".")); } /** * Converts an integer into a IPv4 address object. The integer must be a * non-negative safe integer in the range `[0, 2**32 - 1]`; otherwise * `AddressError` is thrown. * @param {integer} integer - a number to convert * @returns {Address4} */ static fromInteger(integer2) { if (!Number.isInteger(integer2) || integer2 < 0 || integer2 > 4294967295) { throw new address_error_1.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1"); } return _Address4.fromHex(integer2.toString(16).padStart(8, "0")); } /** * Return an address from in-addr.arpa form * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address * @returns {Adress4} * @example * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) * address.correctForm(); // '192.0.2.42' */ static fromArpa(arpaFormAddress) { const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ""); const address = leader.split(".").reverse().join("."); return new _Address4(address); } /** * Converts an IPv4 address object to a hex string * @returns {String} */ toHex() { return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(":"); } /** * Converts an IPv4 address object to an array of bytes. * * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toArray())`. * @returns {Array} */ toArray() { return this.parsedAddress.map((part) => parseInt(part, 10)); } /** * Converts an IPv4 address object to an IPv6 address group * @returns {String} */ toGroup6() { const output = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } return output.join(":"); } /** * Returns the address as a `bigint` * @returns {bigint} */ bigInt() { return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join("")}`); } /** * Helper function getting start address. * @returns {bigint} */ _startAddress() { return BigInt(`0b${this.mask() + "0".repeat(constants.BITS - this.subnetMask)}`); } /** * The first address in the range given by this address' subnet. * Often referred to as the Network Address. * @returns {Address4} */ startAddress() { return _Address4.fromBigInt(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @returns {Address4} */ startAddressExclusive() { const adjust = BigInt("1"); return _Address4.fromBigInt(this._startAddress() + adjust); } /** * Helper function getting end address. * @returns {bigint} */ _endAddress() { return BigInt(`0b${this.mask() + "1".repeat(constants.BITS - this.subnetMask)}`); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @returns {Address4} */ endAddress() { return _Address4.fromBigInt(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @returns {Address4} */ endAddressExclusive() { const adjust = BigInt("1"); return _Address4.fromBigInt(this._endAddress() - adjust); } /** * The dotted-decimal form of the subnet mask, e.g. `255.255.240.0` for * a `/20`. Returns an `Address4`; call `.correctForm()` for the string. * @returns {Address4} */ subnetMaskAddress() { return _Address4.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants.BITS - this.subnetMask)}`)); } /** * The Cisco-style wildcard mask, e.g. `0.0.0.255` for a `/24`. This is * the bitwise inverse of `subnetMaskAddress()`. Returns an `Address4`; * call `.correctForm()` for the string. * @returns {Address4} */ wildcardMask() { return _Address4.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants.BITS - this.subnetMask)}`)); } /** * The network address in CIDR string form, e.g. `192.168.1.0/24` for * `192.168.1.5/24`. For an address with no explicit subnet the prefix is * `/32`, e.g. `networkForm()` on `192.168.1.5` returns `192.168.1.5/32`. * @returns {string} */ networkForm() { return `${this.startAddress().correctForm()}/${this.subnetMask}`; } /** * Converts a BigInt to a v4 address object. The value must be in the * range `[0, 2**32 - 1]`; otherwise `AddressError` is thrown. * @param {bigint} bigInt - a BigInt to convert * @returns {Address4} */ static fromBigInt(bigInt) { if (bigInt < 0n || bigInt > 0xffffffffn) { throw new address_error_1.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1"); } return _Address4.fromHex(bigInt.toString(16).padStart(8, "0")); } /** * Convert a byte array to an Address4 object. * * To convert from a Node.js `Buffer`, spread it: `Address4.fromByteArray([...buf])`. * @param {Array} bytes - an array of 4 bytes (0-255) * @returns {Address4} */ static fromByteArray(bytes2) { if (bytes2.length !== 4) { throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes"); } for (let i = 0; i < bytes2.length; i++) { if (!Number.isInteger(bytes2[i]) || bytes2[i] < 0 || bytes2[i] > 255) { throw new address_error_1.AddressError("All bytes must be integers between 0 and 255"); } } return this.fromUnsignedByteArray(bytes2); } /** * Convert an unsigned byte array to an Address4 object * @param {Array} bytes - an array of 4 unsigned bytes (0-255) * @returns {Address4} */ static fromUnsignedByteArray(bytes2) { if (bytes2.length !== 4) { throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes"); } const address = bytes2.join("."); return new _Address4(address); } /** * Returns the first n bits of the address, defaulting to the * subnet mask * @returns {String} */ mask(mask) { if (mask === void 0) { mask = this.subnetMask; } return this.getBitsBase2(0, mask); } /** * Returns the bits in the given range as a base-2 string * @returns {string} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the reversed ip6.arpa form of the address * @param {Object} options * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const reversed = this.correctForm().split(".").reverse().join("."); if (options.omitSuffix) { return reversed; } return `${reversed}.in-addr.arpa.`; } /** * Returns true if the given address is a multicast address * @returns {boolean} */ isMulticast() { return this.isInSubnet(MULTICAST_V4); } /** * Returns true if the address is in one of the [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private address ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`). * @returns {boolean} */ isPrivate() { return PRIVATE_V4.some((subnet) => this.isInSubnet(subnet)); } /** * Returns true if the address is in the loopback range `127.0.0.0/8` ([RFC 1122](https://datatracker.ietf.org/doc/html/rfc1122)). * @returns {boolean} */ isLoopback() { return this.isInSubnet(LOOPBACK_V4); } /** * Returns true if the address is in the link-local range `169.254.0.0/16` ([RFC 3927](https://datatracker.ietf.org/doc/html/rfc3927)). * @returns {boolean} */ isLinkLocal() { return this.isInSubnet(LINK_LOCAL_V4); } /** * Returns true if the address is the unspecified address `0.0.0.0`. * @returns {boolean} */ isUnspecified() { return this.isInSubnet(UNSPECIFIED_V4); } /** * Returns true if the address is the limited broadcast address `255.255.255.255` ([RFC 919](https://datatracker.ietf.org/doc/html/rfc919)). * @returns {boolean} */ isBroadcast() { return this.isInSubnet(BROADCAST_V4); } /** * Returns true if the address is in the carrier-grade NAT range `100.64.0.0/10` ([RFC 6598](https://datatracker.ietf.org/doc/html/rfc6598)). * @returns {boolean} */ isCGNAT() { return this.isInSubnet(CGNAT_V4); } /** * Returns a zero-padded base-2 string representation of the address * @returns {string} */ binaryZeroPad() { if (this._binaryZeroPad === void 0) { this._binaryZeroPad = this.bigInt().toString(2).padStart(constants.BITS, "0"); } return this._binaryZeroPad; } /** * Groups an IPv4 address for inclusion at the end of an IPv6 address * @returns {String} */ groupForV6() { const segments = this.parsedAddress; return this.address.replace(constants.RE_ADDRESS, `${segments.slice(0, 2).join(".")}.${segments.slice(2, 4).join(".")}`); } }; exports2.Address4 = Address4; var MULTICAST_V4 = new Address4("224.0.0.0/4"); var PRIVATE_V4 = [ new Address4("10.0.0.0/8"), new Address4("172.16.0.0/12"), new Address4("192.168.0.0/16") ]; var LOOPBACK_V4 = new Address4("127.0.0.0/8"); var LINK_LOCAL_V4 = new Address4("169.254.0.0/16"); var UNSPECIFIED_V4 = new Address4("0.0.0.0/32"); var BROADCAST_V4 = new Address4("255.255.255.255/32"); var CGNAT_V4 = new Address4("100.64.0.0/10"); } }); // node_modules/ip-address/dist/v6/constants.js var require_constants4 = __commonJS({ "node_modules/ip-address/dist/v6/constants.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.RE_URL_WITH_PORT = exports2.RE_URL = exports2.RE_ZONE_STRING = exports2.RE_SUBNET_STRING = exports2.RE_BAD_ADDRESS = exports2.RE_BAD_CHARACTERS = exports2.TYPES = exports2.SCOPES = exports2.GROUPS = exports2.BITS = void 0; exports2.BITS = 128; exports2.GROUPS = 8; exports2.SCOPES = { 0: "Reserved", 1: "Interface local", 2: "Link local", 4: "Admin local", 5: "Site local", 8: "Organization local", 14: "Global", 15: "Reserved" }; exports2.TYPES = { "ff01::1/128": "Multicast (All nodes on this interface)", "ff01::2/128": "Multicast (All routers on this interface)", "ff02::1/128": "Multicast (All nodes on this link)", "ff02::2/128": "Multicast (All routers on this link)", "ff05::2/128": "Multicast (All routers in this site)", "ff02::5/128": "Multicast (OSPFv3 AllSPF routers)", "ff02::6/128": "Multicast (OSPFv3 AllDR routers)", "ff02::9/128": "Multicast (RIP routers)", "ff02::a/128": "Multicast (EIGRP routers)", "ff02::d/128": "Multicast (PIM routers)", "ff02::16/128": "Multicast (MLDv2 reports)", "ff01::fb/128": "Multicast (mDNSv6)", "ff02::fb/128": "Multicast (mDNSv6)", "ff05::fb/128": "Multicast (mDNSv6)", "ff02::1:2/128": "Multicast (All DHCP servers and relay agents on this link)", "ff05::1:2/128": "Multicast (All DHCP servers and relay agents in this site)", "ff02::1:3/128": "Multicast (All DHCP servers on this link)", "ff05::1:3/128": "Multicast (All DHCP servers in this site)", "::/128": "Unspecified", "::1/128": "Loopback", "ff00::/8": "Multicast", "fe80::/10": "Link-local unicast", "fc00::/7": "Unique local", "2002::/16": "6to4", "2001:db8::/32": "Documentation", "64:ff9b::/96": "NAT64 (well-known)", "64:ff9b:1::/48": "NAT64 (local-use)" }; exports2.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; exports2.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; exports2.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; exports2.RE_ZONE_STRING = /%.*$/; exports2.RE_URL = /^\[{0,1}([0-9a-f:]+)\]{0,1}/; exports2.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/; } }); // node_modules/ip-address/dist/v6/helpers.js var require_helpers2 = __commonJS({ "node_modules/ip-address/dist/v6/helpers.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.escapeHtml = escapeHtml; exports2.spanAllZeroes = spanAllZeroes; exports2.spanAll = spanAll; exports2.spanLeadingZeroes = spanLeadingZeroes; exports2.simpleGroup = simpleGroup; function escapeHtml(s) { return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } function spanAllZeroes(s) { return escapeHtml(s).replace(/(0+)/g, '$1'); } function spanAll(s, offset = 0) { const letters = s.split(""); return letters.map((n, i) => `${spanAllZeroes(n)}`).join(""); } function spanLeadingZeroesSimple(group) { return escapeHtml(group).replace(/^(0+)/, '$1'); } function spanLeadingZeroes(address) { const groups = address.split(":"); return groups.map((g) => spanLeadingZeroesSimple(g)).join(":"); } function simpleGroup(addressString, offset = 0) { const groups = addressString.split(":"); return groups.map((g, i) => { if (/group-v4/.test(g)) { return g; } return `${spanLeadingZeroesSimple(g)}`; }); } } }); // node_modules/ip-address/dist/v6/regular-expressions.js var require_regular_expressions = __commonJS({ "node_modules/ip-address/dist/v6/regular-expressions.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ADDRESS_BOUNDARY = void 0; exports2.groupPossibilities = groupPossibilities; exports2.padGroup = padGroup; exports2.simpleRegularExpression = simpleRegularExpression; exports2.possibleElisions = possibleElisions; var v6 = __importStar(require_constants4()); function groupPossibilities(possibilities) { return `(${possibilities.join("|")})`; } function padGroup(group) { if (group.length < 4) { return `0{0,${4 - group.length}}${group}`; } return group; } exports2.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]"; function simpleRegularExpression(groups) { const zeroIndexes = []; groups.forEach((group, i) => { const groupInteger = parseInt(group, 16); if (groupInteger === 0) { zeroIndexes.push(i); } }); const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i) => { if (i === zeroIndex) { const elision = i === 0 || i === v6.GROUPS - 1 ? ":" : ""; return groupPossibilities([padGroup(group), elision]); } return padGroup(group); }).join(":")); possibilities.push(groups.map(padGroup).join(":")); return groupPossibilities(possibilities); } function possibleElisions(elidedGroups, moreLeft, moreRight) { const left = moreLeft ? "" : ":"; const right = moreRight ? "" : ":"; const possibilities = []; if (!moreLeft && !moreRight) { possibilities.push("::"); } if (moreLeft && moreRight) { possibilities.push(""); } if (moreRight && !moreLeft || !moreRight && moreLeft) { possibilities.push(":"); } possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`); possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`); possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`); for (let groups = 1; groups < elidedGroups - 1; groups++) { for (let position = 1; position < elidedGroups - groups; position++) { possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`); } } return groupPossibilities(possibilities); } } }); // node_modules/ip-address/dist/ipv6.js var require_ipv6 = __commonJS({ "node_modules/ip-address/dist/ipv6.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Address6 = void 0; var common = __importStar(require_common2()); var constants4 = __importStar(require_constants3()); var constants6 = __importStar(require_constants4()); var helpers = __importStar(require_helpers2()); var ipv4_1 = require_ipv4(); var regular_expressions_1 = require_regular_expressions(); var address_error_1 = require_address_error(); var common_1 = require_common2(); var isCorrect6 = common.isCorrect(constants6.BITS); function assert2(condition) { if (!condition) { throw new Error("Assertion failed."); } } function addCommas(number4) { const r = /(\d+)(\d{3})/; while (r.test(number4)) { number4 = number4.replace(r, "$1,$2"); } return number4; } function spanLeadingZeroes4(n) { n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); n = n.replace(/^(0{1,})(0)$/, '$1$2'); return n; } function compact(address, slice) { const s1 = []; const s2 = []; let i; for (i = 0; i < address.length; i++) { if (i < slice[0]) { s1.push(address[i]); } else if (i > slice[1]) { s2.push(address[i]); } } return s1.concat(["compact"]).concat(s2); } function paddedHex(octet) { return parseInt(octet, 16).toString(16).padStart(4, "0"); } function unsignByte(b) { return b & 255; } var Address6 = class _Address6 { constructor(address, optionalGroups) { this.addressMinusSuffix = ""; this.parsedSubnet = ""; this.subnet = "/128"; this.subnetMask = 128; this.v4 = false; this.zone = ""; this.isInSubnet = common.isInSubnet; this.isCorrect = isCorrect6; if (optionalGroups === void 0) { this.groups = constants6.GROUPS; } else { this.groups = optionalGroups; } this.address = address; const subnet = constants6.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace("/", ""); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) { throw new address_error_1.AddressError("Invalid subnet mask."); } address = address.replace(constants6.RE_SUBNET_STRING, ""); } else if (/\//.test(address)) { throw new address_error_1.AddressError("Invalid subnet mask."); } const zone = constants6.RE_ZONE_STRING.exec(address); if (zone) { this.zone = zone[0]; address = address.replace(constants6.RE_ZONE_STRING, ""); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(this.addressMinusSuffix); } /** * Returns true if the given string is a valid IPv6 address (with optional * CIDR subnet and zone identifier), false otherwise. Host bits in the * subnet portion are allowed (e.g. `2001:db8::1/32` is valid); for strict * network-address validation compare `correctForm()` to * `startAddress().correctForm()`, or use `networkForm()`. */ static isValid(address) { try { new _Address6(address); return true; } catch (e) { return false; } } /** * Convert a BigInt to a v6 address object. The value must be in the * range `[0, 2**128 - 1]`; otherwise `AddressError` is thrown. * @param {bigint} bigInt - a BigInt to convert * @returns {Address6} * @example * var bigInt = BigInt('1000000000000'); * var address = Address6.fromBigInt(bigInt); * address.correctForm(); // '::e8:d4a5:1000' */ static fromBigInt(bigInt) { if (bigInt < 0n || bigInt > (1n << BigInt(constants6.BITS)) - 1n) { throw new address_error_1.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1"); } const hex3 = bigInt.toString(16).padStart(32, "0"); const groups = []; for (let i = 0; i < constants6.GROUPS; i++) { groups.push(hex3.slice(i * 4, (i + 1) * 4)); } return new _Address6(groups.join(":")); } /** * Parse a URL (with optional bracketed host and port) into an address and * port. Returns either `{ address, port }` on success or * `{ error, address: null, port: null }` if the URL could not be parsed. * Ports are returned as numbers (or `null` if absent or out of range). * @example * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); * addressAndPort.address.correctForm(); // 'ffff::' * addressAndPort.port; // 8080 */ static fromURL(url2) { let host; let port = null; let result; if (url2.indexOf("[") !== -1 && url2.indexOf("]:") !== -1) { result = constants6.RE_URL_WITH_PORT.exec(url2); if (result === null) { return { error: "failed to parse address with port", address: null, port: null }; } host = result[1]; port = result[2]; } else if (url2.indexOf("/") !== -1) { url2 = url2.replace(/^[a-z0-9]+:\/\//, ""); result = constants6.RE_URL.exec(url2); if (result === null) { return { error: "failed to parse address from URL", address: null, port: null }; } host = result[1]; } else { host = url2; } if (port) { port = parseInt(port, 10); if (port < 0 || port > 65536) { port = null; } } else { port = null; } return { address: new _Address6(host), port }; } /** * Construct an `Address6` from an address and a hex subnet mask given as * separate strings (e.g. as returned by Node's `os.networkInterfaces()`). * Throws `AddressError` if the mask is non-contiguous (e.g. * `ffff::ffff`). * @example * var address = Address6.fromAddressAndMask('fe80::1', 'ffff:ffff:ffff:ffff::'); * address.subnetMask; // 64 */ static fromAddressAndMask(address, mask) { const bits = common.prefixLengthFromMask(new _Address6(mask).bigInt(), constants6.BITS); return new _Address6(`${address}/${bits}`); } /** * Construct an `Address6` from an address and a Cisco-style wildcard mask * given as separate strings (e.g. `::ffff:ffff:ffff:ffff` for a `/64`). * The wildcard mask is the bitwise inverse of the subnet mask. Throws * `AddressError` if the mask is non-contiguous. * @example * var address = Address6.fromAddressAndWildcardMask('fe80::1', '::ffff:ffff:ffff:ffff'); * address.subnetMask; // 64 */ static fromAddressAndWildcardMask(address, wildcardMask) { const wildcard = new _Address6(wildcardMask).bigInt(); const allOnes = (BigInt(1) << BigInt(constants6.BITS)) - BigInt(1); const mask = wildcard ^ allOnes; const bits = common.prefixLengthFromMask(mask, constants6.BITS); return new _Address6(`${address}/${bits}`); } /** * Construct an `Address6` from a wildcard pattern with trailing `*` * groups. The number of trailing wildcards determines the prefix * length: each `*` represents 16 bits. `::` is expanded to zero groups * (not wildcards) before evaluating trailing wildcards. * * Only trailing whole-group wildcards are supported. Partial-group * wildcards (e.g. `2001:db8::0*`) and interior wildcards (e.g. * `*::1`) throw `AddressError`. * @example * Address6.fromWildcard('2001:db8:*:*:*:*:*:*').subnet; // '/32' * Address6.fromWildcard('2001:db8::*').subnet; // '/112' * Address6.fromWildcard('*:*:*:*:*:*:*:*').subnet; // '/0' */ static fromWildcard(input) { if (input.includes("%") || input.includes("/")) { throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix"); } const halves = input.split("::"); if (halves.length > 2) { throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'"); } let groups; if (halves.length === 2) { const left = halves[0] === "" ? [] : halves[0].split(":"); const right = halves[1] === "" ? [] : halves[1].split(":"); const remaining = constants6.GROUPS - left.length - right.length; if (remaining < 1) { throw new address_error_1.AddressError("Wildcard pattern with '::' has too many groups"); } groups = [...left, ...new Array(remaining).fill("0"), ...right]; } else { groups = input.split(":"); } if (groups.length !== constants6.GROUPS) { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); } let firstWildcard = -1; for (let i = 0; i < groups.length; i++) { if (groups[i] === "*") { if (firstWildcard === -1) { firstWildcard = i; } } else if (firstWildcard !== -1) { throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)"); } } const trailing = firstWildcard === -1 ? 0 : groups.length - firstWildcard; const replaced = groups.map((g) => g === "*" ? "0" : g); const subnetBits = constants6.BITS - trailing * 16; return new _Address6(`${replaced.join(":")}/${subnetBits}`); } /** * Create an IPv6-mapped address given an IPv4 address * @param {string} address - An IPv4 address string * @returns {Address6} * @example * var address = Address6.fromAddress4('192.168.0.1'); * address.correctForm(); // '::ffff:c0a8:1' * address.to4in6(); // '::ffff:192.168.0.1' */ static fromAddress4(address) { const address4 = new ipv4_1.Address4(address); const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`); } /** * Return an address from ip6.arpa form * @param {string} arpaFormAddress - an 'ip6.arpa' form address * @returns {Adress6} * @example * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' */ static fromArpa(arpaFormAddress) { let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ""); const semicolonAmount = 7; if (address.length !== 63) { throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); } const parts = address.split(".").reverse(); for (let i = semicolonAmount; i > 0; i--) { const insertIndex = i * 4; parts.splice(insertIndex, 0, ":"); } address = parts.join(""); return new _Address6(address); } /** * Return the Microsoft UNC transcription of the address * @returns {String} the Microsoft UNC transcription of the address */ microsoftTranscription() { return `${this.correctForm().replace(/:/g, "-")}.ipv6-literal.net`; } /** * Return the first n bits of the address, defaulting to the subnet mask * @param {number} [mask=subnet] - the number of bits to mask * @returns {String} the first n bits of the address as a string */ mask(mask = this.subnetMask) { return this.getBitsBase2(0, mask); } /** * Return the number of possible subnets of a given size in the address * @param {number} [subnetSize=128] - the subnet size * @returns {String} */ // TODO: probably useful to have a numeric version of this too possibleSubnets(subnetSize = 128) { const availableBits = constants6.BITS - this.subnetMask; const subnetBits = Math.abs(subnetSize - constants6.BITS); const subnetPowers = availableBits - subnetBits; if (subnetPowers < 0) { return "0"; } return addCommas((BigInt("2") ** BigInt(subnetPowers)).toString(10)); } /** * Helper function getting start address. * @returns {bigint} */ _startAddress() { return BigInt(`0b${this.mask() + "0".repeat(constants6.BITS - this.subnetMask)}`); } /** * The first address in the range given by this address' subnet * Often referred to as the Network Address. * @returns {Address6} */ startAddress() { return _Address6.fromBigInt(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @returns {Address6} */ startAddressExclusive() { const adjust = BigInt("1"); return _Address6.fromBigInt(this._startAddress() + adjust); } /** * Helper function getting end address. * @returns {bigint} */ _endAddress() { return BigInt(`0b${this.mask() + "1".repeat(constants6.BITS - this.subnetMask)}`); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @returns {Address6} */ endAddress() { return _Address6.fromBigInt(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @returns {Address6} */ endAddressExclusive() { const adjust = BigInt("1"); return _Address6.fromBigInt(this._endAddress() - adjust); } /** * The hex form of the subnet mask, e.g. `ffff:ffff:ffff:ffff::` for a * `/64`. Returns an `Address6`; call `.correctForm()` for the string. * @returns {Address6} */ subnetMaskAddress() { return _Address6.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants6.BITS - this.subnetMask)}`)); } /** * The Cisco-style wildcard mask, e.g. `::ffff:ffff:ffff:ffff` for a * `/64`. This is the bitwise inverse of `subnetMaskAddress()`. Returns * an `Address6`; call `.correctForm()` for the string. * @returns {Address6} */ wildcardMask() { return _Address6.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants6.BITS - this.subnetMask)}`)); } /** * The network address in CIDR string form, e.g. `2001:db8::/32` for * `2001:db8::1/32`. For an address with no explicit subnet the prefix * is `/128`, e.g. `networkForm()` on `2001:db8::1` returns * `2001:db8::1/128`. * @returns {string} */ networkForm() { return `${this.startAddress().correctForm()}/${this.subnetMask}`; } /** * Return the scope of the address. The 4-bit scope field * ([RFC 4291 §2.7](https://datatracker.ietf.org/doc/html/rfc4291#section-2.7)) * is only defined for multicast addresses; for unicast addresses the scope * is derived from the address type per * [RFC 4007 §6](https://datatracker.ietf.org/doc/html/rfc4007#section-6). * @returns {String} */ getScope() { const type = this.getType(); if (type === "Multicast" || type.startsWith("Multicast ")) { const scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)]; return scope || "Unknown"; } if (type === "Link-local unicast" || type === "Loopback") { return "Link local"; } if (type === "Unspecified") { return "Unknown"; } return "Global"; } /** * Return the type of the address * @returns {String} */ getType() { for (let i = 0; i < TYPE_SUBNETS.length; i++) { const entry = TYPE_SUBNETS[i]; if (this.isInSubnet(entry[0])) { return entry[1]; } } return "Global unicast"; } /** * Return the bits in the given range as a BigInt * @returns {bigint} */ getBits(start, end) { return BigInt(`0b${this.getBitsBase2(start, end)}`); } /** * Return the bits in the given range as a base-2 string * @returns {String} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the bits in the given range as a base-16 string * @returns {String} */ getBitsBase16(start, end) { const length = end - start; if (length % 4 !== 0) { throw new Error("Length of bits to retrieve must be divisible by four"); } return this.getBits(start, end).toString(16).padStart(length / 4, "0"); } /** * Return the bits that are set past the subnet mask length * @returns {String} */ getBitsPastSubnet() { return this.getBitsBase2(this.subnetMask, constants6.BITS); } /** * Return the reversed ip6.arpa form of the address * @param {Object} options * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const characters = Math.floor(this.subnetMask / 4); const reversed = this.canonicalForm().replace(/:/g, "").split("").slice(0, characters).reverse().join("."); if (characters > 0) { if (options.omitSuffix) { return reversed; } return `${reversed}.ip6.arpa.`; } if (options.omitSuffix) { return ""; } return "ip6.arpa."; } /** * Returns the address in correct form, per * [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952): leading zeros * stripped, the longest run of zero groups collapsed to `::`, and hex digits * lowercased (e.g. `2001:db8::1`). This is the recommended form for display. */ correctForm() { let i; let groups = []; let zeroCounter = 0; const zeroes = []; for (i = 0; i < this.parsedAddress.length; i++) { const value = parseInt(this.parsedAddress[i], 16); if (value === 0) { zeroCounter++; } if (value !== 0 && zeroCounter > 0) { if (zeroCounter > 1) { zeroes.push([i - zeroCounter, i - 1]); } zeroCounter = 0; } } if (zeroCounter > 1) { zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); } const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); if (zeroes.length > 0) { const index = zeroLengths.indexOf(Math.max(...zeroLengths)); groups = compact(this.parsedAddress, zeroes[index]); } else { groups = this.parsedAddress; } for (i = 0; i < groups.length; i++) { if (groups[i] !== "compact") { groups[i] = parseInt(groups[i], 16).toString(16); } } let correct = groups.join(":"); correct = correct.replace(/^compact$/, "::"); correct = correct.replace(/(^compact)|(compact$)/, ":"); correct = correct.replace(/compact/, ""); return correct; } /** * Return a zero-padded base-2 string representation of the address * @returns {String} * @example * var address = new Address6('2001:4860:4001:803::1011'); * address.binaryZeroPad(); * // '0010000000000001010010000110000001000000000000010000100000000011 * // 0000000000000000000000000000000000000000000000000001000000010001' */ binaryZeroPad() { if (this._binaryZeroPad === void 0) { this._binaryZeroPad = this.bigInt().toString(2).padStart(constants6.BITS, "0"); } return this._binaryZeroPad; } /** * Parses a v4-in-v6 string (e.g. `::ffff:192.168.0.1`) by extracting the * trailing IPv4 address into `this.address4` / `this.parsedAddress4` and * returning the address with the v4 portion converted to two v6 groups. * Used internally by `parse()`. */ // TODO: Improve the semantics of this helper function parse4in6(address) { if (address.indexOf(".") === -1) { return address; } const groups = address.split(":"); const lastGroup = groups.slice(-1)[0]; const address4 = lastGroup.match(constants4.RE_ADDRESS); if (address4) { this.parsedAddress4 = address4[0]; this.address4 = new ipv4_1.Address4(this.parsedAddress4); for (let i = 0; i < this.address4.groups; i++) { if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { const highlighted = this.address4.parsedAddress.map(spanLeadingZeroes4).join("."); const prefix = groups.slice(0, -1).map(helpers.escapeHtml).join(":"); const separator = groups.length > 1 ? ":" : ""; throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", `${prefix}${separator}${highlighted}`); } } this.v4 = true; groups[groups.length - 1] = this.address4.toGroup6(); address = groups.join(":"); } return address; } /** * Parses an IPv6 address string into its 8 hexadecimal groups (expanding * any `::` elision and any trailing v4-in-v6 portion) and stores the result * on `this.parsedAddress`. Called automatically by the constructor; you * typically don't need to call it directly. Throws `AddressError` if the * input is malformed. */ // TODO: Make private? parse(address) { address = this.parse4in6(address); const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); if (badCharacters) { throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? "s" : ""} detected in address: ${badCharacters.join("")}`, address.replace(constants6.RE_BAD_CHARACTERS, '$1')); } const badAddress = address.match(constants6.RE_BAD_ADDRESS); if (badAddress) { throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join("")}`, address.replace(constants6.RE_BAD_ADDRESS, '$1')); } let groups = []; const halves = address.split("::"); if (halves.length === 2) { let first = halves[0].split(":"); let last = halves[1].split(":"); if (first.length === 1 && first[0] === "") { first = []; } if (last.length === 1 && last[0] === "") { last = []; } const remaining = this.groups - (first.length + last.length); if (!remaining) { throw new address_error_1.AddressError("Error parsing groups"); } this.elidedGroups = remaining; this.elisionBegin = first.length; this.elisionEnd = first.length + this.elidedGroups; groups = groups.concat(first); for (let i = 0; i < remaining; i++) { groups.push("0"); } groups = groups.concat(last); } else if (halves.length === 1) { groups = address.split(":"); this.elidedGroups = 0; } else { throw new address_error_1.AddressError("Too many :: groups found"); } groups = groups.map((group) => parseInt(group, 16).toString(16)); if (groups.length !== this.groups) { throw new address_error_1.AddressError("Incorrect number of groups found"); } return groups; } /** * Returns the canonical (fully expanded) form of the address: all 8 groups, * each padded to 4 hex digits, with no `::` collapsing * (e.g. `2001:0db8:0000:0000:0000:0000:0000:0001`). Useful for sorting and * byte-exact comparison. */ canonicalForm() { return this.parsedAddress.map(paddedHex).join(":"); } /** * Return the decimal form of the address * @returns {String} */ decimal() { return this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, "0")).join(":"); } /** * Return the address as a BigInt * @returns {bigint} */ bigInt() { return BigInt(`0x${this.parsedAddress.map(paddedHex).join("")}`); } /** * Return the last two groups of this address as an IPv4 address string * @returns {Address4} * @example * var address = new Address6('2001:4860:4001::1825:bf11'); * address.to4().correctForm(); // '24.37.191.17' */ to4() { const binary = this.binaryZeroPad().split(""); return ipv4_1.Address4.fromHex(BigInt(`0b${binary.slice(96, 128).join("")}`).toString(16).padStart(8, "0")); } /** * Return the v4-in-v6 form of the address * @returns {String} */ to4in6() { const address4 = this.to4(); const address6 = new _Address6(this.parsedAddress.slice(0, 6).join(":"), 6); const correct = address6.correctForm(); let infix = ""; if (!/:$/.test(correct)) { infix = ":"; } return correct + infix + address4.address; } /** * Decodes the Teredo tunneling fields embedded in this address. Returns the * Teredo prefix, server IPv4, client IPv4, raw flag bits, cone-NAT flag, * UDP port, and Microsoft-format flag breakdown (reserved, universal/local, * group/individual, nonce). Only meaningful for addresses in `2001::/32`. */ inspectTeredo() { const prefix = this.getBitsBase16(0, 32); const bitsForUdpPort = this.getBits(80, 96); const udpPort = (bitsForUdpPort ^ BigInt("0xffff")).toString(); const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); const bitsForClient4 = this.getBits(96, 128); const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt("0xffffffff")).toString(16).padStart(8, "0")); const flagsBase2 = this.getBitsBase2(64, 80); const coneNat = (0, common_1.testBit)(flagsBase2, 15); const reserved = (0, common_1.testBit)(flagsBase2, 14); const groupIndividual = (0, common_1.testBit)(flagsBase2, 8); const universalLocal = (0, common_1.testBit)(flagsBase2, 9); const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10); return { prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`, server4: server4.address, client4: client4.address, flags: flagsBase2, coneNat, microsoft: { reserved, universalLocal, groupIndividual, nonce }, udpPort }; } /** * Decodes the 6to4 tunneling fields embedded in this address. Returns the * 6to4 prefix and the embedded IPv4 gateway address. Only meaningful for * addresses in `2002::/16`. */ inspect6to4() { const prefix = this.getBitsBase16(0, 16); const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); return { prefix: prefix.slice(0, 4), gateway: gateway.address }; } /** * Return a v6 6to4 address from a v6 v4inv6 address * @returns {Address6} */ to6to4() { if (!this.is4()) { return null; } const addr6to4 = [ "2002", this.getBitsBase16(96, 112), this.getBitsBase16(112, 128), "", "/16" ].join(":"); return new _Address6(addr6to4); } /** * Embed an IPv4 address into a NAT64 IPv6 address using the encoding * defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052). * The default prefix is the well-known prefix `64:ff9b::/96`. The prefix * length must be one of 32, 40, 48, 56, 64, or 96; for prefixes shorter * than /64 the IPv4 octets are split around the reserved bits 64–71. * @example * Address6.fromAddress4Nat64('192.0.2.33').correctForm(); // '64:ff9b::c000:221' * Address6.fromAddress4Nat64('192.0.2.33', '2001:db8::/32').correctForm(); // '2001:db8:c000:221::' */ static fromAddress4Nat64(address, prefix = "64:ff9b::/96") { const v4 = new ipv4_1.Address4(address); const prefix6 = new _Address6(prefix); const pl = prefix6.subnetMask; if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) { throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96"); } const prefixBits = prefix6.binaryZeroPad(); const v4Bits = v4.binaryZeroPad(); let bits; if (pl === 96) { bits = prefixBits.slice(0, 96) + v4Bits; } else { const beforeU = 64 - pl; bits = prefixBits.slice(0, pl) + v4Bits.slice(0, beforeU) + "00000000" + v4Bits.slice(beforeU) + "0".repeat(128 - 72 - (32 - beforeU)); } const hex3 = BigInt(`0b${bits}`).toString(16).padStart(32, "0"); const groups = []; for (let i = 0; i < 8; i++) { groups.push(hex3.slice(i * 4, (i + 1) * 4)); } return new _Address6(groups.join(":")); } /** * Extract the embedded IPv4 address from a NAT64 IPv6 address using the * encoding defined by [RFC 6052](https://datatracker.ietf.org/doc/html/rfc6052). * The default prefix is the well-known prefix `64:ff9b::/96`. Returns * `null` if this address is not contained within the given prefix. * @example * new Address6('64:ff9b::c000:221').toAddress4Nat64()!.correctForm(); // '192.0.2.33' */ toAddress4Nat64(prefix = "64:ff9b::/96") { const prefix6 = new _Address6(prefix); const pl = prefix6.subnetMask; if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) { throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96"); } if (!this.isInSubnet(prefix6)) { return null; } const bits = this.binaryZeroPad(); let v4Bits; if (pl === 96) { v4Bits = bits.slice(96, 128); } else { const beforeU = 64 - pl; v4Bits = bits.slice(pl, pl + beforeU) + bits.slice(72, 72 + (32 - beforeU)); } const octets = []; for (let i = 0; i < 4; i++) { octets.push(parseInt(v4Bits.slice(i * 8, (i + 1) * 8), 2).toString()); } return new ipv4_1.Address4(octets.join(".")); } /** * Return a byte array. * * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toByteArray())`. * @returns {Array} */ toByteArray() { const valueWithoutPadding = this.bigInt().toString(16); const leadingPad = "0".repeat(valueWithoutPadding.length % 2); const value = `${leadingPad}${valueWithoutPadding}`; const bytes2 = []; for (let i = 0, length = value.length; i < length; i += 2) { bytes2.push(parseInt(value.substring(i, i + 2), 16)); } return bytes2; } /** * Return an unsigned byte array. * * To get a Node.js `Buffer`, wrap the result: `Buffer.from(address.toUnsignedByteArray())`. * @returns {Array} */ toUnsignedByteArray() { return this.toByteArray().map(unsignByte); } /** * Convert a byte array to an Address6 object. * * To convert from a Node.js `Buffer`, spread it: `Address6.fromByteArray([...buf])`. * @returns {Address6} */ static fromByteArray(bytes2) { return this.fromUnsignedByteArray(bytes2.map(unsignByte)); } /** * Convert an unsigned byte array to an Address6 object. * * To convert from a Node.js `Buffer`, spread it: `Address6.fromUnsignedByteArray([...buf])`. * @returns {Address6} */ static fromUnsignedByteArray(bytes2) { const BYTE_MAX = BigInt("256"); let result = BigInt("0"); let multiplier = BigInt("1"); for (let i = bytes2.length - 1; i >= 0; i--) { result += multiplier * BigInt(bytes2[i].toString(10)); multiplier *= BYTE_MAX; } return _Address6.fromBigInt(result); } /** * Returns true if the address is in the canonical form, false otherwise * @returns {boolean} */ isCanonical() { return this.addressMinusSuffix === this.canonicalForm(); } /** * Returns true if the address is a link local address, false otherwise * @returns {boolean} */ isLinkLocal() { if (this.getBitsBase2(0, 64) === "1111111010000000000000000000000000000000000000000000000000000000") { return true; } return false; } /** * Returns true if the address is a multicast address, false otherwise * @returns {boolean} */ isMulticast() { const type = this.getType(); return type === "Multicast" || type.startsWith("Multicast "); } /** * Returns true if the address was written in v4-in-v6 dotted-quad notation * (e.g. `::ffff:127.0.0.1`), false otherwise. This is a notation-level flag * and does not reflect whether the address bits lie in the IPv4-mapped * (`::ffff:0:0/96`) subnet — for that, see {@link isMapped4}. * @returns {boolean} */ is4() { return this.v4; } /** * Returns true if the address is an IPv4-mapped IPv6 address in * `::ffff:0:0/96` ([RFC 4291 §2.5.5.2](https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2)), * false otherwise. Unlike {@link is4}, this checks the underlying address * bits rather than the textual notation, so `::ffff:127.0.0.1` and * `::ffff:7f00:1` both return true. * @returns {boolean} */ isMapped4() { return this.isInSubnet(IPV4_MAPPED_SUBNET); } /** * Returns true if the address is a Teredo address, false otherwise * @returns {boolean} */ isTeredo() { return this.isInSubnet(TEREDO_SUBNET); } /** * Returns true if the address is a 6to4 address, false otherwise * @returns {boolean} */ is6to4() { return this.isInSubnet(SIX_TO_FOUR_SUBNET); } /** * Returns true if the address is a loopback address, false otherwise * @returns {boolean} */ isLoopback() { return this.getType() === "Loopback"; } /** * Returns true if the address is a Unique Local Address in `fc00::/7` ([RFC 4193](https://datatracker.ietf.org/doc/html/rfc4193)). ULAs are the IPv6 equivalent of IPv4 [RFC 1918](https://datatracker.ietf.org/doc/html/rfc1918) private addresses. * @returns {boolean} */ isULA() { return this.isInSubnet(ULA_SUBNET); } /** * Returns true if the address is the unspecified address `::`. * @returns {boolean} */ isUnspecified() { return this.getType() === "Unspecified"; } /** * Returns true if the address is in the documentation prefix `2001:db8::/32` ([RFC 3849](https://datatracker.ietf.org/doc/html/rfc3849)). * @returns {boolean} */ isDocumentation() { return this.isInSubnet(DOCUMENTATION_SUBNET); } // #endregion // #region HTML /** * Returns the address as an HTTP URL with the host bracketed, e.g. * `http://[2001:db8::1]/`. If `optionalPort` is provided it is appended, * e.g. `http://[2001:db8::1]:8080/`. */ href(optionalPort) { if (optionalPort === void 0) { optionalPort = ""; } else { optionalPort = `:${optionalPort}`; } return `http://[${this.correctForm()}]${optionalPort}/`; } /** * Returns an HTML `` element whose `href` encodes the address in a URL * hash fragment (default prefix `/#address=`). Useful for linking between * pages of an address-inspector UI. * @param options.className - CSS class for the rendered `` element * @param options.prefix - hash prefix prepended to the address (default `/#address=`) * @param options.v4 - when true, render the address in v4-in-v6 form */ link(options) { if (!options) { options = {}; } if (options.className === void 0) { options.className = ""; } if (options.prefix === void 0) { options.prefix = "/#address="; } if (options.v4 === void 0) { options.v4 = false; } let formFunction = this.correctForm; if (options.v4) { formFunction = this.to4in6; } const form = formFunction.call(this); const safeHref = helpers.escapeHtml(`${options.prefix}${form}`); const safeForm = helpers.escapeHtml(form); if (options.className) { const safeClass = helpers.escapeHtml(options.className); return `${safeForm}`; } return `${safeForm}`; } /** * Groups an address * @returns {String} */ group() { if (this.elidedGroups === 0) { return helpers.simpleGroup(this.addressMinusSuffix).join(":"); } assert2(typeof this.elidedGroups === "number"); assert2(typeof this.elisionBegin === "number"); const output = []; const [left, right] = this.addressMinusSuffix.split("::"); if (left.length) { output.push(...helpers.simpleGroup(left)); } else { output.push(""); } const classes = ["hover-group"]; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } output.push(``); if (right.length) { output.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { output.push(""); } if (this.is4()) { assert2(this.address4 instanceof ipv4_1.Address4); output.pop(); output.push(this.address4.groupForV6()); } return output.join(":"); } // #endregion // #region Regular expressions /** * Generate a regular expression string that can be used to find or validate * all variations of this address * @param {boolean} substringSearch * @returns {string} */ regularExpressionString(substringSearch = false) { let output = []; const address6 = new _Address6(this.correctForm()); if (address6.elidedGroups === 0) { output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { const halves = address6.address.split("::"); if (halves[0].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))); } assert2(typeof address6.elidedGroups === "number"); output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))); } output = [output.join(":")]; } if (!substringSearch) { output = [ "(?=^|", regular_expressions_1.ADDRESS_BOUNDARY, "|[^\\w\\:])(", ...output, ")(?=[^\\w\\:]|", regular_expressions_1.ADDRESS_BOUNDARY, "|$)" ]; } return output.join(""); } /** * Generate a regular expression that can be used to find or validate all * variations of this address. * @param {boolean} substringSearch * @returns {RegExp} */ regularExpression(substringSearch = false) { return new RegExp(this.regularExpressionString(substringSearch), "i"); } }; exports2.Address6 = Address6; var TYPE_SUBNETS = Object.keys(constants6.TYPES).map((subnet) => [ new Address6(subnet), constants6.TYPES[subnet] ]); var TEREDO_SUBNET = new Address6("2001::/32"); var SIX_TO_FOUR_SUBNET = new Address6("2002::/16"); var ULA_SUBNET = new Address6("fc00::/7"); var DOCUMENTATION_SUBNET = new Address6("2001:db8::/32"); var IPV4_MAPPED_SUBNET = new Address6("::ffff:0:0/96"); } }); // node_modules/ip-address/dist/ip-address.js var require_ip_address = __commonJS({ "node_modules/ip-address/dist/ip-address.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.v6 = exports2.AddressError = exports2.Address6 = exports2.Address4 = void 0; var ipv4_1 = require_ipv4(); Object.defineProperty(exports2, "Address4", { enumerable: true, get: function() { return ipv4_1.Address4; } }); var ipv6_1 = require_ipv6(); Object.defineProperty(exports2, "Address6", { enumerable: true, get: function() { return ipv6_1.Address6; } }); var address_error_1 = require_address_error(); Object.defineProperty(exports2, "AddressError", { enumerable: true, get: function() { return address_error_1.AddressError; } }); var helpers = __importStar(require_helpers2()); exports2.v6 = { helpers }; } }); // node_modules/socks/build/common/helpers.js var require_helpers3 = __commonJS({ "node_modules/socks/build/common/helpers.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ipToBuffer = exports2.int32ToIpv4 = exports2.ipv4ToInt32 = exports2.validateSocksClientChainOptions = exports2.validateSocksClientOptions = void 0; var util_1 = require_util(); var constants_1 = require_constants2(); var stream = require("stream"); var ip_address_1 = require_ip_address(); var net = require("net"); function validateSocksClientOptions(options, acceptedCommands = ["connect", "bind", "associate"]) { if (!constants_1.SocksCommand[options.command]) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options); } if (acceptedCommands.indexOf(options.command) === -1) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options); } if (!isValidSocksRemoteHost(options.destination)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); } if (!isValidSocksProxy(options.proxy)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); } validateCustomProxyAuth(options.proxy, options); if (options.timeout && !isValidTimeoutValue(options.timeout)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); } if (options.existing_socket && !(options.existing_socket instanceof stream.Duplex)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options); } } exports2.validateSocksClientOptions = validateSocksClientOptions; function validateSocksClientChainOptions(options) { if (options.command !== "connect") { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options); } if (!isValidSocksRemoteHost(options.destination)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); } if (!(options.proxies && Array.isArray(options.proxies) && options.proxies.length >= 2)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options); } options.proxies.forEach((proxy) => { if (!isValidSocksProxy(proxy)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); } validateCustomProxyAuth(proxy, options); }); if (options.timeout && !isValidTimeoutValue(options.timeout)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); } } exports2.validateSocksClientChainOptions = validateSocksClientChainOptions; function validateCustomProxyAuth(proxy, options) { if (proxy.custom_auth_method !== void 0) { if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options); } if (proxy.custom_auth_request_handler === void 0 || typeof proxy.custom_auth_request_handler !== "function") { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); } if (proxy.custom_auth_response_size === void 0) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); } if (proxy.custom_auth_response_handler === void 0 || typeof proxy.custom_auth_response_handler !== "function") { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); } } } function isValidSocksRemoteHost(remoteHost) { return remoteHost && typeof remoteHost.host === "string" && Buffer.byteLength(remoteHost.host) < 256 && typeof remoteHost.port === "number" && remoteHost.port >= 0 && remoteHost.port <= 65535; } function isValidSocksProxy(proxy) { return proxy && (typeof proxy.host === "string" || typeof proxy.ipaddress === "string") && typeof proxy.port === "number" && proxy.port >= 0 && proxy.port <= 65535 && (proxy.type === 4 || proxy.type === 5); } function isValidTimeoutValue(value) { return typeof value === "number" && value > 0; } function ipv4ToInt32(ip) { const address = new ip_address_1.Address4(ip); return address.toArray().reduce((acc, part) => (acc << 8) + part, 0) >>> 0; } exports2.ipv4ToInt32 = ipv4ToInt32; function int32ToIpv4(int322) { const octet1 = int322 >>> 24 & 255; const octet2 = int322 >>> 16 & 255; const octet3 = int322 >>> 8 & 255; const octet4 = int322 & 255; return [octet1, octet2, octet3, octet4].join("."); } exports2.int32ToIpv4 = int32ToIpv4; function ipToBuffer(ip) { if (net.isIPv4(ip)) { const address = new ip_address_1.Address4(ip); return Buffer.from(address.toArray()); } else if (net.isIPv6(ip)) { const address = new ip_address_1.Address6(ip); return Buffer.from(address.canonicalForm().split(":").map((segment2) => segment2.padStart(4, "0")).join(""), "hex"); } else { throw new Error("Invalid IP address format"); } } exports2.ipToBuffer = ipToBuffer; } }); // node_modules/socks/build/common/receivebuffer.js var require_receivebuffer = __commonJS({ "node_modules/socks/build/common/receivebuffer.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ReceiveBuffer = void 0; var ReceiveBuffer = class { constructor(size = 4096) { this.buffer = Buffer.allocUnsafe(size); this.offset = 0; this.originalSize = size; } get length() { return this.offset; } append(data) { if (!Buffer.isBuffer(data)) { throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer."); } if (this.offset + data.length >= this.buffer.length) { const tmp = this.buffer; this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length)); tmp.copy(this.buffer); } data.copy(this.buffer, this.offset); return this.offset += data.length; } peek(length) { if (length > this.offset) { throw new Error("Attempted to read beyond the bounds of the managed internal data."); } return this.buffer.slice(0, length); } get(length) { if (length > this.offset) { throw new Error("Attempted to read beyond the bounds of the managed internal data."); } const value = Buffer.allocUnsafe(length); this.buffer.slice(0, length).copy(value); this.buffer.copyWithin(0, length, length + this.offset - length); this.offset -= length; return value; } }; exports2.ReceiveBuffer = ReceiveBuffer; } }); // node_modules/socks/build/client/socksclient.js var require_socksclient = __commonJS({ "node_modules/socks/build/client/socksclient.js"(exports2) { "use strict"; var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SocksClientError = exports2.SocksClient = void 0; var events_1 = require("events"); var net = require("net"); var smart_buffer_1 = require_smartbuffer(); var constants_1 = require_constants2(); var helpers_1 = require_helpers3(); var receivebuffer_1 = require_receivebuffer(); var util_1 = require_util(); Object.defineProperty(exports2, "SocksClientError", { enumerable: true, get: function() { return util_1.SocksClientError; } }); var ip_address_1 = require_ip_address(); var SocksClient = class _SocksClient extends events_1.EventEmitter { constructor(options) { super(); this.options = Object.assign({}, options); (0, helpers_1.validateSocksClientOptions)(options); this.setState(constants_1.SocksClientState.Created); } /** * Creates a new SOCKS connection. * * Note: Supports callbacks and promises. Only supports the connect command. * @param options { SocksClientOptions } Options. * @param callback { Function } An optional callback function. * @returns { Promise } */ static createConnection(options, callback) { return new Promise((resolve, reject) => { try { (0, helpers_1.validateSocksClientOptions)(options, ["connect"]); } catch (err) { if (typeof callback === "function") { callback(err); return resolve(err); } else { return reject(err); } } const client = new _SocksClient(options); client.connect(options.existing_socket); client.once("established", (info) => { client.removeAllListeners(); if (typeof callback === "function") { callback(null, info); resolve(info); } else { resolve(info); } }); client.once("error", (err) => { client.removeAllListeners(); if (typeof callback === "function") { callback(err); resolve(err); } else { reject(err); } }); }); } /** * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies. * * Note: Supports callbacks and promises. Only supports the connect method. * Note: Implemented via createConnection() factory function. * @param options { SocksClientChainOptions } Options * @param callback { Function } An optional callback function. * @returns { Promise } */ static createConnectionChain(options, callback) { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { try { (0, helpers_1.validateSocksClientChainOptions)(options); } catch (err) { if (typeof callback === "function") { callback(err); return resolve(err); } else { return reject(err); } } if (options.randomizeChain) { (0, util_1.shuffleArray)(options.proxies); } try { let sock; for (let i = 0; i < options.proxies.length; i++) { const nextProxy = options.proxies[i]; const nextDestination = i === options.proxies.length - 1 ? options.destination : { host: options.proxies[i + 1].host || options.proxies[i + 1].ipaddress, port: options.proxies[i + 1].port }; const result = yield _SocksClient.createConnection({ command: "connect", proxy: nextProxy, destination: nextDestination, existing_socket: sock }); sock = sock || result.socket; } if (typeof callback === "function") { callback(null, { socket: sock }); resolve({ socket: sock }); } else { resolve({ socket: sock }); } } catch (err) { if (typeof callback === "function") { callback(err); resolve(err); } else { reject(err); } } })); } /** * Creates a SOCKS UDP Frame. * @param options */ static createUDPFrame(options) { const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt16BE(0); buff.writeUInt8(options.frameNumber || 0); if (net.isIPv4(options.remoteHost.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv4); buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host)); } else if (net.isIPv6(options.remoteHost.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv6); buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host)); } else { buff.writeUInt8(constants_1.Socks5HostType.Hostname); buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)); buff.writeString(options.remoteHost.host); } buff.writeUInt16BE(options.remoteHost.port); buff.writeBuffer(options.data); return buff.toBuffer(); } /** * Parses a SOCKS UDP frame. * @param data */ static parseUDPFrame(data) { const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); buff.readOffset = 2; const frameNumber = buff.readUInt8(); const hostType = buff.readUInt8(); let remoteHost; if (hostType === constants_1.Socks5HostType.IPv4) { remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()); } else if (hostType === constants_1.Socks5HostType.IPv6) { remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(); } else { remoteHost = buff.readString(buff.readUInt8()); } const remotePort = buff.readUInt16BE(); return { frameNumber, remoteHost: { host: remoteHost, port: remotePort }, data: buff.readBuffer() }; } /** * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. */ setState(newState) { if (this.state !== constants_1.SocksClientState.Error) { this.state = newState; } } /** * Starts the connection establishment to the proxy and destination. * @param existingSocket Connected socket to use instead of creating a new one (internal use). */ connect(existingSocket) { this.onDataReceived = (data) => this.onDataReceivedHandler(data); this.onClose = () => this.onCloseHandler(); this.onError = (err) => this.onErrorHandler(err); this.onConnect = () => this.onConnectHandler(); const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT); if (timer.unref && typeof timer.unref === "function") { timer.unref(); } if (existingSocket) { this.socket = existingSocket; } else { this.socket = new net.Socket(); } this.socket.once("close", this.onClose); this.socket.once("error", this.onError); this.socket.once("connect", this.onConnect); this.socket.on("data", this.onDataReceived); this.setState(constants_1.SocksClientState.Connecting); this.receiveBuffer = new receivebuffer_1.ReceiveBuffer(); if (existingSocket) { this.socket.emit("connect"); } else { this.socket.connect(this.getSocketOptions()); if (this.options.set_tcp_nodelay !== void 0 && this.options.set_tcp_nodelay !== null) { this.socket.setNoDelay(!!this.options.set_tcp_nodelay); } } this.prependOnceListener("established", (info) => { setImmediate(() => { if (this.receiveBuffer.length > 0) { const excessData = this.receiveBuffer.get(this.receiveBuffer.length); info.socket.emit("data", excessData); } info.socket.resume(); }); }); } // Socket options (defaults host/port to options.proxy.host/options.proxy.port) getSocketOptions() { return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port }); } /** * Handles internal Socks timeout callback. * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. */ onEstablishedTimeout() { if (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.BoundWaitingForConnection) { this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut); } } /** * Handles Socket connect event. */ onConnectHandler() { this.setState(constants_1.SocksClientState.Connected); if (this.options.proxy.type === 4) { this.sendSocks4InitialHandshake(); } else { this.sendSocks5InitialHandshake(); } this.setState(constants_1.SocksClientState.SentInitialHandshake); } /** * Handles Socket data event. * @param data */ onDataReceivedHandler(data) { this.receiveBuffer.append(data); this.processData(); } /** * Handles processing of the data we have received. */ processData() { while (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.Error && this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) { if (this.state === constants_1.SocksClientState.SentInitialHandshake) { if (this.options.proxy.type === 4) { this.handleSocks4FinalHandshakeResponse(); } else { this.handleInitialSocks5HandshakeResponse(); } } else if (this.state === constants_1.SocksClientState.SentAuthentication) { this.handleInitialSocks5AuthenticationHandshakeResponse(); } else if (this.state === constants_1.SocksClientState.SentFinalHandshake) { this.handleSocks5FinalHandshakeResponse(); } else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) { if (this.options.proxy.type === 4) { this.handleSocks4IncomingConnectionResponse(); } else { this.handleSocks5IncomingConnectionResponse(); } } else { this.closeSocket(constants_1.ERRORS.InternalError); break; } } } /** * Handles Socket close event. * @param had_error */ onCloseHandler() { this.closeSocket(constants_1.ERRORS.SocketClosed); } /** * Handles Socket error event. * @param err */ onErrorHandler(err) { this.closeSocket(err.message); } /** * Removes internal event listeners on the underlying Socket. */ removeInternalSocketHandlers() { this.socket.pause(); this.socket.removeListener("data", this.onDataReceived); this.socket.removeListener("close", this.onClose); this.socket.removeListener("error", this.onError); this.socket.removeListener("connect", this.onConnect); } /** * Closes and destroys the underlying Socket. Emits an error event. * @param err { String } An error string to include in error event. */ closeSocket(err) { if (this.state !== constants_1.SocksClientState.Error) { this.setState(constants_1.SocksClientState.Error); this.socket.destroy(); this.removeInternalSocketHandlers(); this.emit("error", new util_1.SocksClientError(err, this.options)); } } /** * Sends initial Socks v4 handshake request. */ sendSocks4InitialHandshake() { const userId = this.options.proxy.userId || ""; const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(4); buff.writeUInt8(constants_1.SocksCommand[this.options.command]); buff.writeUInt16BE(this.options.destination.port); if (net.isIPv4(this.options.destination.host)) { buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); buff.writeStringNT(userId); } else { buff.writeUInt8(0); buff.writeUInt8(0); buff.writeUInt8(0); buff.writeUInt8(1); buff.writeStringNT(userId); buff.writeStringNT(this.options.destination.host); } this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response; this.socket.write(buff.toBuffer()); } /** * Handles Socks v4 handshake response. * @param data */ handleSocks4FinalHandshakeResponse() { const data = this.receiveBuffer.get(8); if (data[1] !== constants_1.Socks4Response.Granted) { this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`); } else { if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); buff.readOffset = 2; const remoteHost = { port: buff.readUInt16BE(), host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()) }; if (remoteHost.host === "0.0.0.0") { remoteHost.host = this.options.proxy.ipaddress; } this.setState(constants_1.SocksClientState.BoundWaitingForConnection); this.emit("bound", { remoteHost, socket: this.socket }); } else { this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit("established", { socket: this.socket }); } } } /** * Handles Socks v4 incoming connection request (BIND) * @param data */ handleSocks4IncomingConnectionResponse() { const data = this.receiveBuffer.get(8); if (data[1] !== constants_1.Socks4Response.Granted) { this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`); } else { const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); buff.readOffset = 2; const remoteHost = { port: buff.readUInt16BE(), host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()) }; this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit("established", { remoteHost, socket: this.socket }); } } /** * Sends initial Socks v5 handshake request. */ sendSocks5InitialHandshake() { const buff = new smart_buffer_1.SmartBuffer(); const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth]; if (this.options.proxy.userId || this.options.proxy.password) { supportedAuthMethods.push(constants_1.Socks5Auth.UserPass); } if (this.options.proxy.custom_auth_method !== void 0) { supportedAuthMethods.push(this.options.proxy.custom_auth_method); } buff.writeUInt8(5); buff.writeUInt8(supportedAuthMethods.length); for (const authMethod of supportedAuthMethods) { buff.writeUInt8(authMethod); } this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse; this.socket.write(buff.toBuffer()); this.setState(constants_1.SocksClientState.SentInitialHandshake); } /** * Handles initial Socks v5 handshake response. * @param data */ handleInitialSocks5HandshakeResponse() { const data = this.receiveBuffer.get(2); if (data[0] !== 5) { this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion); } else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) { this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType); } else { if (data[1] === constants_1.Socks5Auth.NoAuth) { this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth; this.sendSocks5CommandRequest(); } else if (data[1] === constants_1.Socks5Auth.UserPass) { this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass; this.sendSocks5UserPassAuthentication(); } else if (data[1] === this.options.proxy.custom_auth_method) { this.socks5ChosenAuthType = this.options.proxy.custom_auth_method; this.sendSocks5CustomAuthentication(); } else { this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType); } } } /** * Sends Socks v5 user & password auth handshake. * * Note: No auth and user/pass are currently supported. */ sendSocks5UserPassAuthentication() { const userId = this.options.proxy.userId || ""; const password = this.options.proxy.password || ""; const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(1); buff.writeUInt8(Buffer.byteLength(userId)); buff.writeString(userId); buff.writeUInt8(Buffer.byteLength(password)); buff.writeString(password); this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse; this.socket.write(buff.toBuffer()); this.setState(constants_1.SocksClientState.SentAuthentication); } sendSocks5CustomAuthentication() { return __awaiter(this, void 0, void 0, function* () { this.nextRequiredPacketBufferSize = this.options.proxy.custom_auth_response_size; this.socket.write(yield this.options.proxy.custom_auth_request_handler()); this.setState(constants_1.SocksClientState.SentAuthentication); }); } handleSocks5CustomAuthHandshakeResponse(data) { return __awaiter(this, void 0, void 0, function* () { return yield this.options.proxy.custom_auth_response_handler(data); }); } handleSocks5AuthenticationNoAuthHandshakeResponse(data) { return __awaiter(this, void 0, void 0, function* () { return data[1] === 0; }); } handleSocks5AuthenticationUserPassHandshakeResponse(data) { return __awaiter(this, void 0, void 0, function* () { return data[1] === 0; }); } /** * Handles Socks v5 auth handshake response. * @param data */ handleInitialSocks5AuthenticationHandshakeResponse() { return __awaiter(this, void 0, void 0, function* () { this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse); let authResult = false; if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) { authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)); } else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) { authResult = yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)); } else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) { authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size)); } if (!authResult) { this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed); } else { this.sendSocks5CommandRequest(); } }); } /** * Sends Socks v5 final handshake request. */ sendSocks5CommandRequest() { const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(5); buff.writeUInt8(constants_1.SocksCommand[this.options.command]); buff.writeUInt8(0); if (net.isIPv4(this.options.destination.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv4); buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); } else if (net.isIPv6(this.options.destination.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv6); buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); } else { buff.writeUInt8(constants_1.Socks5HostType.Hostname); buff.writeUInt8(this.options.destination.host.length); buff.writeString(this.options.destination.host); } buff.writeUInt16BE(this.options.destination.port); this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; this.socket.write(buff.toBuffer()); this.setState(constants_1.SocksClientState.SentFinalHandshake); } /** * Handles Socks v5 final handshake response. * @param data */ handleSocks5FinalHandshakeResponse() { const header = this.receiveBuffer.peek(5); if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) { this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`); } else { const addressType = header[3]; let remoteHost; let buff; if (addressType === constants_1.Socks5HostType.IPv4) { const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), port: buff.readUInt16BE() }; if (remoteHost.host === "0.0.0.0") { remoteHost.host = this.options.proxy.ipaddress; } } else if (addressType === constants_1.Socks5HostType.Hostname) { const hostLength = header[4]; const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); remoteHost = { host: buff.readString(hostLength), port: buff.readUInt16BE() }; } else if (addressType === constants_1.Socks5HostType.IPv6) { const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), port: buff.readUInt16BE() }; } this.setState(constants_1.SocksClientState.ReceivedFinalResponse); if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) { this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit("established", { remoteHost, socket: this.socket }); } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { this.setState(constants_1.SocksClientState.BoundWaitingForConnection); this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; this.emit("bound", { remoteHost, socket: this.socket }); } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) { this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit("established", { remoteHost, socket: this.socket }); } } } /** * Handles Socks v5 incoming connection request (BIND). */ handleSocks5IncomingConnectionResponse() { const header = this.receiveBuffer.peek(5); if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) { this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`); } else { const addressType = header[3]; let remoteHost; let buff; if (addressType === constants_1.Socks5HostType.IPv4) { const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), port: buff.readUInt16BE() }; if (remoteHost.host === "0.0.0.0") { remoteHost.host = this.options.proxy.ipaddress; } } else if (addressType === constants_1.Socks5HostType.Hostname) { const hostLength = header[4]; const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); remoteHost = { host: buff.readString(hostLength), port: buff.readUInt16BE() }; } else if (addressType === constants_1.Socks5HostType.IPv6) { const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), port: buff.readUInt16BE() }; } this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit("established", { remoteHost, socket: this.socket }); } } get socksClientOptions() { return Object.assign({}, this.options); } }; exports2.SocksClient = SocksClient; } }); // node_modules/socks/build/index.js var require_build = __commonJS({ "node_modules/socks/build/index.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); }; Object.defineProperty(exports2, "__esModule", { value: true }); __exportStar(require_socksclient(), exports2); } }); // node_modules/socks-proxy-agent/dist/index.js var require_dist3 = __commonJS({ "node_modules/socks-proxy-agent/dist/index.js"(exports2) { "use strict"; var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = exports2 && exports2.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; var __importDefault = exports2 && exports2.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SocksProxyAgent = void 0; var socks_1 = require_build(); var agent_base_1 = require_dist(); var debug_1 = __importDefault(require_src()); var dns = __importStar(require("dns")); var net = __importStar(require("net")); var tls = __importStar(require("tls")); var url_1 = require("url"); var debug2 = (0, debug_1.default)("socks-proxy-agent"); var setServernameFromNonIpHost = (options) => { if (options.servername === void 0 && options.host && !net.isIP(options.host)) { return { ...options, servername: options.host }; } return options; }; function parseSocksURL(url2) { let lookup = false; let type = 5; const host = url2.hostname; const port = parseInt(url2.port, 10) || 1080; switch (url2.protocol.replace(":", "")) { case "socks4": lookup = true; type = 4; break; // pass through case "socks4a": type = 4; break; case "socks5": lookup = true; type = 5; break; // pass through case "socks": type = 5; break; case "socks5h": type = 5; break; default: throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url2.protocol)}`); } const proxy = { host, port, type }; if (url2.username) { Object.defineProperty(proxy, "userId", { value: decodeURIComponent(url2.username), enumerable: false }); } if (url2.password != null) { Object.defineProperty(proxy, "password", { value: decodeURIComponent(url2.password), enumerable: false }); } return { lookup, proxy }; } var SocksProxyAgent2 = class extends agent_base_1.Agent { constructor(uri, opts) { super(opts); const url2 = typeof uri === "string" ? new url_1.URL(uri) : uri; const { proxy, lookup } = parseSocksURL(url2); this.shouldLookup = lookup; this.proxy = proxy; this.timeout = opts?.timeout ?? null; this.socketOptions = opts?.socketOptions ?? null; } /** * Initiates a SOCKS connection to the specified SOCKS proxy server, * which in turn connects to the specified remote host and port. */ async connect(req, opts) { const { shouldLookup, proxy, timeout } = this; if (!opts.host) { throw new Error("No `host` defined!"); } let { host } = opts; const { port, lookup: lookupFn = dns.lookup } = opts; if (shouldLookup) { host = await new Promise((resolve, reject) => { lookupFn(host, {}, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } const socksOpts = { proxy, destination: { host, port: typeof port === "number" ? port : parseInt(port, 10) }, command: "connect", timeout: timeout ?? void 0, // @ts-expect-error the type supplied by socks for socket_options is wider // than necessary since socks will always override the host and port socket_options: this.socketOptions ?? void 0 }; const cleanup = (tlsSocket) => { req.destroy(); socket.destroy(); if (tlsSocket) tlsSocket.destroy(); }; debug2("Creating socks proxy connection: %o", socksOpts); const { socket } = await socks_1.SocksClient.createConnection(socksOpts); debug2("Successfully created socks proxy connection"); if (timeout !== null) { socket.setTimeout(timeout); socket.on("timeout", () => cleanup()); } if (opts.secureEndpoint) { debug2("Upgrading socket connection to TLS"); const tlsSocket = tls.connect({ ...omit2(setServernameFromNonIpHost(opts), "host", "path", "port"), socket }); tlsSocket.once("error", (error48) => { debug2("Socket TLS error", error48.message); cleanup(tlsSocket); }); return tlsSocket; } return socket; } }; SocksProxyAgent2.protocols = [ "socks", "socks4", "socks4a", "socks5", "socks5h" ]; exports2.SocksProxyAgent = SocksProxyAgent2; function omit2(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } } }); // node_modules/ws/lib/stream.js var require_stream = __commonJS({ "node_modules/ws/lib/stream.js"(exports2, module2) { "use strict"; var { Duplex } = require("stream"); function emitClose(stream) { stream.emit("close"); } function duplexOnEnd() { if (!this.destroyed && this._writableState.finished) { this.destroy(); } } function duplexOnError(err) { this.removeListener("error", duplexOnError); this.destroy(); if (this.listenerCount("error") === 0) { this.emit("error", err); } } function createWebSocketStream2(ws2, options) { let terminateOnDestroy = true; const duplex = new Duplex({ ...options, autoDestroy: false, emitClose: false, objectMode: false, writableObjectMode: false }); ws2.on("message", function message(msg, isBinary) { const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; if (!duplex.push(data)) ws2.pause(); }); ws2.once("error", function error48(err) { if (duplex.destroyed) return; terminateOnDestroy = false; duplex.destroy(err); }); ws2.once("close", function close() { if (duplex.destroyed) return; duplex.push(null); }); duplex._destroy = function(err, callback) { if (ws2.readyState === ws2.CLOSED) { callback(err); process.nextTick(emitClose, duplex); return; } let called = false; ws2.once("error", function error48(err2) { called = true; callback(err2); }); ws2.once("close", function close() { if (!called) callback(err); process.nextTick(emitClose, duplex); }); if (terminateOnDestroy) ws2.terminate(); }; duplex._final = function(callback) { if (ws2.readyState === ws2.CONNECTING) { ws2.once("open", function open2() { duplex._final(callback); }); return; } if (ws2._socket === null) return; if (ws2._socket._writableState.finished) { callback(); if (duplex._readableState.endEmitted) duplex.destroy(); } else { ws2._socket.once("finish", function finish() { callback(); }); ws2.close(); } }; duplex._read = function() { if (ws2.isPaused) ws2.resume(); }; duplex._write = function(chunk, encoding, callback) { if (ws2.readyState === ws2.CONNECTING) { ws2.once("open", function open2() { duplex._write(chunk, encoding, callback); }); return; } ws2.send(chunk, callback); }; duplex.on("end", duplexOnEnd); duplex.on("error", duplexOnError); return duplex; } module2.exports = createWebSocketStream2; } }); // node_modules/ws/lib/constants.js var require_constants5 = __commonJS({ "node_modules/ws/lib/constants.js"(exports2, module2) { "use strict"; module2.exports = { BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"], EMPTY_BUFFER: Buffer.alloc(0), GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), kListener: Symbol("kListener"), kStatusCode: Symbol("status-code"), kWebSocket: Symbol("websocket"), NOOP: () => { } }; } }); // node_modules/ws/lib/buffer-util.js var require_buffer_util = __commonJS({ "node_modules/ws/lib/buffer-util.js"(exports2, module2) { "use strict"; var { EMPTY_BUFFER } = require_constants5(); var FastBuffer = Buffer[Symbol.species]; function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; target.set(buf, offset); offset += buf.length; } if (offset < totalLength) { return new FastBuffer(target.buffer, target.byteOffset, offset); } return target; } function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } } function _unmask(buffer, mask) { for (let i = 0; i < buffer.length; i++) { buffer[i] ^= mask[i & 3]; } } function toArrayBuffer(buf) { if (buf.length === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); } function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = new FastBuffer(data); } else if (ArrayBuffer.isView(data)) { buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; } module2.exports = { concat, mask: _mask, toArrayBuffer, toBuffer, unmask: _unmask }; if (!process.env.WS_NO_BUFFER_UTIL) { try { const bufferUtil = require("bufferutil"); module2.exports.mask = function(source, mask, output, offset, length) { if (length < 48) _mask(source, mask, output, offset, length); else bufferUtil.mask(source, mask, output, offset, length); }; module2.exports.unmask = function(buffer, mask) { if (buffer.length < 32) _unmask(buffer, mask); else bufferUtil.unmask(buffer, mask); }; } catch (e) { } } } }); // node_modules/ws/lib/limiter.js var require_limiter = __commonJS({ "node_modules/ws/lib/limiter.js"(exports2, module2) { "use strict"; var kDone = Symbol("kDone"); var kRun = Symbol("kRun"); var Limiter = class { /** * Creates a new `Limiter`. * * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed * to run concurrently */ constructor(concurrency) { this[kDone] = () => { this.pending--; this[kRun](); }; this.concurrency = concurrency || Infinity; this.jobs = []; this.pending = 0; } /** * Adds a job to the queue. * * @param {Function} job The job to run * @public */ add(job) { this.jobs.push(job); this[kRun](); } /** * Removes a job from the queue and runs it if possible. * * @private */ [kRun]() { if (this.pending === this.concurrency) return; if (this.jobs.length) { const job = this.jobs.shift(); this.pending++; job(this[kDone]); } } }; module2.exports = Limiter; } }); // node_modules/ws/lib/permessage-deflate.js var require_permessage_deflate = __commonJS({ "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) { "use strict"; var zlib = require("zlib"); var bufferUtil = require_buffer_util(); var Limiter = require_limiter(); var { kStatusCode } = require_constants5(); var FastBuffer = Buffer[Symbol.species]; var TRAILER = Buffer.from([0, 0, 255, 255]); var kPerMessageDeflate = Symbol("permessage-deflate"); var kTotalLength = Symbol("total-length"); var kCallback = Symbol("callback"); var kBuffers = Symbol("buffers"); var kError = Symbol("error"); var zlibLimiter; var PerMessageDeflate = class { /** * Creates a PerMessageDeflate instance. * * @param {Object} [options] Configuration options * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support * for, or request, a custom client window size * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ * acknowledge disabling of client context takeover * @param {Number} [options.concurrencyLimit=10] The number of concurrent * calls to zlib * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the * use of a custom server window size * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept * disabling of server context takeover * @param {Number} [options.threshold=1024] Size (in bytes) below which * messages should not be compressed if context takeover is disabled * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on * deflate * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on * inflate * @param {Boolean} [isServer=false] Create the instance in either server or * client mode * @param {Number} [maxPayload=0] The maximum allowed message length */ constructor(options, isServer, maxPayload) { this._maxPayload = maxPayload | 0; this._options = options || {}; this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; this._isServer = !!isServer; this._deflate = null; this._inflate = null; this.params = null; if (!zlibLimiter) { const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; zlibLimiter = new Limiter(concurrency); } } /** * @type {String} */ static get extensionName() { return "permessage-deflate"; } /** * Create an extension negotiation offer. * * @return {Object} Extension parameters * @public */ offer() { const params = {}; if (this._options.serverNoContextTakeover) { params.server_no_context_takeover = true; } if (this._options.clientNoContextTakeover) { params.client_no_context_takeover = true; } if (this._options.serverMaxWindowBits) { params.server_max_window_bits = this._options.serverMaxWindowBits; } if (this._options.clientMaxWindowBits) { params.client_max_window_bits = this._options.clientMaxWindowBits; } else if (this._options.clientMaxWindowBits == null) { params.client_max_window_bits = true; } return params; } /** * Accept an extension negotiation offer/response. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Object} Accepted configuration * @public */ accept(configurations) { configurations = this.normalizeParams(configurations); this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); return this.params; } /** * Releases all resources used by the extension. * * @public */ cleanup() { if (this._inflate) { this._inflate.close(); this._inflate = null; } if (this._deflate) { const callback = this._deflate[kCallback]; this._deflate.close(); this._deflate = null; if (callback) { callback( new Error( "The deflate stream was closed while data was being processed" ) ); } } } /** * Accept an extension negotiation offer. * * @param {Array} offers The extension negotiation offers * @return {Object} Accepted configuration * @private */ acceptAsServer(offers) { const opts = this._options; const accepted = offers.find((params) => { if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { return false; } return true; }); if (!accepted) { throw new Error("None of the extension offers can be accepted"); } if (opts.serverNoContextTakeover) { accepted.server_no_context_takeover = true; } if (opts.clientNoContextTakeover) { accepted.client_no_context_takeover = true; } if (typeof opts.serverMaxWindowBits === "number") { accepted.server_max_window_bits = opts.serverMaxWindowBits; } if (typeof opts.clientMaxWindowBits === "number") { accepted.client_max_window_bits = opts.clientMaxWindowBits; } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { delete accepted.client_max_window_bits; } return accepted; } /** * Accept the extension negotiation response. * * @param {Array} response The extension negotiation response * @return {Object} Accepted configuration * @private */ acceptAsClient(response) { const params = response[0]; if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { throw new Error('Unexpected parameter "client_no_context_takeover"'); } if (!params.client_max_window_bits) { if (typeof this._options.clientMaxWindowBits === "number") { params.client_max_window_bits = this._options.clientMaxWindowBits; } } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { throw new Error( 'Unexpected or invalid parameter "client_max_window_bits"' ); } return params; } /** * Normalize parameters. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Array} The offers/response with normalized parameters * @private */ normalizeParams(configurations) { configurations.forEach((params) => { Object.keys(params).forEach((key) => { let value = params[key]; if (value.length > 1) { throw new Error(`Parameter "${key}" must have only a single value`); } value = value[0]; if (key === "client_max_window_bits") { if (value !== true) { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (!this._isServer) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else if (key === "server_max_window_bits") { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { if (value !== true) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else { throw new Error(`Unknown parameter "${key}"`); } params[key] = value; }); }); return configurations; } /** * Decompress data. Concurrency limited. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ decompress(data, fin, callback) { zlibLimiter.add((done) => { this._decompress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Compress data. Concurrency limited. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ compress(data, fin, callback) { zlibLimiter.add((done) => { this._compress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Decompress data. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _decompress(data, fin, callback) { const endpoint = this._isServer ? "client" : "server"; if (!this._inflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._inflate = zlib.createInflateRaw({ ...this._options.zlibInflateOptions, windowBits }); this._inflate[kPerMessageDeflate] = this; this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; this._inflate.on("error", inflateOnError); this._inflate.on("data", inflateOnData); } this._inflate[kCallback] = callback; this._inflate.write(data); if (fin) this._inflate.write(TRAILER); this._inflate.flush(() => { const err = this._inflate[kError]; if (err) { this._inflate.close(); this._inflate = null; callback(err); return; } const data2 = bufferUtil.concat( this._inflate[kBuffers], this._inflate[kTotalLength] ); if (this._inflate._readableState.endEmitted) { this._inflate.close(); this._inflate = null; } else { this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._inflate.reset(); } } callback(null, data2); }); } /** * Compress data. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _compress(data, fin, callback) { const endpoint = this._isServer ? "server" : "client"; if (!this._deflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._deflate = zlib.createDeflateRaw({ ...this._options.zlibDeflateOptions, windowBits }); this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; this._deflate.on("data", deflateOnData); } this._deflate[kCallback] = callback; this._deflate.write(data); this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { if (!this._deflate) { return; } let data2 = bufferUtil.concat( this._deflate[kBuffers], this._deflate[kTotalLength] ); if (fin) { data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4); } this._deflate[kCallback] = null; this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._deflate.reset(); } callback(null, data2); }); } }; module2.exports = PerMessageDeflate; function deflateOnData(chunk) { this[kBuffers].push(chunk); this[kTotalLength] += chunk.length; } function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError("Max payload size exceeded"); this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; this[kError][kStatusCode] = 1009; this.removeListener("data", inflateOnData); this.reset(); } function inflateOnError(err) { this[kPerMessageDeflate]._inflate = null; err[kStatusCode] = 1007; this[kCallback](err); } } }); // node_modules/ws/lib/validation.js var require_validation = __commonJS({ "node_modules/ws/lib/validation.js"(exports2, module2) { "use strict"; var { isUtf8 } = require("buffer"); var tokenChars = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 ]; function isValidStatusCode(code) { return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; } function _isValidUTF8(buf) { const len = buf.length; let i = 0; while (i < len) { if ((buf[i] & 128) === 0) { i++; } else if ((buf[i] & 224) === 192) { if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { return false; } i += 2; } else if ((buf[i] & 240) === 224) { if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong buf[i] === 237 && (buf[i + 1] & 224) === 160) { return false; } i += 3; } else if ((buf[i] & 248) === 240) { if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { return false; } i += 4; } else { return false; } } return true; } module2.exports = { isValidStatusCode, isValidUTF8: _isValidUTF8, tokenChars }; if (isUtf8) { module2.exports.isValidUTF8 = function(buf) { return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); }; } else if (!process.env.WS_NO_UTF_8_VALIDATE) { try { const isValidUTF8 = require("utf-8-validate"); module2.exports.isValidUTF8 = function(buf) { return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); }; } catch (e) { } } } }); // node_modules/ws/lib/receiver.js var require_receiver = __commonJS({ "node_modules/ws/lib/receiver.js"(exports2, module2) { "use strict"; var { Writable } = require("stream"); var PerMessageDeflate = require_permessage_deflate(); var { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants5(); var { concat, toArrayBuffer, unmask } = require_buffer_util(); var { isValidStatusCode, isValidUTF8 } = require_validation(); var FastBuffer = Buffer[Symbol.species]; var GET_INFO = 0; var GET_PAYLOAD_LENGTH_16 = 1; var GET_PAYLOAD_LENGTH_64 = 2; var GET_MASK = 3; var GET_DATA = 4; var INFLATING = 5; var DEFER_EVENT = 6; var Receiver2 = class extends Writable { /** * Creates a Receiver instance. * * @param {Object} [options] Options object * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {String} [options.binaryType=nodebuffer] The type for binary data * @param {Object} [options.extensions] An object containing the negotiated * extensions * @param {Boolean} [options.isServer=false] Specifies whether to operate in * client or server mode * @param {Number} [options.maxPayload=0] The maximum allowed message length * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages */ constructor(options = {}) { super(); this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true; this._binaryType = options.binaryType || BINARY_TYPES[0]; this._extensions = options.extensions || {}; this._isServer = !!options.isServer; this._maxPayload = options.maxPayload | 0; this._skipUTF8Validation = !!options.skipUTF8Validation; this[kWebSocket] = void 0; this._bufferedBytes = 0; this._buffers = []; this._compressed = false; this._payloadLength = 0; this._mask = void 0; this._fragmented = 0; this._masked = false; this._fin = false; this._opcode = 0; this._totalPayloadLength = 0; this._messageLength = 0; this._fragments = []; this._errored = false; this._loop = false; this._state = GET_INFO; } /** * Implements `Writable.prototype._write()`. * * @param {Buffer} chunk The chunk of data to write * @param {String} encoding The character encoding of `chunk` * @param {Function} cb Callback * @private */ _write(chunk, encoding, cb) { if (this._opcode === 8 && this._state == GET_INFO) return cb(); this._bufferedBytes += chunk.length; this._buffers.push(chunk); this.startLoop(cb); } /** * Consumes `n` bytes from the buffered data. * * @param {Number} n The number of bytes to consume * @return {Buffer} The consumed bytes * @private */ consume(n) { this._bufferedBytes -= n; if (n === this._buffers[0].length) return this._buffers.shift(); if (n < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n, buf.length - n ); return new FastBuffer(buf.buffer, buf.byteOffset, n); } const dst = Buffer.allocUnsafe(n); do { const buf = this._buffers[0]; const offset = dst.length - n; if (n >= buf.length) { dst.set(this._buffers.shift(), offset); } else { dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n, buf.length - n ); } n -= buf.length; } while (n > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { this._loop = true; do { switch (this._state) { case GET_INFO: this.getInfo(cb); break; case GET_PAYLOAD_LENGTH_16: this.getPayloadLength16(cb); break; case GET_PAYLOAD_LENGTH_64: this.getPayloadLength64(cb); break; case GET_MASK: this.getMask(); break; case GET_DATA: this.getData(cb); break; case INFLATING: case DEFER_EVENT: this._loop = false; return; } } while (this._loop); if (!this._errored) cb(); } /** * Reads the first two bytes of a frame. * * @param {Function} cb Callback * @private */ getInfo(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 48) !== 0) { const error48 = this.createError( RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3" ); cb(error48); return; } const compressed = (buf[0] & 64) === 64; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { const error48 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error48); return; } this._fin = (buf[0] & 128) === 128; this._opcode = buf[0] & 15; this._payloadLength = buf[1] & 127; if (this._opcode === 0) { if (compressed) { const error48 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error48); return; } if (!this._fragmented) { const error48 = this.createError( RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error48); return; } this._opcode = this._fragmented; } else if (this._opcode === 1 || this._opcode === 2) { if (this._fragmented) { const error48 = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error48); return; } this._compressed = compressed; } else if (this._opcode > 7 && this._opcode < 11) { if (!this._fin) { const error48 = this.createError( RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN" ); cb(error48); return; } if (compressed) { const error48 = this.createError( RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1" ); cb(error48); return; } if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { const error48 = this.createError( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" ); cb(error48); return; } } else { const error48 = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE" ); cb(error48); return; } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 128) === 128; if (this._isServer) { if (!this._masked) { const error48 = this.createError( RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK" ); cb(error48); return; } } else if (this._masked) { const error48 = this.createError( RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK" ); cb(error48); return; } if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else this.haveLength(cb); } /** * Gets extended payload length (7+16). * * @param {Function} cb Callback * @private */ getPayloadLength16(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); this.haveLength(cb); } /** * Gets extended payload length (7+64). * * @param {Function} cb Callback * @private */ getPayloadLength64(cb) { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); if (num > Math.pow(2, 53 - 32) - 1) { const error48 = this.createError( RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" ); cb(error48); return; } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); this.haveLength(cb); } /** * Payload length has been read. * * @param {Function} cb Callback * @private */ haveLength(cb) { if (this._payloadLength && this._opcode < 8) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { const error48 = this.createError( RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ); cb(error48); return; } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @private */ getData(cb) { let data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { unmask(data, this._mask); } } if (this._opcode > 7) { this.controlMessage(data, cb); return; } if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { this._messageLength = this._totalPayloadLength; this._fragments.push(data); } this.dataMessage(cb); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err, buf) => { if (err) return cb(err); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { const error48 = this.createError( RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ); cb(error48); return; } this._fragments.push(buf); } this.dataMessage(cb); if (this._state === GET_INFO) this.startLoop(cb); }); } /** * Handles a data message. * * @param {Function} cb Callback * @private */ dataMessage(cb) { if (!this._fin) { this._state = GET_INFO; return; } const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._fragments = []; if (this._opcode === 2) { let data; if (this._binaryType === "nodebuffer") { data = concat(fragments, messageLength); } else if (this._binaryType === "arraybuffer") { data = toArrayBuffer(concat(fragments, messageLength)); } else { data = fragments; } if (this._allowSynchronousEvents) { this.emit("message", data, true); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit("message", data, true); this._state = GET_INFO; this.startLoop(cb); }); } } else { const buf = concat(fragments, messageLength); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error48 = this.createError( Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8" ); cb(error48); return; } if (this._state === INFLATING || this._allowSynchronousEvents) { this.emit("message", buf, false); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit("message", buf, false); this._state = GET_INFO; this.startLoop(cb); }); } } } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data, cb) { if (this._opcode === 8) { if (data.length === 0) { this._loop = false; this.emit("conclude", 1005, EMPTY_BUFFER); this.end(); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { const error48 = this.createError( RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE" ); cb(error48); return; } const buf = new FastBuffer( data.buffer, data.byteOffset + 2, data.length - 2 ); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error48 = this.createError( Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8" ); cb(error48); return; } this._loop = false; this.emit("conclude", code, buf); this.end(); } this._state = GET_INFO; return; } if (this._allowSynchronousEvents) { this.emit(this._opcode === 9 ? "ping" : "pong", data); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit(this._opcode === 9 ? "ping" : "pong", data); this._state = GET_INFO; this.startLoop(cb); }); } } /** * Builds an error object. * * @param {function(new:Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @param {String} errorCode The exposed error code * @return {(Error|RangeError)} The error * @private */ createError(ErrorCtor, message, prefix, statusCode, errorCode) { this._loop = false; this._errored = true; const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, this.createError); err.code = errorCode; err[kStatusCode] = statusCode; return err; } }; module2.exports = Receiver2; } }); // node_modules/ws/lib/sender.js var require_sender = __commonJS({ "node_modules/ws/lib/sender.js"(exports2, module2) { "use strict"; var { Duplex } = require("stream"); var { randomFillSync } = require("crypto"); var PerMessageDeflate = require_permessage_deflate(); var { EMPTY_BUFFER } = require_constants5(); var { isValidStatusCode } = require_validation(); var { mask: applyMask, toBuffer } = require_buffer_util(); var kByteLength = Symbol("kByteLength"); var maskBuffer = Buffer.alloc(4); var RANDOM_POOL_SIZE = 8 * 1024; var randomPool; var randomPoolPointer = RANDOM_POOL_SIZE; var Sender2 = class _Sender { /** * Creates a Sender instance. * * @param {Duplex} socket The connection socket * @param {Object} [extensions] An object containing the negotiated extensions * @param {Function} [generateMask] The function used to generate the masking * key */ constructor(socket, extensions, generateMask) { this._extensions = extensions || {}; if (generateMask) { this._generateMask = generateMask; this._maskBuffer = Buffer.alloc(4); } this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._deflating = false; this._queue = []; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {(Buffer|String)} data The data to frame * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @return {(Buffer|String)[]} The framed data * @public */ static frame(data, options) { let mask; let merge2 = false; let offset = 2; let skipMasking = false; if (options.mask) { mask = options.maskBuffer || maskBuffer; if (options.generateMask) { options.generateMask(mask); } else { if (randomPoolPointer === RANDOM_POOL_SIZE) { if (randomPool === void 0) { randomPool = Buffer.alloc(RANDOM_POOL_SIZE); } randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); randomPoolPointer = 0; } mask[0] = randomPool[randomPoolPointer++]; mask[1] = randomPool[randomPoolPointer++]; mask[2] = randomPool[randomPoolPointer++]; mask[3] = randomPool[randomPoolPointer++]; } skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; offset = 6; } let dataLength; if (typeof data === "string") { if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { dataLength = options[kByteLength]; } else { data = Buffer.from(data); dataLength = data.length; } } else { dataLength = data.length; merge2 = options.mask && options.readOnly && !skipMasking; } let payloadLength = dataLength; if (dataLength >= 65536) { offset += 8; payloadLength = 127; } else if (dataLength > 125) { offset += 2; payloadLength = 126; } const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset); target[0] = options.fin ? options.opcode | 128 : options.opcode; if (options.rsv1) target[0] |= 64; target[1] = payloadLength; if (payloadLength === 126) { target.writeUInt16BE(dataLength, 2); } else if (payloadLength === 127) { target[2] = target[3] = 0; target.writeUIntBE(dataLength, 4, 6); } if (!options.mask) return [target, data]; target[1] |= 128; target[offset - 4] = mask[0]; target[offset - 3] = mask[1]; target[offset - 2] = mask[2]; target[offset - 1] = mask[3]; if (skipMasking) return [target, data]; if (merge2) { applyMask(data, mask, target, offset, dataLength); return [target]; } applyMask(data, mask, data, 0, dataLength); return [target, data]; } /** * Sends a close message to the other peer. * * @param {Number} [code] The status code component of the body * @param {(String|Buffer)} [data] The message component of the body * @param {Boolean} [mask=false] Specifies whether or not to mask the message * @param {Function} [cb] Callback * @public */ close(code, data, mask, cb) { let buf; if (code === void 0) { buf = EMPTY_BUFFER; } else if (typeof code !== "number" || !isValidStatusCode(code)) { throw new TypeError("First argument must be a valid error code number"); } else if (data === void 0 || !data.length) { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { const length = Buffer.byteLength(data); if (length > 123) { throw new RangeError("The message must not be greater than 123 bytes"); } buf = Buffer.allocUnsafe(2 + length); buf.writeUInt16BE(code, 0); if (typeof data === "string") { buf.write(data, 2); } else { buf.set(data, 2); } } const options = { [kByteLength]: buf.length, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 8, readOnly: false, rsv1: false }; if (this._deflating) { this.enqueue([this.dispatch, buf, false, options, cb]); } else { this.sendFrame(_Sender.frame(buf, options), cb); } } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ ping(data, mask, cb) { let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError("The data size must not be greater than 125 bytes"); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 9, readOnly, rsv1: false }; if (this._deflating) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(_Sender.frame(data, options), cb); } } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ pong(data, mask, cb) { let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError("The data size must not be greater than 125 bytes"); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 10, readOnly, rsv1: false }; if (this._deflating) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(_Sender.frame(data, options), cb); } } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} [options.binary=false] Specifies whether `data` is binary * or text * @param {Boolean} [options.compress=false] Specifies whether or not to * compress `data` * @param {Boolean} [options.fin=false] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Function} [cb] Callback * @public */ send(data, options, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; let opcode = options.binary ? 2 : 1; let rsv1 = options.compress; let byteLength; let readOnly; if (typeof data === "string") { byteLength = Buffer.byteLength(data); readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (this._firstFragment) { this._firstFragment = false; if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { rsv1 = byteLength >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; if (perMessageDeflate) { const opts = { [kByteLength]: byteLength, fin: options.fin, generateMask: this._generateMask, mask: options.mask, maskBuffer: this._maskBuffer, opcode, readOnly, rsv1 }; if (this._deflating) { this.enqueue([this.dispatch, data, this._compress, opts, cb]); } else { this.dispatch(data, this._compress, opts, cb); } } else { this.sendFrame( _Sender.frame(data, { [kByteLength]: byteLength, fin: options.fin, generateMask: this._generateMask, mask: options.mask, maskBuffer: this._maskBuffer, opcode, readOnly, rsv1: false }), cb ); } } /** * Dispatches a message. * * @param {(Buffer|String)} data The message to send * @param {Boolean} [compress=false] Specifies whether or not to compress * `data` * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ dispatch(data, compress, options, cb) { if (!compress) { this.sendFrame(_Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._bufferedBytes += options[kByteLength]; this._deflating = true; perMessageDeflate.compress(data, options.fin, (_, buf) => { if (this._socket.destroyed) { const err = new Error( "The socket was closed while data was being compressed" ); if (typeof cb === "function") cb(err); for (let i = 0; i < this._queue.length; i++) { const params = this._queue[i]; const callback = params[params.length - 1]; if (typeof callback === "function") callback(err); } return; } this._bufferedBytes -= options[kByteLength]; this._deflating = false; options.readOnly = false; this.sendFrame(_Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (!this._deflating && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[3][kByteLength]; Reflect.apply(params[0], this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[3][kByteLength]; this._queue.push(params); } /** * Sends a frame. * * @param {Buffer[]} list The frame to send * @param {Function} [cb] Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } }; module2.exports = Sender2; } }); // node_modules/ws/lib/event-target.js var require_event_target = __commonJS({ "node_modules/ws/lib/event-target.js"(exports2, module2) { "use strict"; var { kForOnEventAttribute, kListener } = require_constants5(); var kCode = Symbol("kCode"); var kData = Symbol("kData"); var kError = Symbol("kError"); var kMessage = Symbol("kMessage"); var kReason = Symbol("kReason"); var kTarget = Symbol("kTarget"); var kType = Symbol("kType"); var kWasClean = Symbol("kWasClean"); var Event2 = class { /** * Create a new `Event`. * * @param {String} type The name of the event * @throws {TypeError} If the `type` argument is not specified */ constructor(type) { this[kTarget] = null; this[kType] = type; } /** * @type {*} */ get target() { return this[kTarget]; } /** * @type {String} */ get type() { return this[kType]; } }; Object.defineProperty(Event2.prototype, "target", { enumerable: true }); Object.defineProperty(Event2.prototype, "type", { enumerable: true }); var CloseEvent = class extends Event2 { /** * Create a new `CloseEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {Number} [options.code=0] The status code explaining why the * connection was closed * @param {String} [options.reason=''] A human-readable string explaining why * the connection was closed * @param {Boolean} [options.wasClean=false] Indicates whether or not the * connection was cleanly closed */ constructor(type, options = {}) { super(type); this[kCode] = options.code === void 0 ? 0 : options.code; this[kReason] = options.reason === void 0 ? "" : options.reason; this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; } /** * @type {Number} */ get code() { return this[kCode]; } /** * @type {String} */ get reason() { return this[kReason]; } /** * @type {Boolean} */ get wasClean() { return this[kWasClean]; } }; Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); var ErrorEvent2 = class extends Event2 { /** * Create a new `ErrorEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.error=null] The error that generated this event * @param {String} [options.message=''] The error message */ constructor(type, options = {}) { super(type); this[kError] = options.error === void 0 ? null : options.error; this[kMessage] = options.message === void 0 ? "" : options.message; } /** * @type {*} */ get error() { return this[kError]; } /** * @type {String} */ get message() { return this[kMessage]; } }; Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true }); Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true }); var MessageEvent2 = class extends Event2 { /** * Create a new `MessageEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.data=null] The message content */ constructor(type, options = {}) { super(type); this[kData] = options.data === void 0 ? null : options.data; } /** * @type {*} */ get data() { return this[kData]; } }; Object.defineProperty(MessageEvent2.prototype, "data", { enumerable: true }); var EventTarget2 = { /** * Register an event listener. * * @param {String} type A string representing the event type to listen for * @param {(Function|Object)} handler The listener to add * @param {Object} [options] An options object specifies characteristics about * the event listener * @param {Boolean} [options.once=false] A `Boolean` indicating that the * listener should be invoked at most once after being added. If `true`, * the listener would be automatically removed when invoked. * @public */ addEventListener(type, handler, options = {}) { for (const listener of this.listeners(type)) { if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { return; } } let wrapper; if (type === "message") { wrapper = function onMessage(data, isBinary) { const event = new MessageEvent2("message", { data: isBinary ? data : data.toString() }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === "close") { wrapper = function onClose(code, message) { const event = new CloseEvent("close", { code, reason: message.toString(), wasClean: this._closeFrameReceived && this._closeFrameSent }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === "error") { wrapper = function onError(error48) { const event = new ErrorEvent2("error", { error: error48, message: error48.message }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === "open") { wrapper = function onOpen() { const event = new Event2("open"); event[kTarget] = this; callListener(handler, this, event); }; } else { return; } wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; wrapper[kListener] = handler; if (options.once) { this.once(type, wrapper); } else { this.on(type, wrapper); } }, /** * Remove an event listener. * * @param {String} type A string representing the event type to remove * @param {(Function|Object)} handler The listener to remove * @public */ removeEventListener(type, handler) { for (const listener of this.listeners(type)) { if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { this.removeListener(type, listener); break; } } } }; module2.exports = { CloseEvent, ErrorEvent: ErrorEvent2, Event: Event2, EventTarget: EventTarget2, MessageEvent: MessageEvent2 }; function callListener(listener, thisArg, event) { if (typeof listener === "object" && listener.handleEvent) { listener.handleEvent.call(listener, event); } else { listener.call(thisArg, event); } } } }); // node_modules/ws/lib/extension.js var require_extension = __commonJS({ "node_modules/ws/lib/extension.js"(exports2, module2) { "use strict"; var { tokenChars } = require_validation(); function push(dest, name, elem) { if (dest[name] === void 0) dest[name] = [elem]; else dest[name].push(elem); } function parse3(header) { const offers = /* @__PURE__ */ Object.create(null); let params = /* @__PURE__ */ Object.create(null); let mustUnescape = false; let isEscaping = false; let inQuotes = false; let extensionName; let paramName; let start = -1; let code = -1; let end = -1; let i = 0; for (; i < header.length; i++) { code = header.charCodeAt(i); if (extensionName === void 0) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (i !== 0 && (code === 32 || code === 9)) { if (end === -1 && start !== -1) end = i; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const name = header.slice(start, end); if (code === 44) { push(offers, name, params); params = /* @__PURE__ */ Object.create(null); } else { extensionName = name; } start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (paramName === void 0) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 32 || code === 9) { if (end === -1 && start !== -1) end = i; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; push(params, header.slice(start, end), true); if (code === 44) { push(offers, extensionName, params); params = /* @__PURE__ */ Object.create(null); extensionName = void 0; } start = end = -1; } else if (code === 61 && start !== -1 && end === -1) { paramName = header.slice(start, i); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else { if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (start === -1) start = i; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 34 && start !== -1) { inQuotes = false; end = i; } else if (code === 92) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (code === 34 && header.charCodeAt(i - 1) === 61) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (start !== -1 && (code === 32 || code === 9)) { if (end === -1) end = i; } else if (code === 59 || code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; let value = header.slice(start, end); if (mustUnescape) { value = value.replace(/\\/g, ""); mustUnescape = false; } push(params, paramName, value); if (code === 44) { push(offers, extensionName, params); params = /* @__PURE__ */ Object.create(null); extensionName = void 0; } paramName = void 0; start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } } if (start === -1 || inQuotes || code === 32 || code === 9) { throw new SyntaxError("Unexpected end of input"); } if (end === -1) end = i; const token = header.slice(start, end); if (extensionName === void 0) { push(offers, token, params); } else { if (paramName === void 0) { push(params, token, true); } else if (mustUnescape) { push(params, paramName, token.replace(/\\/g, "")); } else { push(params, paramName, token); } push(offers, extensionName, params); } return offers; } function format(extensions) { return Object.keys(extensions).map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations.map((params) => { return [extension].concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values.map((v) => v === true ? k : `${k}=${v}`).join("; "); }) ).join("; "); }).join(", "); }).join(", "); } module2.exports = { format, parse: parse3 }; } }); // node_modules/ws/lib/websocket.js var require_websocket = __commonJS({ "node_modules/ws/lib/websocket.js"(exports2, module2) { "use strict"; var EventEmitter = require("events"); var https = require("https"); var http = require("http"); var net = require("net"); var tls = require("tls"); var { randomBytes, createHash } = require("crypto"); var { Duplex, Readable: Readable2 } = require("stream"); var { URL: URL3 } = require("url"); var PerMessageDeflate = require_permessage_deflate(); var Receiver2 = require_receiver(); var Sender2 = require_sender(); var { BINARY_TYPES, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants5(); var { EventTarget: { addEventListener, removeEventListener } } = require_event_target(); var { format, parse: parse3 } = require_extension(); var { toBuffer } = require_buffer_util(); var closeTimeout = 30 * 1e3; var kAborted = Symbol("kAborted"); var protocolVersions = [8, 13]; var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; var WebSocket2 = class _WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|URL)} address The URL to which to connect * @param {(String|String[])} [protocols] The subprotocols * @param {Object} [options] Connection options */ constructor(address, protocols, options) { super(); this._binaryType = BINARY_TYPES[0]; this._closeCode = 1006; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = EMPTY_BUFFER; this._closeTimer = null; this._extensions = {}; this._paused = false; this._protocol = ""; this._readyState = _WebSocket.CONNECTING; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._bufferedAmount = 0; this._isServer = false; this._redirects = 0; if (protocols === void 0) { protocols = []; } else if (!Array.isArray(protocols)) { if (typeof protocols === "object" && protocols !== null) { options = protocols; protocols = []; } else { protocols = [protocols]; } } initAsClient(this, address, protocols, options); } else { this._autoPong = options.autoPong; this._isServer = true; } } /** * This deviates from the WHATWG interface since ws doesn't support the * required default "blob" type (instead we define a custom "nodebuffer" * type). * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return this._bufferedAmount; return this._socket._writableState.length + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * @type {Boolean} */ get isPaused() { return this._paused; } /** * @type {Function} */ /* istanbul ignore next */ get onclose() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onerror() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onopen() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onmessage() { return null; } /** * @type {String} */ get protocol() { return this._protocol; } /** * @type {Number} */ get readyState() { return this._readyState; } /** * @type {String} */ get url() { return this._url; } /** * Set up the socket and the internal resources. * * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Object} options Options object * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.maxPayload=0] The maximum allowed message size * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private */ setSocket(socket, head, options) { const receiver = new Receiver2({ allowSynchronousEvents: options.allowSynchronousEvents, binaryType: this.binaryType, extensions: this._extensions, isServer: this._isServer, maxPayload: options.maxPayload, skipUTF8Validation: options.skipUTF8Validation }); this._sender = new Sender2(socket, this._extensions, options.generateMask); this._receiver = receiver; this._socket = socket; receiver[kWebSocket] = this; socket[kWebSocket] = this; receiver.on("conclude", receiverOnConclude); receiver.on("drain", receiverOnDrain); receiver.on("error", receiverOnError); receiver.on("message", receiverOnMessage); receiver.on("ping", receiverOnPing); receiver.on("pong", receiverOnPong); if (socket.setTimeout) socket.setTimeout(0); if (socket.setNoDelay) socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on("close", socketOnClose); socket.on("data", socketOnData); socket.on("end", socketOnEnd); socket.on("error", socketOnError); this._readyState = _WebSocket.OPEN; this.emit("open"); } /** * Emit the `'close'` event. * * @private */ emitClose() { if (!this._socket) { this._readyState = _WebSocket.CLOSED; this.emit("close", this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this._readyState = _WebSocket.CLOSED; this.emit("close", this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} [code] Status code explaining why the connection is closing * @param {(String|Buffer)} [data] The reason why the connection is * closing * @public */ close(code, data) { if (this.readyState === _WebSocket.CLOSED) return; if (this.readyState === _WebSocket.CONNECTING) { const msg = "WebSocket was closed before the connection was established"; abortHandshake(this, this._req, msg); return; } if (this.readyState === _WebSocket.CLOSING) { if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { this._socket.end(); } return; } this._readyState = _WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err) => { if (err) return; this._closeFrameSent = true; if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { this._socket.end(); } }); this._closeTimer = setTimeout( this._socket.destroy.bind(this._socket), closeTimeout ); } /** * Pause the socket. * * @public */ pause() { if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { return; } this._paused = true; this._socket.pause(); } /** * Send a ping. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof data === "function") { cb = data; data = mask = void 0; } else if (typeof mask === "function") { cb = mask; mask = void 0; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === void 0) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof data === "function") { cb = data; data = mask = void 0; } else if (typeof mask === "function") { cb = mask; mask = void 0; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === void 0) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Resume the socket. * * @public */ resume() { if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { return; } this._paused = false; if (!this._receiver._writableState.needDrain) this._socket.resume(); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} [options] Options object * @param {Boolean} [options.binary] Specifies whether `data` is binary or * text * @param {Boolean} [options.compress] Specifies whether or not to compress * `data` * @param {Boolean} [options.fin=true] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask] Specifies whether or not to mask `data` * @param {Function} [cb] Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === _WebSocket.CONNECTING) { throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } if (typeof options === "function") { cb = options; options = {}; } if (typeof data === "number") data = data.toString(); if (this.readyState !== _WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== "string", mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === _WebSocket.CLOSED) return; if (this.readyState === _WebSocket.CONNECTING) { const msg = "WebSocket was closed before the connection was established"; abortHandshake(this, this._req, msg); return; } if (this._socket) { this._readyState = _WebSocket.CLOSING; this._socket.destroy(); } } }; Object.defineProperty(WebSocket2, "CONNECTING", { enumerable: true, value: readyStates.indexOf("CONNECTING") }); Object.defineProperty(WebSocket2.prototype, "CONNECTING", { enumerable: true, value: readyStates.indexOf("CONNECTING") }); Object.defineProperty(WebSocket2, "OPEN", { enumerable: true, value: readyStates.indexOf("OPEN") }); Object.defineProperty(WebSocket2.prototype, "OPEN", { enumerable: true, value: readyStates.indexOf("OPEN") }); Object.defineProperty(WebSocket2, "CLOSING", { enumerable: true, value: readyStates.indexOf("CLOSING") }); Object.defineProperty(WebSocket2.prototype, "CLOSING", { enumerable: true, value: readyStates.indexOf("CLOSING") }); Object.defineProperty(WebSocket2, "CLOSED", { enumerable: true, value: readyStates.indexOf("CLOSED") }); Object.defineProperty(WebSocket2.prototype, "CLOSED", { enumerable: true, value: readyStates.indexOf("CLOSED") }); [ "binaryType", "bufferedAmount", "extensions", "isPaused", "protocol", "readyState", "url" ].forEach((property) => { Object.defineProperty(WebSocket2.prototype, property, { enumerable: true }); }); ["open", "error", "close", "message"].forEach((method) => { Object.defineProperty(WebSocket2.prototype, `on${method}`, { enumerable: true, get() { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) return listener[kListener]; } return null; }, set(handler) { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) { this.removeListener(method, listener); break; } } if (typeof handler !== "function") return; this.addEventListener(method, handler, { [kForOnEventAttribute]: true }); } }); }); WebSocket2.prototype.addEventListener = addEventListener; WebSocket2.prototype.removeEventListener = removeEventListener; module2.exports = WebSocket2; function initAsClient(websocket, address, protocols, options) { const opts = { allowSynchronousEvents: true, autoPong: true, protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, socketPath: void 0, hostname: void 0, protocol: void 0, timeout: void 0, method: "GET", host: void 0, path: void 0, port: void 0 }; websocket._autoPong = opts.autoPong; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` ); } let parsedUrl; if (address instanceof URL3) { parsedUrl = address; } else { try { parsedUrl = new URL3(address); } catch (e) { throw new SyntaxError(`Invalid URL: ${address}`); } } if (parsedUrl.protocol === "http:") { parsedUrl.protocol = "ws:"; } else if (parsedUrl.protocol === "https:") { parsedUrl.protocol = "wss:"; } websocket._url = parsedUrl.href; const isSecure = parsedUrl.protocol === "wss:"; const isIpcUrl = parsedUrl.protocol === "ws+unix:"; let invalidUrlMessage; if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`; } else if (isIpcUrl && !parsedUrl.pathname) { invalidUrlMessage = "The URL's pathname is empty"; } else if (parsedUrl.hash) { invalidUrlMessage = "The URL contains a fragment identifier"; } if (invalidUrlMessage) { const err = new SyntaxError(invalidUrlMessage); if (websocket._redirects === 0) { throw err; } else { emitErrorAndClose(websocket, err); return; } } const defaultPort = isSecure ? 443 : 80; const key = randomBytes(16).toString("base64"); const request = isSecure ? https.request : http.request; const protocolSet = /* @__PURE__ */ new Set(); let perMessageDeflate; opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = { ...opts.headers, "Sec-WebSocket-Version": opts.protocolVersion, "Sec-WebSocket-Key": key, Connection: "Upgrade", Upgrade: "websocket" }; opts.path = parsedUrl.pathname + parsedUrl.search; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate( opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload ); opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() }); } if (protocols.length) { for (const protocol of protocols) { if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { throw new SyntaxError( "An invalid or duplicated subprotocol was specified" ); } protocolSet.add(protocol); } opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers["Sec-WebSocket-Origin"] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.username || parsedUrl.password) { opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; } if (isIpcUrl) { const parts = opts.path.split(":"); opts.socketPath = parts[0]; opts.path = parts[1]; } let req; if (opts.followRedirects) { if (websocket._redirects === 0) { websocket._originalIpc = isIpcUrl; websocket._originalSecure = isSecure; websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; const headers = options && options.headers; options = { ...options, headers: {} }; if (headers) { for (const [key2, value] of Object.entries(headers)) { options.headers[key2.toLowerCase()] = value; } } } else if (websocket.listenerCount("redirect") === 0) { const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; if (!isSameHost || websocket._originalSecure && !isSecure) { delete opts.headers.authorization; delete opts.headers.cookie; if (!isSameHost) delete opts.headers.host; opts.auth = void 0; } } if (opts.auth && !options.headers.authorization) { options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); } req = websocket._req = request(opts); if (websocket._redirects) { websocket.emit("redirect", websocket.url, req); } } else { req = websocket._req = request(opts); } if (opts.timeout) { req.on("timeout", () => { abortHandshake(websocket, req, "Opening handshake has timed out"); }); } req.on("error", (err) => { if (req === null || req[kAborted]) return; req = websocket._req = null; emitErrorAndClose(websocket, err); }); req.on("response", (res) => { const location = res.headers.location; const statusCode = res.statusCode; if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake(websocket, req, "Maximum redirects exceeded"); return; } req.abort(); let addr; try { addr = new URL3(location, address); } catch (e) { const err = new SyntaxError(`Invalid URL: ${location}`); emitErrorAndClose(websocket, err); return; } initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit("unexpected-response", req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on("upgrade", (res, socket, head) => { websocket.emit("upgrade", res); if (websocket.readyState !== WebSocket2.CONNECTING) return; req = websocket._req = null; const upgrade = res.headers.upgrade; if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { abortHandshake(websocket, socket, "Invalid Upgrade header"); return; } const digest = createHash("sha1").update(key + GUID).digest("base64"); if (res.headers["sec-websocket-accept"] !== digest) { abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); return; } const serverProt = res.headers["sec-websocket-protocol"]; let protError; if (serverProt !== void 0) { if (!protocolSet.size) { protError = "Server sent a subprotocol but none was requested"; } else if (!protocolSet.has(serverProt)) { protError = "Server sent an invalid subprotocol"; } } else if (protocolSet.size) { protError = "Server sent no subprotocol"; } if (protError) { abortHandshake(websocket, socket, protError); return; } if (serverProt) websocket._protocol = serverProt; const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; if (secWebSocketExtensions !== void 0) { if (!perMessageDeflate) { const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; abortHandshake(websocket, socket, message); return; } let extensions; try { extensions = parse3(secWebSocketExtensions); } catch (err) { const message = "Invalid Sec-WebSocket-Extensions header"; abortHandshake(websocket, socket, message); return; } const extensionNames = Object.keys(extensions); if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { const message = "Server indicated an extension that was not requested"; abortHandshake(websocket, socket, message); return; } try { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); } catch (err) { const message = "Invalid Sec-WebSocket-Extensions header"; abortHandshake(websocket, socket, message); return; } websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } websocket.setSocket(socket, head, { allowSynchronousEvents: opts.allowSynchronousEvents, generateMask: opts.generateMask, maxPayload: opts.maxPayload, skipUTF8Validation: opts.skipUTF8Validation }); }); if (opts.finishRequest) { opts.finishRequest(req, websocket); } else { req.end(); } } function emitErrorAndClose(websocket, err) { websocket._readyState = WebSocket2.CLOSING; websocket.emit("error", err); websocket.emitClose(); } function netConnect(options) { options.path = options.socketPath; return net.connect(options); } function tlsConnect(options) { options.path = void 0; if (!options.servername && options.servername !== "") { options.servername = net.isIP(options.host) ? "" : options.host; } return tls.connect(options); } function abortHandshake(websocket, stream, message) { websocket._readyState = WebSocket2.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream[kAborted] = true; stream.abort(); if (stream.socket && !stream.socket.destroyed) { stream.socket.destroy(); } process.nextTick(emitErrorAndClose, websocket, err); } else { stream.destroy(err); stream.once("error", websocket.emit.bind(websocket, "error")); stream.once("close", websocket.emitClose.bind(websocket)); } } function sendAfterClose(websocket, data, cb) { if (data) { const length = toBuffer(data).length; if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err = new Error( `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` ); process.nextTick(cb, err); } } function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (websocket._socket[kWebSocket] === void 0) return; websocket._socket.removeListener("data", socketOnData); process.nextTick(resume, websocket._socket); if (code === 1005) websocket.close(); else websocket.close(code, reason); } function receiverOnDrain() { const websocket = this[kWebSocket]; if (!websocket.isPaused) websocket._socket.resume(); } function receiverOnError(err) { const websocket = this[kWebSocket]; if (websocket._socket[kWebSocket] !== void 0) { websocket._socket.removeListener("data", socketOnData); process.nextTick(resume, websocket._socket); websocket.close(err[kStatusCode]); } websocket.emit("error", err); } function receiverOnFinish() { this[kWebSocket].emitClose(); } function receiverOnMessage(data, isBinary) { this[kWebSocket].emit("message", data, isBinary); } function receiverOnPing(data) { const websocket = this[kWebSocket]; if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); websocket.emit("ping", data); } function receiverOnPong(data) { this[kWebSocket].emit("pong", data); } function resume(stream) { stream.resume(); } function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener("close", socketOnClose); this.removeListener("data", socketOnData); this.removeListener("end", socketOnEnd); websocket._readyState = WebSocket2.CLOSING; let chunk; if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) { websocket._receiver.write(chunk); } websocket._receiver.end(); this[kWebSocket] = void 0; clearTimeout(websocket._closeTimer); if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { websocket.emitClose(); } else { websocket._receiver.on("error", receiverOnFinish); websocket._receiver.on("finish", receiverOnFinish); } } function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } function socketOnEnd() { const websocket = this[kWebSocket]; websocket._readyState = WebSocket2.CLOSING; websocket._receiver.end(); this.end(); } function socketOnError() { const websocket = this[kWebSocket]; this.removeListener("error", socketOnError); this.on("error", NOOP); if (websocket) { websocket._readyState = WebSocket2.CLOSING; this.destroy(); } } } }); // node_modules/ws/lib/subprotocol.js var require_subprotocol = __commonJS({ "node_modules/ws/lib/subprotocol.js"(exports2, module2) { "use strict"; var { tokenChars } = require_validation(); function parse3(header) { const protocols = /* @__PURE__ */ new Set(); let start = -1; let end = -1; let i = 0; for (i; i < header.length; i++) { const code = header.charCodeAt(i); if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (i !== 0 && (code === 32 || code === 9)) { if (end === -1 && start !== -1) end = i; } else if (code === 44) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const protocol2 = header.slice(start, end); if (protocols.has(protocol2)) { throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); } protocols.add(protocol2); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } if (start === -1 || end !== -1) { throw new SyntaxError("Unexpected end of input"); } const protocol = header.slice(start, i); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); return protocols; } module2.exports = { parse: parse3 }; } }); // node_modules/ws/lib/websocket-server.js var require_websocket_server = __commonJS({ "node_modules/ws/lib/websocket-server.js"(exports2, module2) { "use strict"; var EventEmitter = require("events"); var http = require("http"); var { Duplex } = require("stream"); var { createHash } = require("crypto"); var extension = require_extension(); var PerMessageDeflate = require_permessage_deflate(); var subprotocol = require_subprotocol(); var WebSocket2 = require_websocket(); var { GUID, kWebSocket } = require_constants5(); var keyRegex = /^[+/0-9A-Za-z]{22}==$/; var RUNNING = 0; var CLOSING = 1; var CLOSED = 2; var WebSocketServer2 = class extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Boolean} [options.autoPong=true] Specifies whether or not to * automatically send a pong in response to a ping * @param {Number} [options.backlog=511] The maximum length of the queue of * pending connections * @param {Boolean} [options.clientTracking=true] Specifies whether or not to * track clients * @param {Function} [options.handleProtocols] A hook to handle protocols * @param {String} [options.host] The hostname where to bind the server * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Boolean} [options.noServer=false] Enable no server mode * @param {String} [options.path] Accept only connections matching this path * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable * permessage-deflate * @param {Number} [options.port] The port where to bind the server * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S * server to use * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @param {Function} [options.verifyClient] A hook to reject connections * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` * class to use. It must be the `WebSocket` class or class that extends it * @param {Function} [callback] A listener for the `listening` event */ constructor(options, callback) { super(); options = { allowSynchronousEvents: true, autoPong: true, maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: false, handleProtocols: null, clientTracking: true, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null, WebSocket: WebSocket2, ...options }; if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { throw new TypeError( 'One and only one of the "port", "server", or "noServer" options must be specified' ); } if (options.port != null) { this._server = http.createServer((req, res) => { const body = http.STATUS_CODES[426]; res.writeHead(426, { "Content-Length": body.length, "Content-Type": "text/plain" }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { const emitConnection = this.emit.bind(this, "connection"); this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, "listening"), error: this.emit.bind(this, "error"), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, emitConnection); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) { this.clients = /* @__PURE__ */ new Set(); this._shouldEmitClose = false; } this.options = options; this._state = RUNNING; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Stop the server from accepting new connections and emit the `'close'` event * when all existing connections are closed. * * @param {Function} [cb] A one-time listener for the `'close'` event * @public */ close(cb) { if (this._state === CLOSED) { if (cb) { this.once("close", () => { cb(new Error("The server is not running")); }); } process.nextTick(emitClose, this); return; } if (cb) this.once("close", cb); if (this._state === CLOSING) return; this._state = CLOSING; if (this.options.noServer || this.options.server) { if (this._server) { this._removeListeners(); this._removeListeners = this._server = null; } if (this.clients) { if (!this.clients.size) { process.nextTick(emitClose, this); } else { this._shouldEmitClose = true; } } else { process.nextTick(emitClose, this); } } else { const server = this._server; this._removeListeners(); this._removeListeners = this._server = null; server.close(() => { emitClose(this); }); } } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index = req.url.indexOf("?"); const pathname = index !== -1 ? req.url.slice(0, index) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on("error", socketOnError); const key = req.headers["sec-websocket-key"]; const upgrade = req.headers.upgrade; const version2 = +req.headers["sec-websocket-version"]; if (req.method !== "GET") { const message = "Invalid HTTP method"; abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); return; } if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { const message = "Invalid Upgrade header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (key === void 0 || !keyRegex.test(key)) { const message = "Missing or invalid Sec-WebSocket-Key header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (version2 !== 8 && version2 !== 13) { const message = "Missing or invalid Sec-WebSocket-Version header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (!this.shouldHandle(req)) { abortHandshake(socket, 400); return; } const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; let protocols = /* @__PURE__ */ new Set(); if (secWebSocketProtocol !== void 0) { try { protocols = subprotocol.parse(secWebSocketProtocol); } catch (err) { const message = "Invalid Sec-WebSocket-Protocol header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; const extensions = {}; if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { const perMessageDeflate = new PerMessageDeflate( this.options.perMessageDeflate, true, this.options.maxPayload ); try { const offers = extension.parse(secWebSocketExtensions); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err) { const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } if (this.options.verifyClient) { const info = { origin: req.headers[`${version2 === 8 ? "sec-websocket-origin" : "origin"}`], secure: !!(req.socket.authorized || req.socket.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade( extensions, key, protocols, req, socket, head, cb ); }); return; } if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); } this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {Object} extensions The accepted extensions * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Set} protocols The subprotocols * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @throws {Error} If called more than once with the same socket * @private */ completeUpgrade(extensions, key, protocols, req, socket, head, cb) { if (!socket.readable || !socket.writable) return socket.destroy(); if (socket[kWebSocket]) { throw new Error( "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" ); } if (this._state > RUNNING) return abortHandshake(socket, 503); const digest = createHash("sha1").update(key + GUID).digest("base64"); const headers = [ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", `Sec-WebSocket-Accept: ${digest}` ]; const ws2 = new this.options.WebSocket(null, void 0, this.options); if (protocols.size) { const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws2._protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = extension.format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws2._extensions = extensions; } this.emit("headers", headers, req); socket.write(headers.concat("\r\n").join("\r\n")); socket.removeListener("error", socketOnError); ws2.setSocket(socket, head, { allowSynchronousEvents: this.options.allowSynchronousEvents, maxPayload: this.options.maxPayload, skipUTF8Validation: this.options.skipUTF8Validation }); if (this.clients) { this.clients.add(ws2); ws2.on("close", () => { this.clients.delete(ws2); if (this._shouldEmitClose && !this.clients.size) { process.nextTick(emitClose, this); } }); } cb(ws2, req); } }; module2.exports = WebSocketServer2; function addListeners(server, map2) { for (const event of Object.keys(map2)) server.on(event, map2[event]); return function removeListeners() { for (const event of Object.keys(map2)) { server.removeListener(event, map2[event]); } }; } function emitClose(server) { server._state = CLOSED; server.emit("close"); } function socketOnError() { this.destroy(); } function abortHandshake(socket, code, message, headers) { message = message || http.STATUS_CODES[code]; headers = { Connection: "close", "Content-Type": "text/html", "Content-Length": Buffer.byteLength(message), ...headers }; socket.once("finish", socket.destroy); socket.end( `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message ); } function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { if (server.listenerCount("wsClientError")) { const err = new Error(message); Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); server.emit("wsClientError", err, socket, req); } else { abortHandshake(socket, code, message); } } } }); // node_modules/yaml/dist/nodes/identity.js var require_identity = __commonJS({ "node_modules/yaml/dist/nodes/identity.js"(exports2) { "use strict"; var ALIAS = Symbol.for("yaml.alias"); var DOC = Symbol.for("yaml.document"); var MAP = Symbol.for("yaml.map"); var PAIR = Symbol.for("yaml.pair"); var SCALAR = Symbol.for("yaml.scalar"); var SEQ = Symbol.for("yaml.seq"); var NODE_TYPE = Symbol.for("yaml.node.type"); var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; function isCollection(node) { if (node && typeof node === "object") switch (node[NODE_TYPE]) { case MAP: case SEQ: return true; } return false; } function isNode(node) { if (node && typeof node === "object") switch (node[NODE_TYPE]) { case ALIAS: case MAP: case SCALAR: case SEQ: return true; } return false; } var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; exports2.ALIAS = ALIAS; exports2.DOC = DOC; exports2.MAP = MAP; exports2.NODE_TYPE = NODE_TYPE; exports2.PAIR = PAIR; exports2.SCALAR = SCALAR; exports2.SEQ = SEQ; exports2.hasAnchor = hasAnchor; exports2.isAlias = isAlias; exports2.isCollection = isCollection; exports2.isDocument = isDocument; exports2.isMap = isMap; exports2.isNode = isNode; exports2.isPair = isPair; exports2.isScalar = isScalar; exports2.isSeq = isSeq; } }); // node_modules/yaml/dist/visit.js var require_visit = __commonJS({ "node_modules/yaml/dist/visit.js"(exports2) { "use strict"; var identity = require_identity(); var BREAK = Symbol("break visit"); var SKIP = Symbol("skip children"); var REMOVE = Symbol("remove node"); function visit(node, visitor) { const visitor_ = initVisitor(visitor); if (identity.isDocument(node)) { const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); if (cd === REMOVE) node.contents = null; } else visit_(null, node, visitor_, Object.freeze([])); } visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; function visit_(key, node, visitor, path) { const ctrl = callVisitor(key, node, visitor, path); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { replaceNode(key, path, ctrl); return visit_(key, ctrl, visitor, path); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { path = Object.freeze(path.concat(node)); for (let i = 0; i < node.items.length; ++i) { const ci = visit_(i, node.items[i], visitor, path); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) return BREAK; else if (ci === REMOVE) { node.items.splice(i, 1); i -= 1; } } } else if (identity.isPair(node)) { path = Object.freeze(path.concat(node)); const ck = visit_("key", node.key, visitor, path); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; const cv = visit_("value", node.value, visitor, path); if (cv === BREAK) return BREAK; else if (cv === REMOVE) node.value = null; } } return ctrl; } async function visitAsync(node, visitor) { const visitor_ = initVisitor(visitor); if (identity.isDocument(node)) { const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); if (cd === REMOVE) node.contents = null; } else await visitAsync_(null, node, visitor_, Object.freeze([])); } visitAsync.BREAK = BREAK; visitAsync.SKIP = SKIP; visitAsync.REMOVE = REMOVE; async function visitAsync_(key, node, visitor, path) { const ctrl = await callVisitor(key, node, visitor, path); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { replaceNode(key, path, ctrl); return visitAsync_(key, ctrl, visitor, path); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { path = Object.freeze(path.concat(node)); for (let i = 0; i < node.items.length; ++i) { const ci = await visitAsync_(i, node.items[i], visitor, path); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) return BREAK; else if (ci === REMOVE) { node.items.splice(i, 1); i -= 1; } } } else if (identity.isPair(node)) { path = Object.freeze(path.concat(node)); const ck = await visitAsync_("key", node.key, visitor, path); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; const cv = await visitAsync_("value", node.value, visitor, path); if (cv === BREAK) return BREAK; else if (cv === REMOVE) node.value = null; } } return ctrl; } function initVisitor(visitor) { if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { return Object.assign({ Alias: visitor.Node, Map: visitor.Node, Scalar: visitor.Node, Seq: visitor.Node }, visitor.Value && { Map: visitor.Value, Scalar: visitor.Value, Seq: visitor.Value }, visitor.Collection && { Map: visitor.Collection, Seq: visitor.Collection }, visitor); } return visitor; } function callVisitor(key, node, visitor, path) { if (typeof visitor === "function") return visitor(key, node, path); if (identity.isMap(node)) return visitor.Map?.(key, node, path); if (identity.isSeq(node)) return visitor.Seq?.(key, node, path); if (identity.isPair(node)) return visitor.Pair?.(key, node, path); if (identity.isScalar(node)) return visitor.Scalar?.(key, node, path); if (identity.isAlias(node)) return visitor.Alias?.(key, node, path); return void 0; } function replaceNode(key, path, node) { const parent = path[path.length - 1]; if (identity.isCollection(parent)) { parent.items[key] = node; } else if (identity.isPair(parent)) { if (key === "key") parent.key = node; else parent.value = node; } else if (identity.isDocument(parent)) { parent.contents = node; } else { const pt = identity.isAlias(parent) ? "alias" : "scalar"; throw new Error(`Cannot replace node with ${pt} parent`); } } exports2.visit = visit; exports2.visitAsync = visitAsync; } }); // node_modules/yaml/dist/doc/directives.js var require_directives = __commonJS({ "node_modules/yaml/dist/doc/directives.js"(exports2) { "use strict"; var identity = require_identity(); var visit = require_visit(); var escapeChars = { "!": "%21", ",": "%2C", "[": "%5B", "]": "%5D", "{": "%7B", "}": "%7D" }; var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); var Directives = class _Directives { constructor(yaml2, tags) { this.docStart = null; this.docEnd = false; this.yaml = Object.assign({}, _Directives.defaultYaml, yaml2); this.tags = Object.assign({}, _Directives.defaultTags, tags); } clone() { const copy = new _Directives(this.yaml, this.tags); copy.docStart = this.docStart; return copy; } /** * During parsing, get a Directives instance for the current document and * update the stream state according to the current version's spec. */ atDocument() { const res = new _Directives(this.yaml, this.tags); switch (this.yaml.version) { case "1.1": this.atNextDocument = true; break; case "1.2": this.atNextDocument = false; this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.2" }; this.tags = Object.assign({}, _Directives.defaultTags); break; } return res; } /** * @param onError - May be called even if the action was successful * @returns `true` on success */ add(line, onError) { if (this.atNextDocument) { this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; this.tags = Object.assign({}, _Directives.defaultTags); this.atNextDocument = false; } const parts = line.trim().split(/[ \t]+/); const name = parts.shift(); switch (name) { case "%TAG": { if (parts.length !== 2) { onError(0, "%TAG directive should contain exactly two parts"); if (parts.length < 2) return false; } const [handle, prefix] = parts; this.tags[handle] = prefix; return true; } case "%YAML": { this.yaml.explicit = true; if (parts.length !== 1) { onError(0, "%YAML directive should contain exactly one part"); return false; } const [version2] = parts; if (version2 === "1.1" || version2 === "1.2") { this.yaml.version = version2; return true; } else { const isValid2 = /^\d+\.\d+$/.test(version2); onError(6, `Unsupported YAML version ${version2}`, isValid2); return false; } } default: onError(0, `Unknown directive ${name}`, true); return false; } } /** * Resolves a tag, matching handles to those defined in %TAG directives. * * @returns Resolved tag, which may also be the non-specific tag `'!'` or a * `'!local'` tag, or `null` if unresolvable. */ tagName(source, onError) { if (source === "!") return "!"; if (source[0] !== "!") { onError(`Not a valid tag: ${source}`); return null; } if (source[1] === "<") { const verbatim = source.slice(2, -1); if (verbatim === "!" || verbatim === "!!") { onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); return null; } if (source[source.length - 1] !== ">") onError("Verbatim tags must end with a >"); return verbatim; } const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); if (!suffix) onError(`The ${source} tag has no suffix`); const prefix = this.tags[handle]; if (prefix) { try { return prefix + decodeURIComponent(suffix); } catch (error48) { onError(String(error48)); return null; } } if (handle === "!") return source; onError(`Could not resolve tag: ${source}`); return null; } /** * Given a fully resolved tag, returns its printable string form, * taking into account current tag prefixes and defaults. */ tagString(tag) { for (const [handle, prefix] of Object.entries(this.tags)) { if (tag.startsWith(prefix)) return handle + escapeTagName(tag.substring(prefix.length)); } return tag[0] === "!" ? tag : `!<${tag}>`; } toString(doc) { const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; const tagEntries = Object.entries(this.tags); let tagNames; if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) { const tags = {}; visit.visit(doc.contents, (_key, node) => { if (identity.isNode(node) && node.tag) tags[node.tag] = true; }); tagNames = Object.keys(tags); } else tagNames = []; for (const [handle, prefix] of tagEntries) { if (handle === "!!" && prefix === "tag:yaml.org,2002:") continue; if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) lines.push(`%TAG ${handle} ${prefix}`); } return lines.join("\n"); } }; Directives.defaultYaml = { explicit: false, version: "1.2" }; Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; exports2.Directives = Directives; } }); // node_modules/yaml/dist/doc/anchors.js var require_anchors = __commonJS({ "node_modules/yaml/dist/doc/anchors.js"(exports2) { "use strict"; var identity = require_identity(); var visit = require_visit(); function anchorIsValid(anchor) { if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { const sa = JSON.stringify(anchor); const msg = `Anchor must not contain whitespace or control characters: ${sa}`; throw new Error(msg); } return true; } function anchorNames(root) { const anchors = /* @__PURE__ */ new Set(); visit.visit(root, { Value(_key, node) { if (node.anchor) anchors.add(node.anchor); } }); return anchors; } function findNewAnchor(prefix, exclude) { for (let i = 1; true; ++i) { const name = `${prefix}${i}`; if (!exclude.has(name)) return name; } } function createNodeAnchors(doc, prefix) { const aliasObjects = []; const sourceObjects = /* @__PURE__ */ new Map(); let prevAnchors = null; return { onAnchor: (source) => { aliasObjects.push(source); prevAnchors ?? (prevAnchors = anchorNames(doc)); const anchor = findNewAnchor(prefix, prevAnchors); prevAnchors.add(anchor); return anchor; }, /** * With circular references, the source node is only resolved after all * of its child nodes are. This is why anchors are set only after all of * the nodes have been created. */ setAnchors: () => { for (const source of aliasObjects) { const ref = sourceObjects.get(source); if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) { ref.node.anchor = ref.anchor; } else { const error48 = new Error("Failed to resolve repeated object (this should not happen)"); error48.source = source; throw error48; } } }, sourceObjects }; } exports2.anchorIsValid = anchorIsValid; exports2.anchorNames = anchorNames; exports2.createNodeAnchors = createNodeAnchors; exports2.findNewAnchor = findNewAnchor; } }); // node_modules/yaml/dist/doc/applyReviver.js var require_applyReviver = __commonJS({ "node_modules/yaml/dist/doc/applyReviver.js"(exports2) { "use strict"; function applyReviver(reviver, obj, key, val) { if (val && typeof val === "object") { if (Array.isArray(val)) { for (let i = 0, len = val.length; i < len; ++i) { const v0 = val[i]; const v1 = applyReviver(reviver, val, String(i), v0); if (v1 === void 0) delete val[i]; else if (v1 !== v0) val[i] = v1; } } else if (val instanceof Map) { for (const k of Array.from(val.keys())) { const v0 = val.get(k); const v1 = applyReviver(reviver, val, k, v0); if (v1 === void 0) val.delete(k); else if (v1 !== v0) val.set(k, v1); } } else if (val instanceof Set) { for (const v0 of Array.from(val)) { const v1 = applyReviver(reviver, val, v0, v0); if (v1 === void 0) val.delete(v0); else if (v1 !== v0) { val.delete(v0); val.add(v1); } } } else { for (const [k, v0] of Object.entries(val)) { const v1 = applyReviver(reviver, val, k, v0); if (v1 === void 0) delete val[k]; else if (v1 !== v0) val[k] = v1; } } } return reviver.call(obj, key, val); } exports2.applyReviver = applyReviver; } }); // node_modules/yaml/dist/nodes/toJS.js var require_toJS = __commonJS({ "node_modules/yaml/dist/nodes/toJS.js"(exports2) { "use strict"; var identity = require_identity(); function toJS(value, arg, ctx) { if (Array.isArray(value)) return value.map((v, i) => toJS(v, String(i), ctx)); if (value && typeof value.toJSON === "function") { if (!ctx || !identity.hasAnchor(value)) return value.toJSON(arg, ctx); const data = { aliasCount: 0, count: 1, res: void 0 }; ctx.anchors.set(value, data); ctx.onCreate = (res2) => { data.res = res2; delete ctx.onCreate; }; const res = value.toJSON(arg, ctx); if (ctx.onCreate) ctx.onCreate(res); return res; } if (typeof value === "bigint" && !ctx?.keep) return Number(value); return value; } exports2.toJS = toJS; } }); // node_modules/yaml/dist/nodes/Node.js var require_Node = __commonJS({ "node_modules/yaml/dist/nodes/Node.js"(exports2) { "use strict"; var applyReviver = require_applyReviver(); var identity = require_identity(); var toJS = require_toJS(); var NodeBase = class { constructor(type) { Object.defineProperty(this, identity.NODE_TYPE, { value: type }); } /** Create a copy of this node. */ clone() { const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); if (this.range) copy.range = this.range.slice(); return copy; } /** A plain JavaScript representation of this node. */ toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { if (!identity.isDocument(doc)) throw new TypeError("A document argument is required"); const ctx = { anchors: /* @__PURE__ */ new Map(), doc, keep: true, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 }; const res = toJS.toJS(this, "", ctx); if (typeof onAnchor === "function") for (const { count, res: res2 } of ctx.anchors.values()) onAnchor(res2, count); return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; } }; exports2.NodeBase = NodeBase; } }); // node_modules/yaml/dist/nodes/Alias.js var require_Alias = __commonJS({ "node_modules/yaml/dist/nodes/Alias.js"(exports2) { "use strict"; var anchors = require_anchors(); var visit = require_visit(); var identity = require_identity(); var Node = require_Node(); var toJS = require_toJS(); var Alias = class extends Node.NodeBase { constructor(source) { super(identity.ALIAS); this.source = source; Object.defineProperty(this, "tag", { set() { throw new Error("Alias nodes cannot have tags"); } }); } /** * Resolve the value of this alias within `doc`, finding the last * instance of the `source` anchor before this node. */ resolve(doc, ctx) { let nodes; if (ctx?.aliasResolveCache) { nodes = ctx.aliasResolveCache; } else { nodes = []; visit.visit(doc, { Node: (_key, node) => { if (identity.isAlias(node) || identity.hasAnchor(node)) nodes.push(node); } }); if (ctx) ctx.aliasResolveCache = nodes; } let found = void 0; for (const node of nodes) { if (node === this) break; if (node.anchor === this.source) found = node; } return found; } toJSON(_arg, ctx) { if (!ctx) return { source: this.source }; const { anchors: anchors2, doc, maxAliasCount } = ctx; const source = this.resolve(doc, ctx); if (!source) { const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; throw new ReferenceError(msg); } let data = anchors2.get(source); if (!data) { toJS.toJS(source, null, ctx); data = anchors2.get(source); } if (data?.res === void 0) { const msg = "This should not happen: Alias anchor was not resolved?"; throw new ReferenceError(msg); } if (maxAliasCount >= 0) { data.count += 1; if (data.aliasCount === 0) data.aliasCount = getAliasCount(doc, source, anchors2); if (data.count * data.aliasCount > maxAliasCount) { const msg = "Excessive alias count indicates a resource exhaustion attack"; throw new ReferenceError(msg); } } return data.res; } toString(ctx, _onComment, _onChompKeep) { const src = `*${this.source}`; if (ctx) { anchors.anchorIsValid(this.source); if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; throw new Error(msg); } if (ctx.implicitKey) return `${src} `; } return src; } }; function getAliasCount(doc, node, anchors2) { if (identity.isAlias(node)) { const source = node.resolve(doc); const anchor = anchors2 && source && anchors2.get(source); return anchor ? anchor.count * anchor.aliasCount : 0; } else if (identity.isCollection(node)) { let count = 0; for (const item of node.items) { const c = getAliasCount(doc, item, anchors2); if (c > count) count = c; } return count; } else if (identity.isPair(node)) { const kc = getAliasCount(doc, node.key, anchors2); const vc = getAliasCount(doc, node.value, anchors2); return Math.max(kc, vc); } return 1; } exports2.Alias = Alias; } }); // node_modules/yaml/dist/nodes/Scalar.js var require_Scalar = __commonJS({ "node_modules/yaml/dist/nodes/Scalar.js"(exports2) { "use strict"; var identity = require_identity(); var Node = require_Node(); var toJS = require_toJS(); var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; var Scalar = class extends Node.NodeBase { constructor(value) { super(identity.SCALAR); this.value = value; } toJSON(arg, ctx) { return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); } toString() { return String(this.value); } }; Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; Scalar.PLAIN = "PLAIN"; Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; exports2.Scalar = Scalar; exports2.isScalarValue = isScalarValue; } }); // node_modules/yaml/dist/doc/createNode.js var require_createNode = __commonJS({ "node_modules/yaml/dist/doc/createNode.js"(exports2) { "use strict"; var Alias = require_Alias(); var identity = require_identity(); var Scalar = require_Scalar(); var defaultTagPrefix = "tag:yaml.org,2002:"; function findTagObject(value, tagName, tags) { if (tagName) { const match = tags.filter((t) => t.tag === tagName); const tagObj = match.find((t) => !t.format) ?? match[0]; if (!tagObj) throw new Error(`Tag ${tagName} not found`); return tagObj; } return tags.find((t) => t.identify?.(value) && !t.format); } function createNode(value, tagName, ctx) { if (identity.isDocument(value)) value = value.contents; if (identity.isNode(value)) return value; if (identity.isPair(value)) { const map2 = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); map2.items.push(value); return map2; } if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { value = value.valueOf(); } const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; let ref = void 0; if (aliasDuplicateObjects && value && typeof value === "object") { ref = sourceObjects.get(value); if (ref) { ref.anchor ?? (ref.anchor = onAnchor(value)); return new Alias.Alias(ref.anchor); } else { ref = { anchor: null, node: null }; sourceObjects.set(value, ref); } } if (tagName?.startsWith("!!")) tagName = defaultTagPrefix + tagName.slice(2); let tagObj = findTagObject(value, tagName, schema.tags); if (!tagObj) { if (value && typeof value.toJSON === "function") { value = value.toJSON(); } if (!value || typeof value !== "object") { const node2 = new Scalar.Scalar(value); if (ref) ref.node = node2; return node2; } tagObj = value instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value) ? schema[identity.SEQ] : schema[identity.MAP]; } if (onTagObj) { onTagObj(tagObj); delete ctx.onTagObj; } const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value); if (tagName) node.tag = tagName; else if (!tagObj.default) node.tag = tagObj.tag; if (ref) ref.node = node; return node; } exports2.createNode = createNode; } }); // node_modules/yaml/dist/nodes/Collection.js var require_Collection = __commonJS({ "node_modules/yaml/dist/nodes/Collection.js"(exports2) { "use strict"; var createNode = require_createNode(); var identity = require_identity(); var Node = require_Node(); function collectionFromPath(schema, path, value) { let v = value; for (let i = path.length - 1; i >= 0; --i) { const k = path[i]; if (typeof k === "number" && Number.isInteger(k) && k >= 0) { const a = []; a[k] = v; v = a; } else { v = /* @__PURE__ */ new Map([[k, v]]); } } return createNode.createNode(v, void 0, { aliasDuplicateObjects: false, keepUndefined: false, onAnchor: () => { throw new Error("This should not happen, please report a bug."); }, schema, sourceObjects: /* @__PURE__ */ new Map() }); } var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; var Collection = class extends Node.NodeBase { constructor(type, schema) { super(type); Object.defineProperty(this, "schema", { value: schema, configurable: true, enumerable: false, writable: true }); } /** * Create a copy of this collection. * * @param schema - If defined, overwrites the original's schema */ clone(schema) { const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); if (schema) copy.schema = schema; copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); if (this.range) copy.range = this.range.slice(); return copy; } /** * Adds a value to the collection. For `!!map` and `!!omap` the value must * be a Pair instance or a `{ key, value }` object, which may not have a key * that already exists in the map. */ addIn(path, value) { if (isEmptyPath(path)) this.add(value); else { const [key, ...rest] = path; const node = this.get(key, true); if (identity.isCollection(node)) node.addIn(rest, value); else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } /** * Removes a value from the collection. * @returns `true` if the item was found and removed. */ deleteIn(path) { const [key, ...rest] = path; if (rest.length === 0) return this.delete(key); const node = this.get(key, true); if (identity.isCollection(node)) return node.deleteIn(rest); else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path, keepScalar) { const [key, ...rest] = path; const node = this.get(key, true); if (rest.length === 0) return !keepScalar && identity.isScalar(node) ? node.value : node; else return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0; } hasAllNullValues(allowScalar) { return this.items.every((node) => { if (!identity.isPair(node)) return false; const n = node.value; return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; }); } /** * Checks if the collection includes a value with the key `key`. */ hasIn(path) { const [key, ...rest] = path; if (rest.length === 0) return this.has(key); const node = this.get(key, true); return identity.isCollection(node) ? node.hasIn(rest) : false; } /** * Sets a value in this collection. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path, value) { const [key, ...rest] = path; if (rest.length === 0) { this.set(key, value); } else { const node = this.get(key, true); if (identity.isCollection(node)) node.setIn(rest, value); else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } }; exports2.Collection = Collection; exports2.collectionFromPath = collectionFromPath; exports2.isEmptyPath = isEmptyPath; } }); // node_modules/yaml/dist/stringify/stringifyComment.js var require_stringifyComment = __commonJS({ "node_modules/yaml/dist/stringify/stringifyComment.js"(exports2) { "use strict"; var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); function indentComment(comment, indent) { if (/^\n+$/.test(comment)) return comment.substring(1); return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; } var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; exports2.indentComment = indentComment; exports2.lineComment = lineComment; exports2.stringifyComment = stringifyComment; } }); // node_modules/yaml/dist/stringify/foldFlowLines.js var require_foldFlowLines = __commonJS({ "node_modules/yaml/dist/stringify/foldFlowLines.js"(exports2) { "use strict"; var FOLD_FLOW = "flow"; var FOLD_BLOCK = "block"; var FOLD_QUOTED = "quoted"; function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { if (!lineWidth || lineWidth < 0) return text; if (lineWidth < minContentWidth) minContentWidth = 0; const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); if (text.length <= endStep) return text; const folds = []; const escapedFolds = {}; let end = lineWidth - indent.length; if (typeof indentAtStart === "number") { if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0); else end = lineWidth - indentAtStart; } let split = void 0; let prev = void 0; let overflow = false; let i = -1; let escStart = -1; let escEnd = -1; if (mode === FOLD_BLOCK) { i = consumeMoreIndentedLines(text, i, indent.length); if (i !== -1) end = i + endStep; } for (let ch; ch = text[i += 1]; ) { if (mode === FOLD_QUOTED && ch === "\\") { escStart = i; switch (text[i + 1]) { case "x": i += 3; break; case "u": i += 5; break; case "U": i += 9; break; default: i += 1; } escEnd = i; } if (ch === "\n") { if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i, indent.length); end = i + indent.length + endStep; split = void 0; } else { if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { const next = text[i + 1]; if (next && next !== " " && next !== "\n" && next !== " ") split = i; } if (i >= end) { if (split) { folds.push(split); end = split + endStep; split = void 0; } else if (mode === FOLD_QUOTED) { while (prev === " " || prev === " ") { prev = ch; ch = text[i += 1]; overflow = true; } const j = i > escEnd + 1 ? i - 2 : escStart - 1; if (escapedFolds[j]) return text; folds.push(j); escapedFolds[j] = true; end = j + endStep; split = void 0; } else { overflow = true; } } } prev = ch; } if (overflow && onOverflow) onOverflow(); if (folds.length === 0) return text; if (onFold) onFold(); let res = text.slice(0, folds[0]); for (let i2 = 0; i2 < folds.length; ++i2) { const fold = folds[i2]; const end2 = folds[i2 + 1] || text.length; if (fold === 0) res = ` ${indent}${text.slice(0, end2)}`; else { if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; res += ` ${indent}${text.slice(fold + 1, end2)}`; } } return res; } function consumeMoreIndentedLines(text, i, indent) { let end = i; let start = i + 1; let ch = text[start]; while (ch === " " || ch === " ") { if (i < start + indent) { ch = text[++i]; } else { do { ch = text[++i]; } while (ch && ch !== "\n"); end = i; start = i + 1; ch = text[start]; } } return end; } exports2.FOLD_BLOCK = FOLD_BLOCK; exports2.FOLD_FLOW = FOLD_FLOW; exports2.FOLD_QUOTED = FOLD_QUOTED; exports2.foldFlowLines = foldFlowLines; } }); // node_modules/yaml/dist/stringify/stringifyString.js var require_stringifyString = __commonJS({ "node_modules/yaml/dist/stringify/stringifyString.js"(exports2) { "use strict"; var Scalar = require_Scalar(); var foldFlowLines = require_foldFlowLines(); var getFoldOptions = (ctx, isBlock) => ({ indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, lineWidth: ctx.options.lineWidth, minContentWidth: ctx.options.minContentWidth }); var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); function lineLengthOverLimit(str, lineWidth, indentLength) { if (!lineWidth || lineWidth < 0) return false; const limit = lineWidth - indentLength; const strLen = str.length; if (strLen <= limit) return false; for (let i = 0, start = 0; i < strLen; ++i) { if (str[i] === "\n") { if (i - start > limit) return true; start = i + 1; if (strLen - start <= limit) return false; } } return true; } function doubleQuotedString(value, ctx) { const json2 = JSON.stringify(value); if (ctx.options.doubleQuotedAsJSON) return json2; const { implicitKey } = ctx; const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); let str = ""; let start = 0; for (let i = 0, ch = json2[i]; ch; ch = json2[++i]) { if (ch === " " && json2[i + 1] === "\\" && json2[i + 2] === "n") { str += json2.slice(start, i) + "\\ "; i += 1; start = i; ch = "\\"; } if (ch === "\\") switch (json2[i + 1]) { case "u": { str += json2.slice(start, i); const code = json2.substr(i + 2, 4); switch (code) { case "0000": str += "\\0"; break; case "0007": str += "\\a"; break; case "000b": str += "\\v"; break; case "001b": str += "\\e"; break; case "0085": str += "\\N"; break; case "00a0": str += "\\_"; break; case "2028": str += "\\L"; break; case "2029": str += "\\P"; break; default: if (code.substr(0, 2) === "00") str += "\\x" + code.substr(2); else str += json2.substr(i, 6); } i += 5; start = i + 1; } break; case "n": if (implicitKey || json2[i + 2] === '"' || json2.length < minMultiLineLength) { i += 1; } else { str += json2.slice(start, i) + "\n\n"; while (json2[i + 2] === "\\" && json2[i + 3] === "n" && json2[i + 4] !== '"') { str += "\n"; i += 2; } str += indent; if (json2[i + 2] === " ") str += "\\"; i += 1; start = i + 1; } break; default: i += 1; } } str = start ? str + json2.slice(start) : json2; return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); } function singleQuotedString(value, ctx) { if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& ${indent}`) + "'"; return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); } function quotedString(value, ctx) { const { singleQuote } = ctx.options; let qs; if (singleQuote === false) qs = doubleQuotedString; else { const hasDouble = value.includes('"'); const hasSingle = value.includes("'"); if (hasDouble && !hasSingle) qs = singleQuotedString; else if (hasSingle && !hasDouble) qs = doubleQuotedString; else qs = singleQuote ? singleQuotedString : doubleQuotedString; } return qs(value, ctx); } var blockEndNewlines; try { blockEndNewlines = new RegExp("(^|(?\n"; let chomp; let endStart; for (endStart = value.length; endStart > 0; --endStart) { const ch = value[endStart - 1]; if (ch !== "\n" && ch !== " " && ch !== " ") break; } let end = value.substring(endStart); const endNlPos = end.indexOf("\n"); if (endNlPos === -1) { chomp = "-"; } else if (value === end || endNlPos !== end.length - 1) { chomp = "+"; if (onChompKeep) onChompKeep(); } else { chomp = ""; } if (end) { value = value.slice(0, -end.length); if (end[end.length - 1] === "\n") end = end.slice(0, -1); end = end.replace(blockEndNewlines, `$&${indent}`); } let startWithSpace = false; let startEnd; let startNlPos = -1; for (startEnd = 0; startEnd < value.length; ++startEnd) { const ch = value[startEnd]; if (ch === " ") startWithSpace = true; else if (ch === "\n") startNlPos = startEnd; else break; } let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); if (start) { value = value.substring(start.length); start = start.replace(/\n+/g, `$&${indent}`); } const indentSize = indent ? "2" : "1"; let header = (startWithSpace ? indentSize : "") + chomp; if (comment) { header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); if (onComment) onComment(); } if (!literal2) { const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); let literalFallback = false; const foldOptions = getFoldOptions(ctx, true); if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) { foldOptions.onOverflow = () => { literalFallback = true; }; } const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); if (!literalFallback) return `>${header} ${indent}${body}`; } value = value.replace(/\n+/g, `$&${indent}`); return `|${header} ${indent}${start}${value}${end}`; } function plainString(item, ctx, onComment, onChompKeep) { const { type, value } = item; const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) { return quotedString(value, ctx); } if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); } if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes("\n")) { return blockString(item, ctx, onComment, onChompKeep); } if (containsDocumentMarker(value)) { if (indent === "") { ctx.forceBlockIndent = true; return blockString(item, ctx, onComment, onChompKeep); } else if (implicitKey && indent === indentStep) { return quotedString(value, ctx); } } const str = value.replace(/\n+/g, `$& ${indent}`); if (actualString) { const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); const { compat, tags } = ctx.doc.schema; if (tags.some(test) || compat?.some(test)) return quotedString(value, ctx); } return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); } function stringifyString(item, ctx, onComment, onChompKeep) { const { implicitKey, inFlow } = ctx; const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); let { type } = item; if (type !== Scalar.Scalar.QUOTE_DOUBLE) { if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) type = Scalar.Scalar.QUOTE_DOUBLE; } const _stringify = (_type) => { switch (_type) { case Scalar.Scalar.BLOCK_FOLDED: case Scalar.Scalar.BLOCK_LITERAL: return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); case Scalar.Scalar.QUOTE_DOUBLE: return doubleQuotedString(ss.value, ctx); case Scalar.Scalar.QUOTE_SINGLE: return singleQuotedString(ss.value, ctx); case Scalar.Scalar.PLAIN: return plainString(ss, ctx, onComment, onChompKeep); default: return null; } }; let res = _stringify(type); if (res === null) { const { defaultKeyType, defaultStringType } = ctx.options; const t = implicitKey && defaultKeyType || defaultStringType; res = _stringify(t); if (res === null) throw new Error(`Unsupported default string type ${t}`); } return res; } exports2.stringifyString = stringifyString; } }); // node_modules/yaml/dist/stringify/stringify.js var require_stringify = __commonJS({ "node_modules/yaml/dist/stringify/stringify.js"(exports2) { "use strict"; var anchors = require_anchors(); var identity = require_identity(); var stringifyComment = require_stringifyComment(); var stringifyString = require_stringifyString(); function createStringifyContext(doc, options) { const opt = Object.assign({ blockQuote: true, commentString: stringifyComment.stringifyComment, defaultKeyType: null, defaultStringType: "PLAIN", directives: null, doubleQuotedAsJSON: false, doubleQuotedMinMultiLineLength: 40, falseStr: "false", flowCollectionPadding: true, indentSeq: true, lineWidth: 80, minContentWidth: 20, nullStr: "null", simpleKeys: false, singleQuote: null, trailingComma: false, trueStr: "true", verifyAliasOrder: true }, doc.schema.toStringOptions, options); let inFlow; switch (opt.collectionStyle) { case "block": inFlow = false; break; case "flow": inFlow = true; break; default: inFlow = null; } return { anchors: /* @__PURE__ */ new Set(), doc, flowCollectionPadding: opt.flowCollectionPadding ? " " : "", indent: "", indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", inFlow, options: opt }; } function getTagObject(tags, item) { if (item.tag) { const match = tags.filter((t) => t.tag === item.tag); if (match.length > 0) return match.find((t) => t.format === item.format) ?? match[0]; } let tagObj = void 0; let obj; if (identity.isScalar(item)) { obj = item.value; let match = tags.filter((t) => t.identify?.(obj)); if (match.length > 1) { const testMatch = match.filter((t) => t.test); if (testMatch.length > 0) match = testMatch; } tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); } else { obj = item; tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); } if (!tagObj) { const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); throw new Error(`Tag not resolved for ${name} value`); } return tagObj; } function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) { if (!doc.directives) return ""; const props = []; const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; if (anchor && anchors.anchorIsValid(anchor)) { anchors$1.add(anchor); props.push(`&${anchor}`); } const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); if (tag) props.push(doc.directives.tagString(tag)); return props.join(" "); } function stringify(item, ctx, onComment, onChompKeep) { if (identity.isPair(item)) return item.toString(ctx, onComment, onChompKeep); if (identity.isAlias(item)) { if (ctx.doc.directives) return item.toString(ctx); if (ctx.resolvedAliases?.has(item)) { throw new TypeError(`Cannot stringify circular structure without alias nodes`); } else { if (ctx.resolvedAliases) ctx.resolvedAliases.add(item); else ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); item = item.resolve(ctx.doc); } } let tagObj = void 0; const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); const props = stringifyProps(node, tagObj, ctx); if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); if (!props) return str; return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} ${ctx.indent}${str}`; } exports2.createStringifyContext = createStringifyContext; exports2.stringify = stringify; } }); // node_modules/yaml/dist/stringify/stringifyPair.js var require_stringifyPair = __commonJS({ "node_modules/yaml/dist/stringify/stringifyPair.js"(exports2) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var stringify = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; let keyComment = identity.isNode(key) && key.comment || null; if (simpleKeys) { if (keyComment) { throw new Error("With simple keys, key nodes cannot have comments"); } if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") { const msg = "With simple keys, collection cannot be used as a key value"; throw new Error(msg); } } let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object")); ctx = Object.assign({}, ctx, { allNullValues: false, implicitKey: !explicitKey && (simpleKeys || !allNullValues), indent: indent + indentStep }); let keyCommentDone = false; let chompKeep = false; let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); if (!explicitKey && !ctx.inFlow && str.length > 1024) { if (simpleKeys) throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); explicitKey = true; } if (ctx.inFlow) { if (allNullValues || value == null) { if (keyCommentDone && onComment) onComment(); return str === "" ? "?" : explicitKey ? `? ${str}` : str; } } else if (allNullValues && !simpleKeys || value == null && explicitKey) { str = `? ${str}`; if (keyComment && !keyCommentDone) { str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); } else if (chompKeep && onChompKeep) onChompKeep(); return str; } if (keyCommentDone) keyComment = null; if (explicitKey) { if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); str = `? ${str} ${indent}:`; } else { str = `${str}:`; if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); } let vsb, vcb, valueComment; if (identity.isNode(value)) { vsb = !!value.spaceBefore; vcb = value.commentBefore; valueComment = value.comment; } else { vsb = false; vcb = null; valueComment = null; if (value && typeof value === "object") value = doc.createNode(value); } ctx.implicitKey = false; if (!explicitKey && !keyComment && identity.isScalar(value)) ctx.indentAtStart = str.length + 1; chompKeep = false; if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) { ctx.indent = ctx.indent.substring(2); } let valueCommentDone = false; const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); let ws2 = " "; if (keyComment || vsb || vcb) { ws2 = vsb ? "\n" : ""; if (vcb) { const cs = commentString(vcb); ws2 += ` ${stringifyComment.indentComment(cs, ctx.indent)}`; } if (valueStr === "" && !ctx.inFlow) { if (ws2 === "\n" && valueComment) ws2 = "\n\n"; } else { ws2 += ` ${ctx.indent}`; } } else if (!explicitKey && identity.isCollection(value)) { const vs0 = valueStr[0]; const nl0 = valueStr.indexOf("\n"); const hasNewline = nl0 !== -1; const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; if (hasNewline || !flow) { let hasPropsLine = false; if (hasNewline && (vs0 === "&" || vs0 === "!")) { let sp0 = valueStr.indexOf(" "); if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { sp0 = valueStr.indexOf(" ", sp0 + 1); } if (sp0 === -1 || nl0 < sp0) hasPropsLine = true; } if (!hasPropsLine) ws2 = ` ${ctx.indent}`; } } else if (valueStr === "" || valueStr[0] === "\n") { ws2 = ""; } str += ws2 + valueStr; if (ctx.inFlow) { if (valueCommentDone && onComment) onComment(); } else if (valueComment && !valueCommentDone) { str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); } else if (chompKeep && onChompKeep) { onChompKeep(); } return str; } exports2.stringifyPair = stringifyPair; } }); // node_modules/yaml/dist/log.js var require_log = __commonJS({ "node_modules/yaml/dist/log.js"(exports2) { "use strict"; var node_process = require("process"); function debug2(logLevel, ...messages) { if (logLevel === "debug") console.log(...messages); } function warn(logLevel, warning) { if (logLevel === "debug" || logLevel === "warn") { if (typeof node_process.emitWarning === "function") node_process.emitWarning(warning); else console.warn(warning); } } exports2.debug = debug2; exports2.warn = warn; } }); // node_modules/yaml/dist/schema/yaml-1.1/merge.js var require_merge = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/merge.js"(exports2) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var MERGE_KEY = "<<"; var merge2 = { identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, default: "key", tag: "tag:yaml.org,2002:merge", test: /^<<$/, resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { addToJSMap: addMergeToJSMap }), stringify: () => MERGE_KEY }; var isMergeKey = (ctx, key) => (merge2.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge2.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge2.tag && tag.default); function addMergeToJSMap(ctx, map2, value) { value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value; if (identity.isSeq(value)) for (const it of value.items) mergeValue(ctx, map2, it); else if (Array.isArray(value)) for (const it of value) mergeValue(ctx, map2, it); else mergeValue(ctx, map2, value); } function mergeValue(ctx, map2, value) { const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value; if (!identity.isMap(source)) throw new Error("Merge sources must be maps or map aliases"); const srcMap = source.toJSON(null, ctx, Map); for (const [key, value2] of srcMap) { if (map2 instanceof Map) { if (!map2.has(key)) map2.set(key, value2); } else if (map2 instanceof Set) { map2.add(key); } else if (!Object.prototype.hasOwnProperty.call(map2, key)) { Object.defineProperty(map2, key, { value: value2, writable: true, enumerable: true, configurable: true }); } } return map2; } exports2.addMergeToJSMap = addMergeToJSMap; exports2.isMergeKey = isMergeKey; exports2.merge = merge2; } }); // node_modules/yaml/dist/nodes/addPairToJSMap.js var require_addPairToJSMap = __commonJS({ "node_modules/yaml/dist/nodes/addPairToJSMap.js"(exports2) { "use strict"; var log = require_log(); var merge2 = require_merge(); var stringify = require_stringify(); var identity = require_identity(); var toJS = require_toJS(); function addPairToJSMap(ctx, map2, { key, value }) { if (identity.isNode(key) && key.addToJSMap) key.addToJSMap(ctx, map2, value); else if (merge2.isMergeKey(ctx, key)) merge2.addMergeToJSMap(ctx, map2, value); else { const jsKey = toJS.toJS(key, "", ctx); if (map2 instanceof Map) { map2.set(jsKey, toJS.toJS(value, jsKey, ctx)); } else if (map2 instanceof Set) { map2.add(jsKey); } else { const stringKey = stringifyKey(key, jsKey, ctx); const jsValue = toJS.toJS(value, stringKey, ctx); if (stringKey in map2) Object.defineProperty(map2, stringKey, { value: jsValue, writable: true, enumerable: true, configurable: true }); else map2[stringKey] = jsValue; } } return map2; } function stringifyKey(key, jsKey, ctx) { if (jsKey === null) return ""; if (typeof jsKey !== "object") return String(jsKey); if (identity.isNode(key) && ctx?.doc) { const strCtx = stringify.createStringifyContext(ctx.doc, {}); strCtx.anchors = /* @__PURE__ */ new Set(); for (const node of ctx.anchors.keys()) strCtx.anchors.add(node.anchor); strCtx.inFlow = true; strCtx.inStringifyKey = true; const strKey = key.toString(strCtx); if (!ctx.mapKeyWarned) { let jsonStr = JSON.stringify(strKey); if (jsonStr.length > 40) jsonStr = jsonStr.substring(0, 36) + '..."'; log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); ctx.mapKeyWarned = true; } return strKey; } return JSON.stringify(jsKey); } exports2.addPairToJSMap = addPairToJSMap; } }); // node_modules/yaml/dist/nodes/Pair.js var require_Pair = __commonJS({ "node_modules/yaml/dist/nodes/Pair.js"(exports2) { "use strict"; var createNode = require_createNode(); var stringifyPair = require_stringifyPair(); var addPairToJSMap = require_addPairToJSMap(); var identity = require_identity(); function createPair(key, value, ctx) { const k = createNode.createNode(key, void 0, ctx); const v = createNode.createNode(value, void 0, ctx); return new Pair(k, v); } var Pair = class _Pair { constructor(key, value = null) { Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); this.key = key; this.value = value; } clone(schema) { let { key, value } = this; if (identity.isNode(key)) key = key.clone(schema); if (identity.isNode(value)) value = value.clone(schema); return new _Pair(key, value); } toJSON(_, ctx) { const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; return addPairToJSMap.addPairToJSMap(ctx, pair, this); } toString(ctx, onComment, onChompKeep) { return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); } }; exports2.Pair = Pair; exports2.createPair = createPair; } }); // node_modules/yaml/dist/stringify/stringifyCollection.js var require_stringifyCollection = __commonJS({ "node_modules/yaml/dist/stringify/stringifyCollection.js"(exports2) { "use strict"; var identity = require_identity(); var stringify = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyCollection(collection, ctx, options) { const flow = ctx.inFlow ?? collection.flow; const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection; return stringify2(collection, ctx, options); } function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { const { indent, options: { commentString } } = ctx; const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); let chompKeep = false; const lines = []; for (let i = 0; i < items.length; ++i) { const item = items[i]; let comment2 = null; if (identity.isNode(item)) { if (!chompKeep && item.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, item.commentBefore, chompKeep); if (item.comment) comment2 = item.comment; } else if (identity.isPair(item)) { const ik = identity.isNode(item.key) ? item.key : null; if (ik) { if (!chompKeep && ik.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); } } chompKeep = false; let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); if (comment2) str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2)); if (chompKeep && comment2) chompKeep = false; lines.push(blockItemPrefix + str2); } let str; if (lines.length === 0) { str = flowChars.start + flowChars.end; } else { str = lines[0]; for (let i = 1; i < lines.length; ++i) { const line = lines[i]; str += line ? ` ${indent}${line}` : "\n"; } } if (comment) { str += "\n" + stringifyComment.indentComment(commentString(comment), indent); if (onComment) onComment(); } else if (chompKeep && onChompKeep) onChompKeep(); return str; } function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; itemIndent += indentStep; const itemCtx = Object.assign({}, ctx, { indent: itemIndent, inFlow: true, type: null }); let reqNewline = false; let linesAtValue = 0; const lines = []; for (let i = 0; i < items.length; ++i) { const item = items[i]; let comment = null; if (identity.isNode(item)) { if (item.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, item.commentBefore, false); if (item.comment) comment = item.comment; } else if (identity.isPair(item)) { const ik = identity.isNode(item.key) ? item.key : null; if (ik) { if (ik.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, ik.commentBefore, false); if (ik.comment) reqNewline = true; } const iv = identity.isNode(item.value) ? item.value : null; if (iv) { if (iv.comment) comment = iv.comment; if (iv.commentBefore) reqNewline = true; } else if (item.value == null && ik?.comment) { comment = ik.comment; } } if (comment) reqNewline = true; let str = stringify.stringify(item, itemCtx, () => comment = null); reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n")); if (i < items.length - 1) { str += ","; } else if (ctx.options.trailingComma) { if (ctx.options.lineWidth > 0) { reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); } if (reqNewline) { str += ","; } } if (comment) str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); lines.push(str); linesAtValue = lines.length; } const { start, end } = flowChars; if (lines.length === 0) { return start + end; } else { if (!reqNewline) { const len = lines.reduce((sum, line) => sum + line.length + 2, 2); reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; } if (reqNewline) { let str = start; for (const line of lines) str += line ? ` ${indentStep}${indent}${line}` : "\n"; return `${str} ${indent}${end}`; } else { return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; } } } function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { if (comment && chompKeep) comment = comment.replace(/^\n+/, ""); if (comment) { const ic = stringifyComment.indentComment(commentString(comment), indent); lines.push(ic.trimStart()); } } exports2.stringifyCollection = stringifyCollection; } }); // node_modules/yaml/dist/nodes/YAMLMap.js var require_YAMLMap = __commonJS({ "node_modules/yaml/dist/nodes/YAMLMap.js"(exports2) { "use strict"; var stringifyCollection = require_stringifyCollection(); var addPairToJSMap = require_addPairToJSMap(); var Collection = require_Collection(); var identity = require_identity(); var Pair = require_Pair(); var Scalar = require_Scalar(); function findPair(items, key) { const k = identity.isScalar(key) ? key.value : key; for (const it of items) { if (identity.isPair(it)) { if (it.key === key || it.key === k) return it; if (identity.isScalar(it.key) && it.key.value === k) return it; } } return void 0; } var YAMLMap = class extends Collection.Collection { static get tagName() { return "tag:yaml.org,2002:map"; } constructor(schema) { super(identity.MAP, schema); this.items = []; } /** * A generic collection parsing method that can be extended * to other node classes that inherit from YAMLMap */ static from(schema, obj, ctx) { const { keepUndefined, replacer } = ctx; const map2 = new this(schema); const add = (key, value) => { if (typeof replacer === "function") value = replacer.call(obj, key, value); else if (Array.isArray(replacer) && !replacer.includes(key)) return; if (value !== void 0 || keepUndefined) map2.items.push(Pair.createPair(key, value, ctx)); }; if (obj instanceof Map) { for (const [key, value] of obj) add(key, value); } else if (obj && typeof obj === "object") { for (const key of Object.keys(obj)) add(key, obj[key]); } if (typeof schema.sortMapEntries === "function") { map2.items.sort(schema.sortMapEntries); } return map2; } /** * Adds a value to the collection. * * @param overwrite - If not set `true`, using a key that is already in the * collection will throw. Otherwise, overwrites the previous value. */ add(pair, overwrite) { let _pair; if (identity.isPair(pair)) _pair = pair; else if (!pair || typeof pair !== "object" || !("key" in pair)) { _pair = new Pair.Pair(pair, pair?.value); } else _pair = new Pair.Pair(pair.key, pair.value); const prev = findPair(this.items, _pair.key); const sortEntries = this.schema?.sortMapEntries; if (prev) { if (!overwrite) throw new Error(`Key ${_pair.key} already set`); if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) prev.value.value = _pair.value; else prev.value = _pair.value; } else if (sortEntries) { const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); if (i === -1) this.items.push(_pair); else this.items.splice(i, 0, _pair); } else { this.items.push(_pair); } } delete(key) { const it = findPair(this.items, key); if (!it) return false; const del = this.items.splice(this.items.indexOf(it), 1); return del.length > 0; } get(key, keepScalar) { const it = findPair(this.items, key); const node = it?.value; return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0; } has(key) { return !!findPair(this.items, key); } set(key, value) { this.add(new Pair.Pair(key, value), true); } /** * @param ctx - Conversion context, originally set in Document#toJS() * @param {Class} Type - If set, forces the returned collection type * @returns Instance of Type, Map, or Object */ toJSON(_, ctx, Type) { const map2 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; if (ctx?.onCreate) ctx.onCreate(map2); for (const item of this.items) addPairToJSMap.addPairToJSMap(ctx, map2, item); return map2; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); for (const item of this.items) { if (!identity.isPair(item)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); } if (!ctx.allNullValues && this.hasAllNullValues(false)) ctx = Object.assign({}, ctx, { allNullValues: true }); return stringifyCollection.stringifyCollection(this, ctx, { blockItemPrefix: "", flowChars: { start: "{", end: "}" }, itemIndent: ctx.indent || "", onChompKeep, onComment }); } }; exports2.YAMLMap = YAMLMap; exports2.findPair = findPair; } }); // node_modules/yaml/dist/schema/common/map.js var require_map = __commonJS({ "node_modules/yaml/dist/schema/common/map.js"(exports2) { "use strict"; var identity = require_identity(); var YAMLMap = require_YAMLMap(); var map2 = { collection: "map", default: true, nodeClass: YAMLMap.YAMLMap, tag: "tag:yaml.org,2002:map", resolve(map3, onError) { if (!identity.isMap(map3)) onError("Expected a mapping for this tag"); return map3; }, createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) }; exports2.map = map2; } }); // node_modules/yaml/dist/nodes/YAMLSeq.js var require_YAMLSeq = __commonJS({ "node_modules/yaml/dist/nodes/YAMLSeq.js"(exports2) { "use strict"; var createNode = require_createNode(); var stringifyCollection = require_stringifyCollection(); var Collection = require_Collection(); var identity = require_identity(); var Scalar = require_Scalar(); var toJS = require_toJS(); var YAMLSeq = class extends Collection.Collection { static get tagName() { return "tag:yaml.org,2002:seq"; } constructor(schema) { super(identity.SEQ, schema); this.items = []; } add(value) { this.items.push(value); } /** * Removes a value from the collection. * * `key` must contain a representation of an integer for this to succeed. * It may be wrapped in a `Scalar`. * * @returns `true` if the item was found and removed. */ delete(key) { const idx = asItemIndex(key); if (typeof idx !== "number") return false; const del = this.items.splice(idx, 1); return del.length > 0; } get(key, keepScalar) { const idx = asItemIndex(key); if (typeof idx !== "number") return void 0; const it = this.items[idx]; return !keepScalar && identity.isScalar(it) ? it.value : it; } /** * Checks if the collection includes a value with the key `key`. * * `key` must contain a representation of an integer for this to succeed. * It may be wrapped in a `Scalar`. */ has(key) { const idx = asItemIndex(key); return typeof idx === "number" && idx < this.items.length; } /** * Sets a value in this collection. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. * * If `key` does not contain a representation of an integer, this will throw. * It may be wrapped in a `Scalar`. */ set(key, value) { const idx = asItemIndex(key); if (typeof idx !== "number") throw new Error(`Expected a valid index, not ${key}.`); const prev = this.items[idx]; if (identity.isScalar(prev) && Scalar.isScalarValue(value)) prev.value = value; else this.items[idx] = value; } toJSON(_, ctx) { const seq = []; if (ctx?.onCreate) ctx.onCreate(seq); let i = 0; for (const item of this.items) seq.push(toJS.toJS(item, String(i++), ctx)); return seq; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); return stringifyCollection.stringifyCollection(this, ctx, { blockItemPrefix: "- ", flowChars: { start: "[", end: "]" }, itemIndent: (ctx.indent || "") + " ", onChompKeep, onComment }); } static from(schema, obj, ctx) { const { replacer } = ctx; const seq = new this(schema); if (obj && Symbol.iterator in Object(obj)) { let i = 0; for (let it of obj) { if (typeof replacer === "function") { const key = obj instanceof Set ? it : String(i++); it = replacer.call(obj, key, it); } seq.items.push(createNode.createNode(it, void 0, ctx)); } } return seq; } }; function asItemIndex(key) { let idx = identity.isScalar(key) ? key.value : key; if (idx && typeof idx === "string") idx = Number(idx); return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; } exports2.YAMLSeq = YAMLSeq; } }); // node_modules/yaml/dist/schema/common/seq.js var require_seq = __commonJS({ "node_modules/yaml/dist/schema/common/seq.js"(exports2) { "use strict"; var identity = require_identity(); var YAMLSeq = require_YAMLSeq(); var seq = { collection: "seq", default: true, nodeClass: YAMLSeq.YAMLSeq, tag: "tag:yaml.org,2002:seq", resolve(seq2, onError) { if (!identity.isSeq(seq2)) onError("Expected a sequence for this tag"); return seq2; }, createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) }; exports2.seq = seq; } }); // node_modules/yaml/dist/schema/common/string.js var require_string = __commonJS({ "node_modules/yaml/dist/schema/common/string.js"(exports2) { "use strict"; var stringifyString = require_stringifyString(); var string4 = { identify: (value) => typeof value === "string", default: true, tag: "tag:yaml.org,2002:str", resolve: (str) => str, stringify(item, ctx, onComment, onChompKeep) { ctx = Object.assign({ actualString: true }, ctx); return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); } }; exports2.string = string4; } }); // node_modules/yaml/dist/schema/common/null.js var require_null = __commonJS({ "node_modules/yaml/dist/schema/common/null.js"(exports2) { "use strict"; var Scalar = require_Scalar(); var nullTag = { identify: (value) => value == null, createNode: () => new Scalar.Scalar(null), default: true, tag: "tag:yaml.org,2002:null", test: /^(?:~|[Nn]ull|NULL)?$/, resolve: () => new Scalar.Scalar(null), stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr }; exports2.nullTag = nullTag; } }); // node_modules/yaml/dist/schema/core/bool.js var require_bool = __commonJS({ "node_modules/yaml/dist/schema/core/bool.js"(exports2) { "use strict"; var Scalar = require_Scalar(); var boolTag = { identify: (value) => typeof value === "boolean", default: true, tag: "tag:yaml.org,2002:bool", test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"), stringify({ source, value }, ctx) { if (source && boolTag.test.test(source)) { const sv = source[0] === "t" || source[0] === "T"; if (value === sv) return source; } return value ? ctx.options.trueStr : ctx.options.falseStr; } }; exports2.boolTag = boolTag; } }); // node_modules/yaml/dist/stringify/stringifyNumber.js var require_stringifyNumber = __commonJS({ "node_modules/yaml/dist/stringify/stringifyNumber.js"(exports2) { "use strict"; function stringifyNumber({ format, minFractionDigits, tag, value }) { if (typeof value === "bigint") return String(value); const num = typeof value === "number" ? value : Number(value); if (!isFinite(num)) return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; let n = Object.is(value, -0) ? "-0" : JSON.stringify(value); if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) { let i = n.indexOf("."); if (i < 0) { i = n.length; n += "."; } let d = minFractionDigits - (n.length - i - 1); while (d-- > 0) n += "0"; } return n; } exports2.stringifyNumber = stringifyNumber; } }); // node_modules/yaml/dist/schema/core/float.js var require_float = __commonJS({ "node_modules/yaml/dist/schema/core/float.js"(exports2) { "use strict"; var Scalar = require_Scalar(); var stringifyNumber = require_stringifyNumber(); var floatNaN = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: stringifyNumber.stringifyNumber }; var floatExp = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", format: "EXP", test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, resolve: (str) => parseFloat(str), stringify(node) { const num = Number(node.value); return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); } }; var float = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, resolve(str) { const node = new Scalar.Scalar(parseFloat(str)); const dot = str.indexOf("."); if (dot !== -1 && str[str.length - 1] === "0") node.minFractionDigits = str.length - dot - 1; return node; }, stringify: stringifyNumber.stringifyNumber }; exports2.float = float; exports2.floatExp = floatExp; exports2.floatNaN = floatNaN; } }); // node_modules/yaml/dist/schema/core/int.js var require_int = __commonJS({ "node_modules/yaml/dist/schema/core/int.js"(exports2) { "use strict"; var stringifyNumber = require_stringifyNumber(); var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); function intStringify(node, radix, prefix) { const { value } = node; if (intIdentify(value) && value >= 0) return prefix + value.toString(radix); return stringifyNumber.stringifyNumber(node); } var intOct = { identify: (value) => intIdentify(value) && value >= 0, default: true, tag: "tag:yaml.org,2002:int", format: "OCT", test: /^0o[0-7]+$/, resolve: (str, _onError2, opt) => intResolve(str, 2, 8, opt), stringify: (node) => intStringify(node, 8, "0o") }; var int2 = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", test: /^[-+]?[0-9]+$/, resolve: (str, _onError2, opt) => intResolve(str, 0, 10, opt), stringify: stringifyNumber.stringifyNumber }; var intHex = { identify: (value) => intIdentify(value) && value >= 0, default: true, tag: "tag:yaml.org,2002:int", format: "HEX", test: /^0x[0-9a-fA-F]+$/, resolve: (str, _onError2, opt) => intResolve(str, 2, 16, opt), stringify: (node) => intStringify(node, 16, "0x") }; exports2.int = int2; exports2.intHex = intHex; exports2.intOct = intOct; } }); // node_modules/yaml/dist/schema/core/schema.js var require_schema = __commonJS({ "node_modules/yaml/dist/schema/core/schema.js"(exports2) { "use strict"; var map2 = require_map(); var _null4 = require_null(); var seq = require_seq(); var string4 = require_string(); var bool = require_bool(); var float = require_float(); var int2 = require_int(); var schema = [ map2.map, seq.seq, string4.string, _null4.nullTag, bool.boolTag, int2.intOct, int2.int, int2.intHex, float.floatNaN, float.floatExp, float.float ]; exports2.schema = schema; } }); // node_modules/yaml/dist/schema/json/schema.js var require_schema2 = __commonJS({ "node_modules/yaml/dist/schema/json/schema.js"(exports2) { "use strict"; var Scalar = require_Scalar(); var map2 = require_map(); var seq = require_seq(); function intIdentify(value) { return typeof value === "bigint" || Number.isInteger(value); } var stringifyJSON = ({ value }) => JSON.stringify(value); var jsonScalars = [ { identify: (value) => typeof value === "string", default: true, tag: "tag:yaml.org,2002:str", resolve: (str) => str, stringify: stringifyJSON }, { identify: (value) => value == null, createNode: () => new Scalar.Scalar(null), default: true, tag: "tag:yaml.org,2002:null", test: /^null$/, resolve: () => null, stringify: stringifyJSON }, { identify: (value) => typeof value === "boolean", default: true, tag: "tag:yaml.org,2002:bool", test: /^true$|^false$/, resolve: (str) => str === "true", stringify: stringifyJSON }, { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", test: /^-?(?:0|[1-9][0-9]*)$/, resolve: (str, _onError2, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) }, { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, resolve: (str) => parseFloat(str), stringify: stringifyJSON } ]; var jsonError = { default: true, tag: "", test: /^/, resolve(str, onError) { onError(`Unresolved plain scalar ${JSON.stringify(str)}`); return str; } }; var schema = [map2.map, seq.seq].concat(jsonScalars, jsonError); exports2.schema = schema; } }); // node_modules/yaml/dist/schema/yaml-1.1/binary.js var require_binary = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/binary.js"(exports2) { "use strict"; var node_buffer = require("buffer"); var Scalar = require_Scalar(); var stringifyString = require_stringifyString(); var binary = { identify: (value) => value instanceof Uint8Array, // Buffer inherits from Uint8Array default: false, tag: "tag:yaml.org,2002:binary", /** * Returns a Buffer in node and an Uint8Array in browsers * * To use the resulting buffer as an image, you'll want to do something like: * * const blob = new Blob([buffer], { type: 'image/jpeg' }) * document.querySelector('#photo').src = URL.createObjectURL(blob) */ resolve(src, onError) { if (typeof node_buffer.Buffer === "function") { return node_buffer.Buffer.from(src, "base64"); } else if (typeof atob === "function") { const str = atob(src.replace(/[\n\r]/g, "")); const buffer = new Uint8Array(str.length); for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); return buffer; } else { onError("This environment does not support reading binary tags; either Buffer or atob is required"); return src; } }, stringify({ comment, type, value }, ctx, onComment, onChompKeep) { if (!value) return ""; const buf = value; let str; if (typeof node_buffer.Buffer === "function") { str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); } else if (typeof btoa === "function") { let s = ""; for (let i = 0; i < buf.length; ++i) s += String.fromCharCode(buf[i]); str = btoa(s); } else { throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); } type ?? (type = Scalar.Scalar.BLOCK_LITERAL); if (type !== Scalar.Scalar.QUOTE_DOUBLE) { const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); const n = Math.ceil(str.length / lineWidth); const lines = new Array(n); for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { lines[i] = str.substr(o, lineWidth); } str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " "); } return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); } }; exports2.binary = binary; } }); // node_modules/yaml/dist/schema/yaml-1.1/pairs.js var require_pairs = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(exports2) { "use strict"; var identity = require_identity(); var Pair = require_Pair(); var Scalar = require_Scalar(); var YAMLSeq = require_YAMLSeq(); function resolvePairs(seq, onError) { if (identity.isSeq(seq)) { for (let i = 0; i < seq.items.length; ++i) { let item = seq.items[i]; if (identity.isPair(item)) continue; else if (identity.isMap(item)) { if (item.items.length > 1) onError("Each pair must have its own sequence indicator"); const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); if (item.commentBefore) pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} ${pair.key.commentBefore}` : item.commentBefore; if (item.comment) { const cn = pair.value ?? pair.key; cn.comment = cn.comment ? `${item.comment} ${cn.comment}` : item.comment; } item = pair; } seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); } } else onError("Expected a sequence for this tag"); return seq; } function createPairs(schema, iterable, ctx) { const { replacer } = ctx; const pairs2 = new YAMLSeq.YAMLSeq(schema); pairs2.tag = "tag:yaml.org,2002:pairs"; let i = 0; if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable) { if (typeof replacer === "function") it = replacer.call(iterable, String(i++), it); let key, value; if (Array.isArray(it)) { if (it.length === 2) { key = it[0]; value = it[1]; } else throw new TypeError(`Expected [key, value] tuple: ${it}`); } else if (it && it instanceof Object) { const keys = Object.keys(it); if (keys.length === 1) { key = keys[0]; value = it[key]; } else { throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); } } else { key = it; } pairs2.items.push(Pair.createPair(key, value, ctx)); } return pairs2; } var pairs = { collection: "seq", default: false, tag: "tag:yaml.org,2002:pairs", resolve: resolvePairs, createNode: createPairs }; exports2.createPairs = createPairs; exports2.pairs = pairs; exports2.resolvePairs = resolvePairs; } }); // node_modules/yaml/dist/schema/yaml-1.1/omap.js var require_omap = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports2) { "use strict"; var identity = require_identity(); var toJS = require_toJS(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var pairs = require_pairs(); var YAMLOMap = class _YAMLOMap extends YAMLSeq.YAMLSeq { constructor() { super(); this.add = YAMLMap.YAMLMap.prototype.add.bind(this); this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); this.get = YAMLMap.YAMLMap.prototype.get.bind(this); this.has = YAMLMap.YAMLMap.prototype.has.bind(this); this.set = YAMLMap.YAMLMap.prototype.set.bind(this); this.tag = _YAMLOMap.tag; } /** * If `ctx` is given, the return type is actually `Map`, * but TypeScript won't allow widening the signature of a child method. */ toJSON(_, ctx) { if (!ctx) return super.toJSON(_); const map2 = /* @__PURE__ */ new Map(); if (ctx?.onCreate) ctx.onCreate(map2); for (const pair of this.items) { let key, value; if (identity.isPair(pair)) { key = toJS.toJS(pair.key, "", ctx); value = toJS.toJS(pair.value, key, ctx); } else { key = toJS.toJS(pair, "", ctx); } if (map2.has(key)) throw new Error("Ordered maps must not include duplicate keys"); map2.set(key, value); } return map2; } static from(schema, iterable, ctx) { const pairs$1 = pairs.createPairs(schema, iterable, ctx); const omap2 = new this(); omap2.items = pairs$1.items; return omap2; } }; YAMLOMap.tag = "tag:yaml.org,2002:omap"; var omap = { collection: "seq", identify: (value) => value instanceof Map, nodeClass: YAMLOMap, default: false, tag: "tag:yaml.org,2002:omap", resolve(seq, onError) { const pairs$1 = pairs.resolvePairs(seq, onError); const seenKeys = []; for (const { key } of pairs$1.items) { if (identity.isScalar(key)) { if (seenKeys.includes(key.value)) { onError(`Ordered maps must not include duplicate keys: ${key.value}`); } else { seenKeys.push(key.value); } } } return Object.assign(new YAMLOMap(), pairs$1); }, createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) }; exports2.YAMLOMap = YAMLOMap; exports2.omap = omap; } }); // node_modules/yaml/dist/schema/yaml-1.1/bool.js var require_bool2 = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports2) { "use strict"; var Scalar = require_Scalar(); function boolStringify({ value, source }, ctx) { const boolObj = value ? trueTag : falseTag; if (source && boolObj.test.test(source)) return source; return value ? ctx.options.trueStr : ctx.options.falseStr; } var trueTag = { identify: (value) => value === true, default: true, tag: "tag:yaml.org,2002:bool", test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, resolve: () => new Scalar.Scalar(true), stringify: boolStringify }; var falseTag = { identify: (value) => value === false, default: true, tag: "tag:yaml.org,2002:bool", test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, resolve: () => new Scalar.Scalar(false), stringify: boolStringify }; exports2.falseTag = falseTag; exports2.trueTag = trueTag; } }); // node_modules/yaml/dist/schema/yaml-1.1/float.js var require_float2 = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports2) { "use strict"; var Scalar = require_Scalar(); var stringifyNumber = require_stringifyNumber(); var floatNaN = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: stringifyNumber.stringifyNumber }; var floatExp = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", format: "EXP", test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, resolve: (str) => parseFloat(str.replace(/_/g, "")), stringify(node) { const num = Number(node.value); return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); } }; var float = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, resolve(str) { const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ""))); const dot = str.indexOf("."); if (dot !== -1) { const f = str.substring(dot + 1).replace(/_/g, ""); if (f[f.length - 1] === "0") node.minFractionDigits = f.length; } return node; }, stringify: stringifyNumber.stringifyNumber }; exports2.float = float; exports2.floatExp = floatExp; exports2.floatNaN = floatNaN; } }); // node_modules/yaml/dist/schema/yaml-1.1/int.js var require_int2 = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports2) { "use strict"; var stringifyNumber = require_stringifyNumber(); var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); function intResolve(str, offset, radix, { intAsBigInt }) { const sign = str[0]; if (sign === "-" || sign === "+") offset += 1; str = str.substring(offset).replace(/_/g, ""); if (intAsBigInt) { switch (radix) { case 2: str = `0b${str}`; break; case 8: str = `0o${str}`; break; case 16: str = `0x${str}`; break; } const n2 = BigInt(str); return sign === "-" ? BigInt(-1) * n2 : n2; } const n = parseInt(str, radix); return sign === "-" ? -1 * n : n; } function intStringify(node, radix, prefix) { const { value } = node; if (intIdentify(value)) { const str = value.toString(radix); return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; } return stringifyNumber.stringifyNumber(node); } var intBin = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", format: "BIN", test: /^[-+]?0b[0-1_]+$/, resolve: (str, _onError2, opt) => intResolve(str, 2, 2, opt), stringify: (node) => intStringify(node, 2, "0b") }; var intOct = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", format: "OCT", test: /^[-+]?0[0-7_]+$/, resolve: (str, _onError2, opt) => intResolve(str, 1, 8, opt), stringify: (node) => intStringify(node, 8, "0") }; var int2 = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", test: /^[-+]?[0-9][0-9_]*$/, resolve: (str, _onError2, opt) => intResolve(str, 0, 10, opt), stringify: stringifyNumber.stringifyNumber }; var intHex = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", format: "HEX", test: /^[-+]?0x[0-9a-fA-F_]+$/, resolve: (str, _onError2, opt) => intResolve(str, 2, 16, opt), stringify: (node) => intStringify(node, 16, "0x") }; exports2.int = int2; exports2.intBin = intBin; exports2.intHex = intHex; exports2.intOct = intOct; } }); // node_modules/yaml/dist/schema/yaml-1.1/set.js var require_set = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports2) { "use strict"; var identity = require_identity(); var Pair = require_Pair(); var YAMLMap = require_YAMLMap(); var YAMLSet = class _YAMLSet extends YAMLMap.YAMLMap { constructor(schema) { super(schema); this.tag = _YAMLSet.tag; } add(key) { let pair; if (identity.isPair(key)) pair = key; else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) pair = new Pair.Pair(key.key, null); else pair = new Pair.Pair(key, null); const prev = YAMLMap.findPair(this.items, pair.key); if (!prev) this.items.push(pair); } /** * If `keepPair` is `true`, returns the Pair matching `key`. * Otherwise, returns the value of that Pair's key. */ get(key, keepPair) { const pair = YAMLMap.findPair(this.items, key); return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair; } set(key, value) { if (typeof value !== "boolean") throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); const prev = YAMLMap.findPair(this.items, key); if (prev && !value) { this.items.splice(this.items.indexOf(prev), 1); } else if (!prev && value) { this.items.push(new Pair.Pair(key)); } } toJSON(_, ctx) { return super.toJSON(_, ctx, Set); } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); if (this.hasAllNullValues(true)) return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); else throw new Error("Set items must all have null values"); } static from(schema, iterable, ctx) { const { replacer } = ctx; const set3 = new this(schema); if (iterable && Symbol.iterator in Object(iterable)) for (let value of iterable) { if (typeof replacer === "function") value = replacer.call(iterable, value, value); set3.items.push(Pair.createPair(value, null, ctx)); } return set3; } }; YAMLSet.tag = "tag:yaml.org,2002:set"; var set2 = { collection: "map", identify: (value) => value instanceof Set, nodeClass: YAMLSet, default: false, tag: "tag:yaml.org,2002:set", createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), resolve(map2, onError) { if (identity.isMap(map2)) { if (map2.hasAllNullValues(true)) return Object.assign(new YAMLSet(), map2); else onError("Set items must all have null values"); } else onError("Expected a mapping for this tag"); return map2; } }; exports2.YAMLSet = YAMLSet; exports2.set = set2; } }); // node_modules/yaml/dist/schema/yaml-1.1/timestamp.js var require_timestamp = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports2) { "use strict"; var stringifyNumber = require_stringifyNumber(); function parseSexagesimal(str, asBigInt) { const sign = str[0]; const parts = sign === "-" || sign === "+" ? str.substring(1) : str; const num = (n) => asBigInt ? BigInt(n) : Number(n); const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); return sign === "-" ? num(-1) * res : res; } function stringifySexagesimal(node) { let { value } = node; let num = (n) => n; if (typeof value === "bigint") num = (n) => BigInt(n); else if (isNaN(value) || !isFinite(value)) return stringifyNumber.stringifyNumber(node); let sign = ""; if (value < 0) { sign = "-"; value *= num(-1); } const _60 = num(60); const parts = [value % _60]; if (value < 60) { parts.unshift(0); } else { value = (value - parts[0]) / _60; parts.unshift(value % _60); if (value >= 60) { value = (value - parts[0]) / _60; parts.unshift(value); } } return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); } var intTime = { identify: (value) => typeof value === "bigint" || Number.isInteger(value), default: true, tag: "tag:yaml.org,2002:int", format: "TIME", test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, resolve: (str, _onError2, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), stringify: stringifySexagesimal }; var floatTime = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", format: "TIME", test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, resolve: (str) => parseSexagesimal(str, false), stringify: stringifySexagesimal }; var timestamp = { identify: (value) => value instanceof Date, default: true, tag: "tag:yaml.org,2002:timestamp", // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part // may be omitted altogether, resulting in a date format. In such a case, the time part is // assumed to be 00:00:00Z (start of day, UTC). test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), resolve(str) { const match = str.match(timestamp.test); if (!match) throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); const [, year, month, day, hour, minute, second] = match.map(Number); const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; let date5 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); const tz = match[8]; if (tz && tz !== "Z") { let d = parseSexagesimal(tz, false); if (Math.abs(d) < 30) d *= 60; date5 -= 6e4 * d; } return new Date(date5); }, stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" }; exports2.floatTime = floatTime; exports2.intTime = intTime; exports2.timestamp = timestamp; } }); // node_modules/yaml/dist/schema/yaml-1.1/schema.js var require_schema3 = __commonJS({ "node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports2) { "use strict"; var map2 = require_map(); var _null4 = require_null(); var seq = require_seq(); var string4 = require_string(); var binary = require_binary(); var bool = require_bool2(); var float = require_float2(); var int2 = require_int2(); var merge2 = require_merge(); var omap = require_omap(); var pairs = require_pairs(); var set2 = require_set(); var timestamp = require_timestamp(); var schema = [ map2.map, seq.seq, string4.string, _null4.nullTag, bool.trueTag, bool.falseTag, int2.intBin, int2.intOct, int2.int, int2.intHex, float.floatNaN, float.floatExp, float.float, binary.binary, merge2.merge, omap.omap, pairs.pairs, set2.set, timestamp.intTime, timestamp.floatTime, timestamp.timestamp ]; exports2.schema = schema; } }); // node_modules/yaml/dist/schema/tags.js var require_tags = __commonJS({ "node_modules/yaml/dist/schema/tags.js"(exports2) { "use strict"; var map2 = require_map(); var _null4 = require_null(); var seq = require_seq(); var string4 = require_string(); var bool = require_bool(); var float = require_float(); var int2 = require_int(); var schema = require_schema(); var schema$1 = require_schema2(); var binary = require_binary(); var merge2 = require_merge(); var omap = require_omap(); var pairs = require_pairs(); var schema$2 = require_schema3(); var set2 = require_set(); var timestamp = require_timestamp(); var schemas = /* @__PURE__ */ new Map([ ["core", schema.schema], ["failsafe", [map2.map, seq.seq, string4.string]], ["json", schema$1.schema], ["yaml11", schema$2.schema], ["yaml-1.1", schema$2.schema] ]); var tagsByName = { binary: binary.binary, bool: bool.boolTag, float: float.float, floatExp: float.floatExp, floatNaN: float.floatNaN, floatTime: timestamp.floatTime, int: int2.int, intHex: int2.intHex, intOct: int2.intOct, intTime: timestamp.intTime, map: map2.map, merge: merge2.merge, null: _null4.nullTag, omap: omap.omap, pairs: pairs.pairs, seq: seq.seq, set: set2.set, timestamp: timestamp.timestamp }; var coreKnownTags = { "tag:yaml.org,2002:binary": binary.binary, "tag:yaml.org,2002:merge": merge2.merge, "tag:yaml.org,2002:omap": omap.omap, "tag:yaml.org,2002:pairs": pairs.pairs, "tag:yaml.org,2002:set": set2.set, "tag:yaml.org,2002:timestamp": timestamp.timestamp }; function getTags(customTags, schemaName, addMergeTag) { const schemaTags = schemas.get(schemaName); if (schemaTags && !customTags) { return addMergeTag && !schemaTags.includes(merge2.merge) ? schemaTags.concat(merge2.merge) : schemaTags.slice(); } let tags = schemaTags; if (!tags) { if (Array.isArray(customTags)) tags = []; else { const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); } } if (Array.isArray(customTags)) { for (const tag of customTags) tags = tags.concat(tag); } else if (typeof customTags === "function") { tags = customTags(tags.slice()); } if (addMergeTag) tags = tags.concat(merge2.merge); return tags.reduce((tags2, tag) => { const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; if (!tagObj) { const tagName = JSON.stringify(tag); const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); } if (!tags2.includes(tagObj)) tags2.push(tagObj); return tags2; }, []); } exports2.coreKnownTags = coreKnownTags; exports2.getTags = getTags; } }); // node_modules/yaml/dist/schema/Schema.js var require_Schema = __commonJS({ "node_modules/yaml/dist/schema/Schema.js"(exports2) { "use strict"; var identity = require_identity(); var map2 = require_map(); var seq = require_seq(); var string4 = require_string(); var tags = require_tags(); var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; var Schema = class _Schema { constructor({ compat, customTags, merge: merge2, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null; this.name = typeof schema === "string" && schema || "core"; this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; this.tags = tags.getTags(customTags, this.name, merge2); this.toStringOptions = toStringDefaults ?? null; Object.defineProperty(this, identity.MAP, { value: map2.map }); Object.defineProperty(this, identity.SCALAR, { value: string4.string }); Object.defineProperty(this, identity.SEQ, { value: seq.seq }); this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; } clone() { const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); copy.tags = this.tags.slice(); return copy; } }; exports2.Schema = Schema; } }); // node_modules/yaml/dist/stringify/stringifyDocument.js var require_stringifyDocument = __commonJS({ "node_modules/yaml/dist/stringify/stringifyDocument.js"(exports2) { "use strict"; var identity = require_identity(); var stringify = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyDocument(doc, options) { const lines = []; let hasDirectives = options.directives === true; if (options.directives !== false && doc.directives) { const dir = doc.directives.toString(doc); if (dir) { lines.push(dir); hasDirectives = true; } else if (doc.directives.docStart) hasDirectives = true; } if (hasDirectives) lines.push("---"); const ctx = stringify.createStringifyContext(doc, options); const { commentString } = ctx.options; if (doc.commentBefore) { if (lines.length !== 1) lines.unshift(""); const cs = commentString(doc.commentBefore); lines.unshift(stringifyComment.indentComment(cs, "")); } let chompKeep = false; let contentComment = null; if (doc.contents) { if (identity.isNode(doc.contents)) { if (doc.contents.spaceBefore && hasDirectives) lines.push(""); if (doc.contents.commentBefore) { const cs = commentString(doc.contents.commentBefore); lines.push(stringifyComment.indentComment(cs, "")); } ctx.forceBlockIndent = !!doc.comment; contentComment = doc.contents.comment; } const onChompKeep = contentComment ? void 0 : () => chompKeep = true; let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); if (contentComment) body += stringifyComment.lineComment(body, "", commentString(contentComment)); if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { lines[lines.length - 1] = `--- ${body}`; } else lines.push(body); } else { lines.push(stringify.stringify(doc.contents, ctx)); } if (doc.directives?.docEnd) { if (doc.comment) { const cs = commentString(doc.comment); if (cs.includes("\n")) { lines.push("..."); lines.push(stringifyComment.indentComment(cs, "")); } else { lines.push(`... ${cs}`); } } else { lines.push("..."); } } else { let dc = doc.comment; if (dc && chompKeep) dc = dc.replace(/^\n+/, ""); if (dc) { if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") lines.push(""); lines.push(stringifyComment.indentComment(commentString(dc), "")); } } return lines.join("\n") + "\n"; } exports2.stringifyDocument = stringifyDocument; } }); // node_modules/yaml/dist/doc/Document.js var require_Document = __commonJS({ "node_modules/yaml/dist/doc/Document.js"(exports2) { "use strict"; var Alias = require_Alias(); var Collection = require_Collection(); var identity = require_identity(); var Pair = require_Pair(); var toJS = require_toJS(); var Schema = require_Schema(); var stringifyDocument = require_stringifyDocument(); var anchors = require_anchors(); var applyReviver = require_applyReviver(); var createNode = require_createNode(); var directives = require_directives(); var Document = class _Document { constructor(value, replacer, options) { this.commentBefore = null; this.comment = null; this.errors = []; this.warnings = []; Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); let _replacer = null; if (typeof replacer === "function" || Array.isArray(replacer)) { _replacer = replacer; } else if (options === void 0 && replacer) { options = replacer; replacer = void 0; } const opt = Object.assign({ intAsBigInt: false, keepSourceTokens: false, logLevel: "warn", prettyErrors: true, strict: true, stringKeys: false, uniqueKeys: true, version: "1.2" }, options); this.options = opt; let { version: version2 } = opt; if (options?._directives) { this.directives = options._directives.atDocument(); if (this.directives.yaml.explicit) version2 = this.directives.yaml.version; } else this.directives = new directives.Directives({ version: version2 }); this.setSchema(version2, options); this.contents = value === void 0 ? null : this.createNode(value, _replacer, options); } /** * Create a deep copy of this Document and its contents. * * Custom Node values that inherit from `Object` still refer to their original instances. */ clone() { const copy = Object.create(_Document.prototype, { [identity.NODE_TYPE]: { value: identity.DOC } }); copy.commentBefore = this.commentBefore; copy.comment = this.comment; copy.errors = this.errors.slice(); copy.warnings = this.warnings.slice(); copy.options = Object.assign({}, this.options); if (this.directives) copy.directives = this.directives.clone(); copy.schema = this.schema.clone(); copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; if (this.range) copy.range = this.range.slice(); return copy; } /** Adds a value to the document. */ add(value) { if (assertCollection(this.contents)) this.contents.add(value); } /** Adds a value to the document. */ addIn(path, value) { if (assertCollection(this.contents)) this.contents.addIn(path, value); } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. * * If `node` already has an anchor, `name` is ignored. * Otherwise, the `node.anchor` value will be set to `name`, * or if an anchor with that name is already present in the document, * `name` will be used as a prefix for a new unique anchor. * If `name` is undefined, the generated anchor will use 'a' as a prefix. */ createAlias(node, name) { if (!node.anchor) { const prev = anchors.anchorNames(this); node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; } return new Alias.Alias(node.anchor); } createNode(value, replacer, options) { let _replacer = void 0; if (typeof replacer === "function") { value = replacer.call({ "": value }, "", value); _replacer = replacer; } else if (Array.isArray(replacer)) { const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; const asStr = replacer.filter(keyToStr).map(String); if (asStr.length > 0) replacer = replacer.concat(asStr); _replacer = replacer; } else if (options === void 0 && replacer) { options = replacer; replacer = void 0; } const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors( this, // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing anchorPrefix || "a" ); const ctx = { aliasDuplicateObjects: aliasDuplicateObjects ?? true, keepUndefined: keepUndefined ?? false, onAnchor, onTagObj, replacer: _replacer, schema: this.schema, sourceObjects }; const node = createNode.createNode(value, tag, ctx); if (flow && identity.isCollection(node)) node.flow = true; setAnchors(); return node; } /** * Convert a key and a value into a `Pair` using the current schema, * recursively wrapping all values as `Scalar` or `Collection` nodes. */ createPair(key, value, options = {}) { const k = this.createNode(key, null, options); const v = this.createNode(value, null, options); return new Pair.Pair(k, v); } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ delete(key) { return assertCollection(this.contents) ? this.contents.delete(key) : false; } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ deleteIn(path) { if (Collection.isEmptyPath(path)) { if (this.contents == null) return false; this.contents = null; return true; } return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ get(key, keepScalar) { return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; } /** * Returns item at `path`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path, keepScalar) { if (Collection.isEmptyPath(path)) return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; } /** * Checks if the document includes a value with the key `key`. */ has(key) { return identity.isCollection(this.contents) ? this.contents.has(key) : false; } /** * Checks if the document includes a value at `path`. */ hasIn(path) { if (Collection.isEmptyPath(path)) return this.contents !== void 0; return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false; } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ set(key, value) { if (this.contents == null) { this.contents = Collection.collectionFromPath(this.schema, [key], value); } else if (assertCollection(this.contents)) { this.contents.set(key, value); } } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path, value) { if (Collection.isEmptyPath(path)) { this.contents = value; } else if (this.contents == null) { this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value); } else if (assertCollection(this.contents)) { this.contents.setIn(path, value); } } /** * Change the YAML version and schema used by the document. * A `null` version disables support for directives, explicit tags, anchors, and aliases. * It also requires the `schema` option to be given as a `Schema` instance value. * * Overrides all previously set schema options. */ setSchema(version2, options = {}) { if (typeof version2 === "number") version2 = String(version2); let opt; switch (version2) { case "1.1": if (this.directives) this.directives.yaml.version = "1.1"; else this.directives = new directives.Directives({ version: "1.1" }); opt = { resolveKnownTags: false, schema: "yaml-1.1" }; break; case "1.2": case "next": if (this.directives) this.directives.yaml.version = version2; else this.directives = new directives.Directives({ version: version2 }); opt = { resolveKnownTags: true, schema: "core" }; break; case null: if (this.directives) delete this.directives; opt = null; break; default: { const sv = JSON.stringify(version2); throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); } } if (options.schema instanceof Object) this.schema = options.schema; else if (opt) this.schema = new Schema.Schema(Object.assign(opt, options)); else throw new Error(`With a null YAML version, the { schema: Schema } option is required`); } // json & jsonArg are only used from toJSON() toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { const ctx = { anchors: /* @__PURE__ */ new Map(), doc: this, keep: !json2, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 }; const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); if (typeof onAnchor === "function") for (const { count, res: res2 } of ctx.anchors.values()) onAnchor(res2, count); return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; } /** * A JSON representation of the document `contents`. * * @param jsonArg Used by `JSON.stringify` to indicate the array index or * property name. */ toJSON(jsonArg, onAnchor) { return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); } /** A YAML representation of the document. */ toString(options = {}) { if (this.errors.length > 0) throw new Error("Document with errors cannot be stringified"); if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { const s = JSON.stringify(options.indent); throw new Error(`"indent" option must be a positive integer, not ${s}`); } return stringifyDocument.stringifyDocument(this, options); } }; function assertCollection(contents) { if (identity.isCollection(contents)) return true; throw new Error("Expected a YAML collection as document contents"); } exports2.Document = Document; } }); // node_modules/yaml/dist/errors.js var require_errors = __commonJS({ "node_modules/yaml/dist/errors.js"(exports2) { "use strict"; var YAMLError = class extends Error { constructor(name, pos, code, message) { super(); this.name = name; this.code = code; this.message = message; this.pos = pos; } }; var YAMLParseError = class extends YAMLError { constructor(pos, code, message) { super("YAMLParseError", pos, code, message); } }; var YAMLWarning = class extends YAMLError { constructor(pos, code, message) { super("YAMLWarning", pos, code, message); } }; var prettifyError2 = (src, lc) => (error48) => { if (error48.pos[0] === -1) return; error48.linePos = error48.pos.map((pos) => lc.linePos(pos)); const { line, col } = error48.linePos[0]; error48.message += ` at line ${line}, column ${col}`; let ci = col - 1; let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); if (ci >= 60 && lineStr.length > 80) { const trimStart = Math.min(ci - 39, lineStr.length - 79); lineStr = "\u2026" + lineStr.substring(trimStart); ci -= trimStart - 1; } if (lineStr.length > 80) lineStr = lineStr.substring(0, 79) + "\u2026"; if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); if (prev.length > 80) prev = prev.substring(0, 79) + "\u2026\n"; lineStr = prev + lineStr; } if (/[^ ]/.test(lineStr)) { let count = 1; const end = error48.linePos[1]; if (end?.line === line && end.col > col) { count = Math.max(1, Math.min(end.col - col, 80 - ci)); } const pointer = " ".repeat(ci) + "^".repeat(count); error48.message += `: ${lineStr} ${pointer} `; } }; exports2.YAMLError = YAMLError; exports2.YAMLParseError = YAMLParseError; exports2.YAMLWarning = YAMLWarning; exports2.prettifyError = prettifyError2; } }); // node_modules/yaml/dist/compose/resolve-props.js var require_resolve_props = __commonJS({ "node_modules/yaml/dist/compose/resolve-props.js"(exports2) { "use strict"; function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { let spaceBefore = false; let atNewline = startOnNewline; let hasSpace = startOnNewline; let comment = ""; let commentSep = ""; let hasNewline = false; let reqSpace = false; let tab = null; let anchor = null; let tag = null; let newlineAfterProp = null; let comma = null; let found = null; let start = null; for (const token of tokens) { if (reqSpace) { if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); reqSpace = false; } if (tab) { if (atNewline && token.type !== "comment" && token.type !== "newline") { onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); } tab = null; } switch (token.type) { case "space": if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { tab = token; } hasSpace = true; break; case "comment": { if (!hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); const cb = token.source.substring(1) || " "; if (!comment) comment = cb; else comment += commentSep + cb; commentSep = ""; atNewline = false; break; } case "newline": if (atNewline) { if (comment) comment += token.source; else if (!found || indicator !== "seq-item-ind") spaceBefore = true; } else commentSep += token.source; atNewline = true; hasNewline = true; if (anchor || tag) newlineAfterProp = token; hasSpace = true; break; case "anchor": if (anchor) onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); if (token.source.endsWith(":")) onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); anchor = token; start ?? (start = token.offset); atNewline = false; hasSpace = false; reqSpace = true; break; case "tag": { if (tag) onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); tag = token; start ?? (start = token.offset); atNewline = false; hasSpace = false; reqSpace = true; break; } case indicator: if (anchor || tag) onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); if (found) onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); found = token; atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; hasSpace = false; break; case "comma": if (flow) { if (comma) onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); comma = token; atNewline = false; hasSpace = false; break; } // else fallthrough default: onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); atNewline = false; hasSpace = false; } } const last = tokens[tokens.length - 1]; const end = last ? last.offset + last.source.length : offset; if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); } if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); return { comma, found, spaceBefore, comment, hasNewline, anchor, tag, newlineAfterProp, end, start: start ?? end }; } exports2.resolveProps = resolveProps; } }); // node_modules/yaml/dist/compose/util-contains-newline.js var require_util_contains_newline = __commonJS({ "node_modules/yaml/dist/compose/util-contains-newline.js"(exports2) { "use strict"; function containsNewline(key) { if (!key) return null; switch (key.type) { case "alias": case "scalar": case "double-quoted-scalar": case "single-quoted-scalar": if (key.source.includes("\n")) return true; if (key.end) { for (const st of key.end) if (st.type === "newline") return true; } return false; case "flow-collection": for (const it of key.items) { for (const st of it.start) if (st.type === "newline") return true; if (it.sep) { for (const st of it.sep) if (st.type === "newline") return true; } if (containsNewline(it.key) || containsNewline(it.value)) return true; } return false; default: return true; } } exports2.containsNewline = containsNewline; } }); // node_modules/yaml/dist/compose/util-flow-indent-check.js var require_util_flow_indent_check = __commonJS({ "node_modules/yaml/dist/compose/util-flow-indent-check.js"(exports2) { "use strict"; var utilContainsNewline = require_util_contains_newline(); function flowIndentCheck(indent, fc, onError) { if (fc?.type === "flow-collection") { const end = fc.end[0]; if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) { const msg = "Flow end indicator should be more indented than parent"; onError(end, "BAD_INDENT", msg, true); } } } exports2.flowIndentCheck = flowIndentCheck; } }); // node_modules/yaml/dist/compose/util-map-includes.js var require_util_map_includes = __commonJS({ "node_modules/yaml/dist/compose/util-map-includes.js"(exports2) { "use strict"; var identity = require_identity(); function mapIncludes(ctx, items, search) { const { uniqueKeys } = ctx.options; if (uniqueKeys === false) return false; const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value; return items.some((pair) => isEqual(pair.key, search)); } exports2.mapIncludes = mapIncludes; } }); // node_modules/yaml/dist/compose/resolve-block-map.js var require_resolve_block_map = __commonJS({ "node_modules/yaml/dist/compose/resolve-block-map.js"(exports2) { "use strict"; var Pair = require_Pair(); var YAMLMap = require_YAMLMap(); var resolveProps = require_resolve_props(); var utilContainsNewline = require_util_contains_newline(); var utilFlowIndentCheck = require_util_flow_indent_check(); var utilMapIncludes = require_util_map_includes(); var startColMsg = "All mapping items must start at the same column"; function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap; const map2 = new NodeClass(ctx.schema); if (ctx.atRoot) ctx.atRoot = false; let offset = bm.offset; let commentEnd = null; for (const collItem of bm.items) { const { start, key, sep, value } = collItem; const keyProps = resolveProps.resolveProps(start, { indicator: "explicit-key-ind", next: key ?? sep?.[0], offset, onError, parentIndent: bm.indent, startOnNewline: true }); const implicitKey = !keyProps.found; if (implicitKey) { if (key) { if (key.type === "block-seq") onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); else if ("indent" in key && key.indent !== bm.indent) onError(offset, "BAD_INDENT", startColMsg); } if (!keyProps.anchor && !keyProps.tag && !sep) { commentEnd = keyProps.end; if (keyProps.comment) { if (map2.comment) map2.comment += "\n" + keyProps.comment; else map2.comment = keyProps.comment; } continue; } if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) { onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); } } else if (keyProps.found?.indent !== bm.indent) { onError(offset, "BAD_INDENT", startColMsg); } ctx.atKey = true; const keyStart = keyProps.end; const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError); ctx.atKey = false; if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); const valueProps = resolveProps.resolveProps(sep ?? [], { indicator: "map-value-ind", next: value, offset: keyNode.range[2], onError, parentIndent: bm.indent, startOnNewline: !key || key.type === "block-scalar" }); offset = valueProps.end; if (valueProps.found) { if (implicitKey) { if (value?.type === "block-map" && !valueProps.hasNewline) onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); } const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError); offset = valueNode.range[2]; const pair = new Pair.Pair(keyNode, valueNode); if (ctx.options.keepSourceTokens) pair.srcToken = collItem; map2.items.push(pair); } else { if (implicitKey) onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); if (valueProps.comment) { if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; else keyNode.comment = valueProps.comment; } const pair = new Pair.Pair(keyNode); if (ctx.options.keepSourceTokens) pair.srcToken = collItem; map2.items.push(pair); } } if (commentEnd && commentEnd < offset) onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); map2.range = [bm.offset, offset, commentEnd ?? offset]; return map2; } exports2.resolveBlockMap = resolveBlockMap; } }); // node_modules/yaml/dist/compose/resolve-block-seq.js var require_resolve_block_seq = __commonJS({ "node_modules/yaml/dist/compose/resolve-block-seq.js"(exports2) { "use strict"; var YAMLSeq = require_YAMLSeq(); var resolveProps = require_resolve_props(); var utilFlowIndentCheck = require_util_flow_indent_check(); function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq; const seq = new NodeClass(ctx.schema); if (ctx.atRoot) ctx.atRoot = false; if (ctx.atKey) ctx.atKey = false; let offset = bs.offset; let commentEnd = null; for (const { start, value } of bs.items) { const props = resolveProps.resolveProps(start, { indicator: "seq-item-ind", next: value, offset, onError, parentIndent: bs.indent, startOnNewline: true }); if (!props.found) { if (props.anchor || props.tag || value) { if (value?.type === "block-seq") onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); else onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); } else { commentEnd = props.end; if (props.comment) seq.comment = props.comment; continue; } } const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError); offset = node.range[2]; seq.items.push(node); } seq.range = [bs.offset, offset, commentEnd ?? offset]; return seq; } exports2.resolveBlockSeq = resolveBlockSeq; } }); // node_modules/yaml/dist/compose/resolve-end.js var require_resolve_end = __commonJS({ "node_modules/yaml/dist/compose/resolve-end.js"(exports2) { "use strict"; function resolveEnd(end, offset, reqSpace, onError) { let comment = ""; if (end) { let hasSpace = false; let sep = ""; for (const token of end) { const { source, type } = token; switch (type) { case "space": hasSpace = true; break; case "comment": { if (reqSpace && !hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); const cb = source.substring(1) || " "; if (!comment) comment = cb; else comment += sep + cb; sep = ""; break; } case "newline": if (comment) sep += source; hasSpace = true; break; default: onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); } offset += source.length; } } return { comment, offset }; } exports2.resolveEnd = resolveEnd; } }); // node_modules/yaml/dist/compose/resolve-flow-collection.js var require_resolve_flow_collection = __commonJS({ "node_modules/yaml/dist/compose/resolve-flow-collection.js"(exports2) { "use strict"; var identity = require_identity(); var Pair = require_Pair(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var resolveEnd = require_resolve_end(); var resolveProps = require_resolve_props(); var utilContainsNewline = require_util_contains_newline(); var utilMapIncludes = require_util_map_includes(); var blockMsg = "Block collections are not allowed within flow collections"; var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { const isMap = fc.start.source === "{"; const fcName = isMap ? "flow map" : "flow sequence"; const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq); const coll = new NodeClass(ctx.schema); coll.flow = true; const atRoot = ctx.atRoot; if (atRoot) ctx.atRoot = false; if (ctx.atKey) ctx.atKey = false; let offset = fc.offset + fc.start.source.length; for (let i = 0; i < fc.items.length; ++i) { const collItem = fc.items[i]; const { start, key, sep, value } = collItem; const props = resolveProps.resolveProps(start, { flow: fcName, indicator: "explicit-key-ind", next: key ?? sep?.[0], offset, onError, parentIndent: fc.indent, startOnNewline: false }); if (!props.found) { if (!props.anchor && !props.tag && !sep && !value) { if (i === 0 && props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); else if (i < fc.items.length - 1) onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); if (props.comment) { if (coll.comment) coll.comment += "\n" + props.comment; else coll.comment = props.comment; } offset = props.end; continue; } if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) onError( key, // checked by containsNewline() "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line" ); } if (i === 0) { if (props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); } else { if (!props.comma) onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); if (props.comment) { let prevItemComment = ""; loop: for (const st of start) { switch (st.type) { case "comma": case "space": break; case "comment": prevItemComment = st.source.substring(1); break loop; default: break loop; } } if (prevItemComment) { let prev = coll.items[coll.items.length - 1]; if (identity.isPair(prev)) prev = prev.value ?? prev.key; if (prev.comment) prev.comment += "\n" + prevItemComment; else prev.comment = prevItemComment; props.comment = props.comment.substring(prevItemComment.length + 1); } } } if (!isMap && !sep && !props.found) { const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError); coll.items.push(valueNode); offset = valueNode.range[2]; if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); } else { ctx.atKey = true; const keyStart = props.end; const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError); if (isBlock(key)) onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); ctx.atKey = false; const valueProps = resolveProps.resolveProps(sep ?? [], { flow: fcName, indicator: "map-value-ind", next: value, offset: keyNode.range[2], onError, parentIndent: fc.indent, startOnNewline: false }); if (valueProps.found) { if (!isMap && !props.found && ctx.options.strict) { if (sep) for (const st of sep) { if (st === valueProps.found) break; if (st.type === "newline") { onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); break; } } if (props.start < valueProps.found.offset - 1024) onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); } } else if (value) { if ("source" in value && value.source?.[0] === ":") onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); else onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); } const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null; if (valueNode) { if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); } else if (valueProps.comment) { if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; else keyNode.comment = valueProps.comment; } const pair = new Pair.Pair(keyNode, valueNode); if (ctx.options.keepSourceTokens) pair.srcToken = collItem; if (isMap) { const map2 = coll; if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); map2.items.push(pair); } else { const map2 = new YAMLMap.YAMLMap(ctx.schema); map2.flow = true; map2.items.push(pair); const endRange = (valueNode ?? keyNode).range; map2.range = [keyNode.range[0], endRange[1], endRange[2]]; coll.items.push(map2); } offset = valueNode ? valueNode.range[2] : valueProps.end; } } const expectedEnd = isMap ? "}" : "]"; const [ce, ...ee] = fc.end; let cePos = offset; if (ce?.source === expectedEnd) cePos = ce.offset + ce.source.length; else { const name = fcName[0].toUpperCase() + fcName.substring(1); const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); if (ce && ce.source.length !== 1) ee.unshift(ce); } if (ee.length > 0) { const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError); if (end.comment) { if (coll.comment) coll.comment += "\n" + end.comment; else coll.comment = end.comment; } coll.range = [fc.offset, cePos, end.offset]; } else { coll.range = [fc.offset, cePos, cePos]; } return coll; } exports2.resolveFlowCollection = resolveFlowCollection; } }); // node_modules/yaml/dist/compose/compose-collection.js var require_compose_collection = __commonJS({ "node_modules/yaml/dist/compose/compose-collection.js"(exports2) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var resolveBlockMap = require_resolve_block_map(); var resolveBlockSeq = require_resolve_block_seq(); var resolveFlowCollection = require_resolve_flow_collection(); function resolveCollection(CN, ctx, token, onError, tagName, tag) { const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag); const Coll = coll.constructor; if (tagName === "!" || tagName === Coll.tagName) { coll.tag = Coll.tagName; return coll; } if (tagName) coll.tag = tagName; return coll; } function composeCollection(CN, ctx, token, props, onError) { const tagToken = props.tag; const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); if (token.type === "block-seq") { const { anchor, newlineAfterProp: nl } = props; const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; if (lastProp && (!nl || nl.offset < lastProp.offset)) { const message = "Missing newline after block sequence props"; onError(lastProp, "MISSING_CHAR", message); } } const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") { return resolveCollection(CN, ctx, token, onError, tagName); } let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); if (!tag) { const kt = ctx.schema.knownTags[tagName]; if (kt?.collection === expType) { ctx.schema.tags.push(Object.assign({}, kt, { default: false })); tag = kt; } else { if (kt) { onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); } else { onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); } return resolveCollection(CN, ctx, token, onError, tagName); } } const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; const node = identity.isNode(res) ? res : new Scalar.Scalar(res); node.range = coll.range; node.tag = tagName; if (tag?.format) node.format = tag.format; return node; } exports2.composeCollection = composeCollection; } }); // node_modules/yaml/dist/compose/resolve-block-scalar.js var require_resolve_block_scalar = __commonJS({ "node_modules/yaml/dist/compose/resolve-block-scalar.js"(exports2) { "use strict"; var Scalar = require_Scalar(); function resolveBlockScalar(ctx, scalar, onError) { const start = scalar.offset; const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); if (!header) return { value: "", type: null, comment: "", range: [start, start, start] }; const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; const lines = scalar.source ? splitLines3(scalar.source) : []; let chompStart = lines.length; for (let i = lines.length - 1; i >= 0; --i) { const content = lines[i][1]; if (content === "" || content === "\r") chompStart = i; else break; } if (chompStart === 0) { const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; let end2 = start + header.length; if (scalar.source) end2 += scalar.source.length; return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; } let trimIndent = scalar.indent + header.indent; let offset = scalar.offset + header.length; let contentStart = 0; for (let i = 0; i < chompStart; ++i) { const [indent, content] = lines[i]; if (content === "" || content === "\r") { if (header.indent === 0 && indent.length > trimIndent) trimIndent = indent.length; } else { if (indent.length < trimIndent) { const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; onError(offset + indent.length, "MISSING_CHAR", message); } if (header.indent === 0) trimIndent = indent.length; contentStart = i; if (trimIndent === 0 && !ctx.atRoot) { const message = "Block scalar values in collections must be indented"; onError(offset, "BAD_INDENT", message); } break; } offset += indent.length + content.length + 1; } for (let i = lines.length - 1; i >= chompStart; --i) { if (lines[i][0].length > trimIndent) chompStart = i + 1; } let value = ""; let sep = ""; let prevMoreIndented = false; for (let i = 0; i < contentStart; ++i) value += lines[i][0].slice(trimIndent) + "\n"; for (let i = contentStart; i < chompStart; ++i) { let [indent, content] = lines[i]; offset += indent.length + content.length + 1; const crlf = content[content.length - 1] === "\r"; if (crlf) content = content.slice(0, -1); if (content && indent.length < trimIndent) { const src = header.indent ? "explicit indentation indicator" : "first line"; const message = `Block scalar lines must not be less indented than their ${src}`; onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); indent = ""; } if (type === Scalar.Scalar.BLOCK_LITERAL) { value += sep + indent.slice(trimIndent) + content; sep = "\n"; } else if (indent.length > trimIndent || content[0] === " ") { if (sep === " ") sep = "\n"; else if (!prevMoreIndented && sep === "\n") sep = "\n\n"; value += sep + indent.slice(trimIndent) + content; sep = "\n"; prevMoreIndented = true; } else if (content === "") { if (sep === "\n") value += "\n"; else sep = "\n"; } else { value += sep + content; sep = " "; prevMoreIndented = false; } } switch (header.chomp) { case "-": break; case "+": for (let i = chompStart; i < lines.length; ++i) value += "\n" + lines[i][0].slice(trimIndent); if (value[value.length - 1] !== "\n") value += "\n"; break; default: value += "\n"; } const end = start + header.length + scalar.source.length; return { value, type, comment: header.comment, range: [start, end, end] }; } function parseBlockScalarHeader({ offset, props }, strict, onError) { if (props[0].type !== "block-scalar-header") { onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); return null; } const { source } = props[0]; const mode = source[0]; let indent = 0; let chomp = ""; let error48 = -1; for (let i = 1; i < source.length; ++i) { const ch = source[i]; if (!chomp && (ch === "-" || ch === "+")) chomp = ch; else { const n = Number(ch); if (!indent && n) indent = n; else if (error48 === -1) error48 = offset + i; } } if (error48 !== -1) onError(error48, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); let hasSpace = false; let comment = ""; let length = source.length; for (let i = 1; i < props.length; ++i) { const token = props[i]; switch (token.type) { case "space": hasSpace = true; // fallthrough case "newline": length += token.source.length; break; case "comment": if (strict && !hasSpace) { const message = "Comments must be separated from other tokens by white space characters"; onError(token, "MISSING_CHAR", message); } length += token.source.length; comment = token.source.substring(1); break; case "error": onError(token, "UNEXPECTED_TOKEN", token.message); length += token.source.length; break; /* istanbul ignore next should not happen */ default: { const message = `Unexpected token in block scalar header: ${token.type}`; onError(token, "UNEXPECTED_TOKEN", message); const ts = token.source; if (ts && typeof ts === "string") length += ts.length; } } } return { mode, indent, chomp, comment, length }; } function splitLines3(source) { const split = source.split(/\n( *)/); const first = split[0]; const m = first.match(/^( *)/); const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; const lines = [line0]; for (let i = 1; i < split.length; i += 2) lines.push([split[i], split[i + 1]]); return lines; } exports2.resolveBlockScalar = resolveBlockScalar; } }); // node_modules/yaml/dist/compose/resolve-flow-scalar.js var require_resolve_flow_scalar = __commonJS({ "node_modules/yaml/dist/compose/resolve-flow-scalar.js"(exports2) { "use strict"; var Scalar = require_Scalar(); var resolveEnd = require_resolve_end(); function resolveFlowScalar(scalar, strict, onError) { const { offset, type, source, end } = scalar; let _type; let value; const _onError2 = (rel, code, msg) => onError(offset + rel, code, msg); switch (type) { case "scalar": _type = Scalar.Scalar.PLAIN; value = plainValue(source, _onError2); break; case "single-quoted-scalar": _type = Scalar.Scalar.QUOTE_SINGLE; value = singleQuotedValue(source, _onError2); break; case "double-quoted-scalar": _type = Scalar.Scalar.QUOTE_DOUBLE; value = doubleQuotedValue(source, _onError2); break; /* istanbul ignore next should not happen */ default: onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); return { value: "", type: null, comment: "", range: [offset, offset + source.length, offset + source.length] }; } const valueEnd = offset + source.length; const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError); return { value, type: _type, comment: re.comment, range: [offset, valueEnd, re.offset] }; } function plainValue(source, onError) { let badChar = ""; switch (source[0]) { /* istanbul ignore next should not happen */ case " ": badChar = "a tab character"; break; case ",": badChar = "flow indicator character ,"; break; case "%": badChar = "directive indicator character %"; break; case "|": case ">": { badChar = `block scalar indicator ${source[0]}`; break; } case "@": case "`": { badChar = `reserved character ${source[0]}`; break; } } if (badChar) onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); return foldLines(source); } function singleQuotedValue(source, onError) { if (source[source.length - 1] !== "'" || source.length === 1) onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); return foldLines(source.slice(1, -1)).replace(/''/g, "'"); } function foldLines(source) { let first, line; try { first = new RegExp("(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; } else { res += ch; } } if (source[source.length - 1] !== '"' || source.length === 1) onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); return res; } function foldNewline(source, offset) { let fold = ""; let ch = source[offset + 1]; while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { if (ch === "\r" && source[offset + 2] !== "\n") break; if (ch === "\n") fold += "\n"; offset += 1; ch = source[offset + 1]; } if (!fold) fold = " "; return { fold, offset }; } var escapeCodes = { "0": "\0", // null character a: "\x07", // bell character b: "\b", // backspace e: "\x1B", // escape character f: "\f", // form feed n: "\n", // line feed r: "\r", // carriage return t: " ", // horizontal tab v: "\v", // vertical tab N: "\x85", // Unicode next line _: "\xA0", // Unicode non-breaking space L: "\u2028", // Unicode line separator P: "\u2029", // Unicode paragraph separator " ": " ", '"': '"', "/": "/", "\\": "\\", " ": " " }; function parseCharCode(source, offset, length, onError) { const cc = source.substr(offset, length); const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); const code = ok ? parseInt(cc, 16) : NaN; if (isNaN(code)) { const raw = source.substr(offset - 2, length + 2); onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); return raw; } return String.fromCodePoint(code); } exports2.resolveFlowScalar = resolveFlowScalar; } }); // node_modules/yaml/dist/compose/compose-scalar.js var require_compose_scalar = __commonJS({ "node_modules/yaml/dist/compose/compose-scalar.js"(exports2) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var resolveBlockScalar = require_resolve_block_scalar(); var resolveFlowScalar = require_resolve_flow_scalar(); function composeScalar(ctx, token, tagToken, onError) { const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError); const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; let tag; if (ctx.options.stringKeys && ctx.atKey) { tag = ctx.schema[identity.SCALAR]; } else if (tagName) tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); else if (token.type === "scalar") tag = findScalarTagByTest(ctx, value, token, onError); else tag = ctx.schema[identity.SCALAR]; let scalar; try { const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); } catch (error48) { const msg = error48 instanceof Error ? error48.message : String(error48); onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); scalar = new Scalar.Scalar(value); } scalar.range = range; scalar.source = value; if (type) scalar.type = type; if (tagName) scalar.tag = tagName; if (tag.format) scalar.format = tag.format; if (comment) scalar.comment = comment; return scalar; } function findScalarTagByName(schema, value, tagName, tagToken, onError) { if (tagName === "!") return schema[identity.SCALAR]; const matchWithTest = []; for (const tag of schema.tags) { if (!tag.collection && tag.tag === tagName) { if (tag.default && tag.test) matchWithTest.push(tag); else return tag; } } for (const tag of matchWithTest) if (tag.test?.test(value)) return tag; const kt = schema.knownTags[tagName]; if (kt && !kt.collection) { schema.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); return kt; } onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); return schema[identity.SCALAR]; } function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) { const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR]; if (schema.compat) { const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR]; if (tag.tag !== compat.tag) { const ts = directives.tagString(tag.tag); const cs = directives.tagString(compat.tag); const msg = `Value may be parsed as either ${ts} or ${cs}`; onError(token, "TAG_RESOLVE_FAILED", msg, true); } } return tag; } exports2.composeScalar = composeScalar; } }); // node_modules/yaml/dist/compose/util-empty-scalar-position.js var require_util_empty_scalar_position = __commonJS({ "node_modules/yaml/dist/compose/util-empty-scalar-position.js"(exports2) { "use strict"; function emptyScalarPosition(offset, before, pos) { if (before) { pos ?? (pos = before.length); for (let i = pos - 1; i >= 0; --i) { let st = before[i]; switch (st.type) { case "space": case "comment": case "newline": offset -= st.source.length; continue; } st = before[++i]; while (st?.type === "space") { offset += st.source.length; st = before[++i]; } break; } } return offset; } exports2.emptyScalarPosition = emptyScalarPosition; } }); // node_modules/yaml/dist/compose/compose-node.js var require_compose_node = __commonJS({ "node_modules/yaml/dist/compose/compose-node.js"(exports2) { "use strict"; var Alias = require_Alias(); var identity = require_identity(); var composeCollection = require_compose_collection(); var composeScalar = require_compose_scalar(); var resolveEnd = require_resolve_end(); var utilEmptyScalarPosition = require_util_empty_scalar_position(); var CN = { composeNode, composeEmptyNode }; function composeNode(ctx, token, props, onError) { const atKey = ctx.atKey; const { spaceBefore, comment, anchor, tag } = props; let node; let isSrcToken = true; switch (token.type) { case "alias": node = composeAlias(ctx, token, onError); if (anchor || tag) onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); break; case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": case "block-scalar": node = composeScalar.composeScalar(ctx, token, tag, onError); if (anchor) node.anchor = anchor.source.substring(1); break; case "block-map": case "block-seq": case "flow-collection": try { node = composeCollection.composeCollection(CN, ctx, token, props, onError); if (anchor) node.anchor = anchor.source.substring(1); } catch (error48) { const message = error48 instanceof Error ? error48.message : String(error48); onError(token, "RESOURCE_EXHAUSTION", message); } break; default: { const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; onError(token, "UNEXPECTED_TOKEN", message); isSrcToken = false; } } node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); if (anchor && node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { const msg = "With stringKeys, all keys must be strings"; onError(tag ?? token, "NON_STRING_KEY", msg); } if (spaceBefore) node.spaceBefore = true; if (comment) { if (token.type === "scalar" && token.source === "") node.comment = comment; else node.commentBefore = comment; } if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token; return node; } function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { const token = { type: "scalar", offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), indent: -1, source: "" }; const node = composeScalar.composeScalar(ctx, token, tag, onError); if (anchor) { node.anchor = anchor.source.substring(1); if (node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); } if (spaceBefore) node.spaceBefore = true; if (comment) { node.comment = comment; node.range[2] = end; } return node; } function composeAlias({ options }, { offset, source, end }, onError) { const alias = new Alias.Alias(source.substring(1)); if (alias.source === "") onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); if (alias.source.endsWith(":")) onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); const valueEnd = offset + source.length; const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError); alias.range = [offset, valueEnd, re.offset]; if (re.comment) alias.comment = re.comment; return alias; } exports2.composeEmptyNode = composeEmptyNode; exports2.composeNode = composeNode; } }); // node_modules/yaml/dist/compose/compose-doc.js var require_compose_doc = __commonJS({ "node_modules/yaml/dist/compose/compose-doc.js"(exports2) { "use strict"; var Document = require_Document(); var composeNode = require_compose_node(); var resolveEnd = require_resolve_end(); var resolveProps = require_resolve_props(); function composeDoc(options, directives, { offset, start, value, end }, onError) { const opts = Object.assign({ _directives: directives }, options); const doc = new Document.Document(void 0, opts); const ctx = { atKey: false, atRoot: true, directives: doc.directives, options: doc.options, schema: doc.schema }; const props = resolveProps.resolveProps(start, { indicator: "doc-start", next: value ?? end?.[0], offset, onError, parentIndent: 0, startOnNewline: true }); if (props.found) { doc.directives.docStart = true; if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); } doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError); const contentEnd = doc.contents.range[2]; const re = resolveEnd.resolveEnd(end, contentEnd, false, onError); if (re.comment) doc.comment = re.comment; doc.range = [offset, contentEnd, re.offset]; return doc; } exports2.composeDoc = composeDoc; } }); // node_modules/yaml/dist/compose/composer.js var require_composer = __commonJS({ "node_modules/yaml/dist/compose/composer.js"(exports2) { "use strict"; var node_process = require("process"); var directives = require_directives(); var Document = require_Document(); var errors = require_errors(); var identity = require_identity(); var composeDoc = require_compose_doc(); var resolveEnd = require_resolve_end(); function getErrorPos(src) { if (typeof src === "number") return [src, src + 1]; if (Array.isArray(src)) return src.length === 2 ? src : [src[0], src[1]]; const { offset, source } = src; return [offset, offset + (typeof source === "string" ? source.length : 1)]; } function parsePrelude(prelude) { let comment = ""; let atComment = false; let afterEmptyLine = false; for (let i = 0; i < prelude.length; ++i) { const source = prelude[i]; switch (source[0]) { case "#": comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); atComment = true; afterEmptyLine = false; break; case "%": if (prelude[i + 1]?.[0] !== "#") i += 1; atComment = false; break; default: if (!atComment) afterEmptyLine = true; atComment = false; } } return { comment, afterEmptyLine }; } var Composer = class { constructor(options = {}) { this.doc = null; this.atDirectives = false; this.prelude = []; this.errors = []; this.warnings = []; this.onError = (source, code, message, warning) => { const pos = getErrorPos(source); if (warning) this.warnings.push(new errors.YAMLWarning(pos, code, message)); else this.errors.push(new errors.YAMLParseError(pos, code, message)); }; this.directives = new directives.Directives({ version: options.version || "1.2" }); this.options = options; } decorate(doc, afterDoc) { const { comment, afterEmptyLine } = parsePrelude(this.prelude); if (comment) { const dc = doc.contents; if (afterDoc) { doc.comment = doc.comment ? `${doc.comment} ${comment}` : comment; } else if (afterEmptyLine || doc.directives.docStart || !dc) { doc.commentBefore = comment; } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { let it = dc.items[0]; if (identity.isPair(it)) it = it.key; const cb = it.commentBefore; it.commentBefore = cb ? `${comment} ${cb}` : comment; } else { const cb = dc.commentBefore; dc.commentBefore = cb ? `${comment} ${cb}` : comment; } } if (afterDoc) { Array.prototype.push.apply(doc.errors, this.errors); Array.prototype.push.apply(doc.warnings, this.warnings); } else { doc.errors = this.errors; doc.warnings = this.warnings; } this.prelude = []; this.errors = []; this.warnings = []; } /** * Current stream status information. * * Mostly useful at the end of input for an empty stream. */ streamInfo() { return { comment: parsePrelude(this.prelude).comment, directives: this.directives, errors: this.errors, warnings: this.warnings }; } /** * Compose tokens into documents. * * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. */ *compose(tokens, forceDoc = false, endOffset = -1) { for (const token of tokens) yield* this.next(token); yield* this.end(forceDoc, endOffset); } /** Advance the composer by one CST token. */ *next(token) { if (node_process.env.LOG_STREAM) console.dir(token, { depth: null }); switch (token.type) { case "directive": this.directives.add(token.source, (offset, message, warning) => { const pos = getErrorPos(token); pos[0] += offset; this.onError(pos, "BAD_DIRECTIVE", message, warning); }); this.prelude.push(token.source); this.atDirectives = true; break; case "document": { const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError); if (this.atDirectives && !doc.directives.docStart) this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); this.decorate(doc, false); if (this.doc) yield this.doc; this.doc = doc; this.atDirectives = false; break; } case "byte-order-mark": case "space": break; case "comment": case "newline": this.prelude.push(token.source); break; case "error": { const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; const error48 = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); if (this.atDirectives || !this.doc) this.errors.push(error48); else this.doc.errors.push(error48); break; } case "doc-end": { if (!this.doc) { const msg = "Unexpected doc-end without preceding document"; this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); break; } this.doc.directives.docEnd = true; const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); this.decorate(this.doc, true); if (end.comment) { const dc = this.doc.comment; this.doc.comment = dc ? `${dc} ${end.comment}` : end.comment; } this.doc.range[2] = end.offset; break; } default: this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); } } /** * Call at end of input to yield any remaining document. * * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. */ *end(forceDoc = false, endOffset = -1) { if (this.doc) { this.decorate(this.doc, true); yield this.doc; this.doc = null; } else if (forceDoc) { const opts = Object.assign({ _directives: this.directives }, this.options); const doc = new Document.Document(void 0, opts); if (this.atDirectives) this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); doc.range = [0, endOffset, endOffset]; this.decorate(doc, false); yield doc; } } }; exports2.Composer = Composer; } }); // node_modules/yaml/dist/parse/cst-scalar.js var require_cst_scalar = __commonJS({ "node_modules/yaml/dist/parse/cst-scalar.js"(exports2) { "use strict"; var resolveBlockScalar = require_resolve_block_scalar(); var resolveFlowScalar = require_resolve_flow_scalar(); var errors = require_errors(); var stringifyString = require_stringifyString(); function resolveAsScalar(token, strict = true, onError) { if (token) { const _onError2 = (pos, code, message) => { const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; if (onError) onError(offset, code, message); else throw new errors.YAMLParseError([offset, offset + 1], code, message); }; switch (token.type) { case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": return resolveFlowScalar.resolveFlowScalar(token, strict, _onError2); case "block-scalar": return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError2); } } return null; } function createScalarToken(value, context) { const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; const source = stringifyString.stringifyString({ type, value }, { implicitKey, indent: indent > 0 ? " ".repeat(indent) : "", inFlow, options: { blockQuote: true, lineWidth: -1 } }); const end = context.end ?? [ { type: "newline", offset: -1, indent, source: "\n" } ]; switch (source[0]) { case "|": case ">": { const he = source.indexOf("\n"); const head = source.substring(0, he); const body = source.substring(he + 1) + "\n"; const props = [ { type: "block-scalar-header", offset, indent, source: head } ]; if (!addEndtoBlockProps(props, end)) props.push({ type: "newline", offset: -1, indent, source: "\n" }); return { type: "block-scalar", offset, indent, props, source: body }; } case '"': return { type: "double-quoted-scalar", offset, indent, source, end }; case "'": return { type: "single-quoted-scalar", offset, indent, source, end }; default: return { type: "scalar", offset, indent, source, end }; } } function setScalarValue(token, value, context = {}) { let { afterKey = false, implicitKey = false, inFlow = false, type } = context; let indent = "indent" in token ? token.indent : null; if (afterKey && typeof indent === "number") indent += 2; if (!type) switch (token.type) { case "single-quoted-scalar": type = "QUOTE_SINGLE"; break; case "double-quoted-scalar": type = "QUOTE_DOUBLE"; break; case "block-scalar": { const header = token.props[0]; if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; break; } default: type = "PLAIN"; } const source = stringifyString.stringifyString({ type, value }, { implicitKey: implicitKey || indent === null, indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", inFlow, options: { blockQuote: true, lineWidth: -1 } }); switch (source[0]) { case "|": case ">": setBlockScalarValue(token, source); break; case '"': setFlowScalarValue(token, source, "double-quoted-scalar"); break; case "'": setFlowScalarValue(token, source, "single-quoted-scalar"); break; default: setFlowScalarValue(token, source, "scalar"); } } function setBlockScalarValue(token, source) { const he = source.indexOf("\n"); const head = source.substring(0, he); const body = source.substring(he + 1) + "\n"; if (token.type === "block-scalar") { const header = token.props[0]; if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); header.source = head; token.source = body; } else { const { offset } = token; const indent = "indent" in token ? token.indent : -1; const props = [ { type: "block-scalar-header", offset, indent, source: head } ]; if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) props.push({ type: "newline", offset: -1, indent, source: "\n" }); for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; Object.assign(token, { type: "block-scalar", indent, props, source: body }); } } function addEndtoBlockProps(props, end) { if (end) for (const st of end) switch (st.type) { case "space": case "comment": props.push(st); break; case "newline": props.push(st); return true; } return false; } function setFlowScalarValue(token, source, type) { switch (token.type) { case "scalar": case "double-quoted-scalar": case "single-quoted-scalar": token.type = type; token.source = source; break; case "block-scalar": { const end = token.props.slice(1); let oa = source.length; if (token.props[0].type === "block-scalar-header") oa -= token.props[0].source.length; for (const tok of end) tok.offset += oa; delete token.props; Object.assign(token, { type, source, end }); break; } case "block-map": case "block-seq": { const offset = token.offset + source.length; const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; delete token.items; Object.assign(token, { type, source, end: [nl] }); break; } default: { const indent = "indent" in token ? token.indent : -1; const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; Object.assign(token, { type, indent, source, end }); } } } exports2.createScalarToken = createScalarToken; exports2.resolveAsScalar = resolveAsScalar; exports2.setScalarValue = setScalarValue; } }); // node_modules/yaml/dist/parse/cst-stringify.js var require_cst_stringify = __commonJS({ "node_modules/yaml/dist/parse/cst-stringify.js"(exports2) { "use strict"; var stringify = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); function stringifyToken(token) { switch (token.type) { case "block-scalar": { let res = ""; for (const tok of token.props) res += stringifyToken(tok); return res + token.source; } case "block-map": case "block-seq": { let res = ""; for (const item of token.items) res += stringifyItem(item); return res; } case "flow-collection": { let res = token.start.source; for (const item of token.items) res += stringifyItem(item); for (const st of token.end) res += st.source; return res; } case "document": { let res = stringifyItem(token); if (token.end) for (const st of token.end) res += st.source; return res; } default: { let res = token.source; if ("end" in token && token.end) for (const st of token.end) res += st.source; return res; } } } function stringifyItem({ start, key, sep, value }) { let res = ""; for (const st of start) res += st.source; if (key) res += stringifyToken(key); if (sep) for (const st of sep) res += st.source; if (value) res += stringifyToken(value); return res; } exports2.stringify = stringify; } }); // node_modules/yaml/dist/parse/cst-visit.js var require_cst_visit = __commonJS({ "node_modules/yaml/dist/parse/cst-visit.js"(exports2) { "use strict"; var BREAK = Symbol("break visit"); var SKIP = Symbol("skip children"); var REMOVE = Symbol("remove item"); function visit(cst, visitor) { if ("type" in cst && cst.type === "document") cst = { start: cst.start, value: cst.value }; _visit(Object.freeze([]), cst, visitor); } visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; visit.itemAtPath = (cst, path) => { let item = cst; for (const [field, index] of path) { const tok = item?.[field]; if (tok && "items" in tok) { item = tok.items[index]; } else return void 0; } return item; }; visit.parentCollection = (cst, path) => { const parent = visit.itemAtPath(cst, path.slice(0, -1)); const field = path[path.length - 1][0]; const coll = parent?.[field]; if (coll && "items" in coll) return coll; throw new Error("Parent collection not found"); }; function _visit(path, item, visitor) { let ctrl = visitor(item, path); if (typeof ctrl === "symbol") return ctrl; for (const field of ["key", "value"]) { const token = item[field]; if (token && "items" in token) { for (let i = 0; i < token.items.length; ++i) { const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) return BREAK; else if (ci === REMOVE) { token.items.splice(i, 1); i -= 1; } } if (typeof ctrl === "function" && field === "key") ctrl = ctrl(item, path); } } return typeof ctrl === "function" ? ctrl(item, path) : ctrl; } exports2.visit = visit; } }); // node_modules/yaml/dist/parse/cst.js var require_cst = __commonJS({ "node_modules/yaml/dist/parse/cst.js"(exports2) { "use strict"; var cstScalar = require_cst_scalar(); var cstStringify = require_cst_stringify(); var cstVisit = require_cst_visit(); var BOM = "\uFEFF"; var DOCUMENT = ""; var FLOW_END = ""; var SCALAR = ""; var isCollection = (token) => !!token && "items" in token; var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); function prettyToken(token) { switch (token) { case BOM: return ""; case DOCUMENT: return ""; case FLOW_END: return ""; case SCALAR: return ""; default: return JSON.stringify(token); } } function tokenType(source) { switch (source) { case BOM: return "byte-order-mark"; case DOCUMENT: return "doc-mode"; case FLOW_END: return "flow-error-end"; case SCALAR: return "scalar"; case "---": return "doc-start"; case "...": return "doc-end"; case "": case "\n": case "\r\n": return "newline"; case "-": return "seq-item-ind"; case "?": return "explicit-key-ind"; case ":": return "map-value-ind"; case "{": return "flow-map-start"; case "}": return "flow-map-end"; case "[": return "flow-seq-start"; case "]": return "flow-seq-end"; case ",": return "comma"; } switch (source[0]) { case " ": case " ": return "space"; case "#": return "comment"; case "%": return "directive-line"; case "*": return "alias"; case "&": return "anchor"; case "!": return "tag"; case "'": return "single-quoted-scalar"; case '"': return "double-quoted-scalar"; case "|": case ">": return "block-scalar-header"; } return null; } exports2.createScalarToken = cstScalar.createScalarToken; exports2.resolveAsScalar = cstScalar.resolveAsScalar; exports2.setScalarValue = cstScalar.setScalarValue; exports2.stringify = cstStringify.stringify; exports2.visit = cstVisit.visit; exports2.BOM = BOM; exports2.DOCUMENT = DOCUMENT; exports2.FLOW_END = FLOW_END; exports2.SCALAR = SCALAR; exports2.isCollection = isCollection; exports2.isScalar = isScalar; exports2.prettyToken = prettyToken; exports2.tokenType = tokenType; } }); // node_modules/yaml/dist/parse/lexer.js var require_lexer = __commonJS({ "node_modules/yaml/dist/parse/lexer.js"(exports2) { "use strict"; var cst = require_cst(); function isEmpty(ch) { switch (ch) { case void 0: case " ": case "\n": case "\r": case " ": return true; default: return false; } } var hexDigits = new Set("0123456789ABCDEFabcdef"); var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); var flowIndicatorChars = new Set(",[]{}"); var invalidAnchorChars = new Set(" ,[]{}\n\r "); var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); var Lexer = class { constructor() { this.atEnd = false; this.blockScalarIndent = -1; this.blockScalarKeep = false; this.buffer = ""; this.flowKey = false; this.flowLevel = 0; this.indentNext = 0; this.indentValue = 0; this.lineEndPos = null; this.next = null; this.pos = 0; } /** * Generate YAML tokens from the `source` string. If `incomplete`, * a part of the last line may be left as a buffer for the next call. * * @returns A generator of lexical tokens */ *lex(source, incomplete = false) { if (source) { if (typeof source !== "string") throw TypeError("source is not a string"); this.buffer = this.buffer ? this.buffer + source : source; this.lineEndPos = null; } this.atEnd = !incomplete; let next = this.next ?? "stream"; while (next && (incomplete || this.hasChars(1))) next = yield* this.parseNext(next); } atLineEnd() { let i = this.pos; let ch = this.buffer[i]; while (ch === " " || ch === " ") ch = this.buffer[++i]; if (!ch || ch === "#" || ch === "\n") return true; if (ch === "\r") return this.buffer[i + 1] === "\n"; return false; } charAt(n) { return this.buffer[this.pos + n]; } continueScalar(offset) { let ch = this.buffer[offset]; if (this.indentNext > 0) { let indent = 0; while (ch === " ") ch = this.buffer[++indent + offset]; if (ch === "\r") { const next = this.buffer[indent + offset + 1]; if (next === "\n" || !next && !this.atEnd) return offset + indent + 1; } return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; } if (ch === "-" || ch === ".") { const dt = this.buffer.substr(offset, 3); if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) return -1; } return offset; } getLine() { let end = this.lineEndPos; if (typeof end !== "number" || end !== -1 && end < this.pos) { end = this.buffer.indexOf("\n", this.pos); this.lineEndPos = end; } if (end === -1) return this.atEnd ? this.buffer.substring(this.pos) : null; if (this.buffer[end - 1] === "\r") end -= 1; return this.buffer.substring(this.pos, end); } hasChars(n) { return this.pos + n <= this.buffer.length; } setNext(state) { this.buffer = this.buffer.substring(this.pos); this.pos = 0; this.lineEndPos = null; this.next = state; return null; } peek(n) { return this.buffer.substr(this.pos, n); } *parseNext(next) { switch (next) { case "stream": return yield* this.parseStream(); case "line-start": return yield* this.parseLineStart(); case "block-start": return yield* this.parseBlockStart(); case "doc": return yield* this.parseDocument(); case "flow": return yield* this.parseFlowCollection(); case "quoted-scalar": return yield* this.parseQuotedScalar(); case "block-scalar": return yield* this.parseBlockScalar(); case "plain-scalar": return yield* this.parsePlainScalar(); } } *parseStream() { let line = this.getLine(); if (line === null) return this.setNext("stream"); if (line[0] === cst.BOM) { yield* this.pushCount(1); line = line.substring(1); } if (line[0] === "%") { let dirEnd = line.length; let cs = line.indexOf("#"); while (cs !== -1) { const ch = line[cs - 1]; if (ch === " " || ch === " ") { dirEnd = cs - 1; break; } else { cs = line.indexOf("#", cs + 1); } } while (true) { const ch = line[dirEnd - 1]; if (ch === " " || ch === " ") dirEnd -= 1; else break; } const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); yield* this.pushCount(line.length - n); this.pushNewline(); return "stream"; } if (this.atLineEnd()) { const sp = yield* this.pushSpaces(true); yield* this.pushCount(line.length - sp); yield* this.pushNewline(); return "stream"; } yield cst.DOCUMENT; return yield* this.parseLineStart(); } *parseLineStart() { const ch = this.charAt(0); if (!ch && !this.atEnd) return this.setNext("line-start"); if (ch === "-" || ch === ".") { if (!this.atEnd && !this.hasChars(4)) return this.setNext("line-start"); const s = this.peek(3); if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { yield* this.pushCount(3); this.indentValue = 0; this.indentNext = 0; return s === "---" ? "doc" : "stream"; } } this.indentValue = yield* this.pushSpaces(false); if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) this.indentNext = this.indentValue; return yield* this.parseBlockStart(); } *parseBlockStart() { const [ch0, ch1] = this.peek(2); if (!ch1 && !this.atEnd) return this.setNext("block-start"); if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); this.indentNext = this.indentValue + 1; this.indentValue += n; return yield* this.parseBlockStart(); } return "doc"; } *parseDocument() { yield* this.pushSpaces(true); const line = this.getLine(); if (line === null) return this.setNext("doc"); let n = yield* this.pushIndicators(); switch (line[n]) { case "#": yield* this.pushCount(line.length - n); // fallthrough case void 0: yield* this.pushNewline(); return yield* this.parseLineStart(); case "{": case "[": yield* this.pushCount(1); this.flowKey = false; this.flowLevel = 1; return "flow"; case "}": case "]": yield* this.pushCount(1); return "doc"; case "*": yield* this.pushUntil(isNotAnchorChar); return "doc"; case '"': case "'": return yield* this.parseQuotedScalar(); case "|": case ">": n += yield* this.parseBlockScalarHeader(); n += yield* this.pushSpaces(true); yield* this.pushCount(line.length - n); yield* this.pushNewline(); return yield* this.parseBlockScalar(); default: return yield* this.parsePlainScalar(); } } *parseFlowCollection() { let nl, sp; let indent = -1; do { nl = yield* this.pushNewline(); if (nl > 0) { sp = yield* this.pushSpaces(false); this.indentValue = indent = sp; } else { sp = 0; } sp += yield* this.pushSpaces(true); } while (nl + sp > 0); const line = this.getLine(); if (line === null) return this.setNext("flow"); if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); if (!atFlowEndMarker) { this.flowLevel = 0; yield cst.FLOW_END; return yield* this.parseLineStart(); } } let n = 0; while (line[n] === ",") { n += yield* this.pushCount(1); n += yield* this.pushSpaces(true); this.flowKey = false; } n += yield* this.pushIndicators(); switch (line[n]) { case void 0: return "flow"; case "#": yield* this.pushCount(line.length - n); return "flow"; case "{": case "[": yield* this.pushCount(1); this.flowKey = false; this.flowLevel += 1; return "flow"; case "}": case "]": yield* this.pushCount(1); this.flowKey = true; this.flowLevel -= 1; return this.flowLevel ? "flow" : "doc"; case "*": yield* this.pushUntil(isNotAnchorChar); return "flow"; case '"': case "'": this.flowKey = true; return yield* this.parseQuotedScalar(); case ":": { const next = this.charAt(1); if (this.flowKey || isEmpty(next) || next === ",") { this.flowKey = false; yield* this.pushCount(1); yield* this.pushSpaces(true); return "flow"; } } // fallthrough default: this.flowKey = false; return yield* this.parsePlainScalar(); } } *parseQuotedScalar() { const quote = this.charAt(0); let end = this.buffer.indexOf(quote, this.pos + 1); if (quote === "'") { while (end !== -1 && this.buffer[end + 1] === "'") end = this.buffer.indexOf("'", end + 2); } else { while (end !== -1) { let n = 0; while (this.buffer[end - 1 - n] === "\\") n += 1; if (n % 2 === 0) break; end = this.buffer.indexOf('"', end + 1); } } const qb = this.buffer.substring(0, end); let nl = qb.indexOf("\n", this.pos); if (nl !== -1) { while (nl !== -1) { const cs = this.continueScalar(nl + 1); if (cs === -1) break; nl = qb.indexOf("\n", cs); } if (nl !== -1) { end = nl - (qb[nl - 1] === "\r" ? 2 : 1); } } if (end === -1) { if (!this.atEnd) return this.setNext("quoted-scalar"); end = this.buffer.length; } yield* this.pushToIndex(end + 1, false); return this.flowLevel ? "flow" : "doc"; } *parseBlockScalarHeader() { this.blockScalarIndent = -1; this.blockScalarKeep = false; let i = this.pos; while (true) { const ch = this.buffer[++i]; if (ch === "+") this.blockScalarKeep = true; else if (ch > "0" && ch <= "9") this.blockScalarIndent = Number(ch) - 1; else if (ch !== "-") break; } return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); } *parseBlockScalar() { let nl = this.pos - 1; let indent = 0; let ch; loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { switch (ch) { case " ": indent += 1; break; case "\n": nl = i2; indent = 0; break; case "\r": { const next = this.buffer[i2 + 1]; if (!next && !this.atEnd) return this.setNext("block-scalar"); if (next === "\n") break; } // fallthrough default: break loop; } } if (!ch && !this.atEnd) return this.setNext("block-scalar"); if (indent >= this.indentNext) { if (this.blockScalarIndent === -1) this.indentNext = indent; else { this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); } do { const cs = this.continueScalar(nl + 1); if (cs === -1) break; nl = this.buffer.indexOf("\n", cs); } while (nl !== -1); if (nl === -1) { if (!this.atEnd) return this.setNext("block-scalar"); nl = this.buffer.length; } } let i = nl + 1; ch = this.buffer[i]; while (ch === " ") ch = this.buffer[++i]; if (ch === " ") { while (ch === " " || ch === " " || ch === "\r" || ch === "\n") ch = this.buffer[++i]; nl = i - 1; } else if (!this.blockScalarKeep) { do { let i2 = nl - 1; let ch2 = this.buffer[i2]; if (ch2 === "\r") ch2 = this.buffer[--i2]; const lastChar = i2; while (ch2 === " ") ch2 = this.buffer[--i2]; if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) nl = i2; else break; } while (true); } yield cst.SCALAR; yield* this.pushToIndex(nl + 1, true); return yield* this.parseLineStart(); } *parsePlainScalar() { const inFlow = this.flowLevel > 0; let end = this.pos - 1; let i = this.pos - 1; let ch; while (ch = this.buffer[++i]) { if (ch === ":") { const next = this.buffer[i + 1]; if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) break; end = i; } else if (isEmpty(ch)) { let next = this.buffer[i + 1]; if (ch === "\r") { if (next === "\n") { i += 1; ch = "\n"; next = this.buffer[i + 1]; } else end = i; } if (next === "#" || inFlow && flowIndicatorChars.has(next)) break; if (ch === "\n") { const cs = this.continueScalar(i + 1); if (cs === -1) break; i = Math.max(i, cs - 2); } } else { if (inFlow && flowIndicatorChars.has(ch)) break; end = i; } } if (!ch && !this.atEnd) return this.setNext("plain-scalar"); yield cst.SCALAR; yield* this.pushToIndex(end + 1, true); return inFlow ? "flow" : "doc"; } *pushCount(n) { if (n > 0) { yield this.buffer.substr(this.pos, n); this.pos += n; return n; } return 0; } *pushToIndex(i, allowEmpty) { const s = this.buffer.slice(this.pos, i); if (s) { yield s; this.pos += s.length; return s.length; } else if (allowEmpty) yield ""; return 0; } *pushIndicators() { switch (this.charAt(0)) { case "!": return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); case "&": return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); case "-": // this is an error case "?": // this is an error outside flow collections case ":": { const inFlow = this.flowLevel > 0; const ch1 = this.charAt(1); if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { if (!inFlow) this.indentNext = this.indentValue + 1; else if (this.flowKey) this.flowKey = false; return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); } } } return 0; } *pushTag() { if (this.charAt(1) === "<") { let i = this.pos + 2; let ch = this.buffer[i]; while (!isEmpty(ch) && ch !== ">") ch = this.buffer[++i]; return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); } else { let i = this.pos + 1; let ch = this.buffer[i]; while (ch) { if (tagChars.has(ch)) ch = this.buffer[++i]; else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { ch = this.buffer[i += 3]; } else break; } return yield* this.pushToIndex(i, false); } } *pushNewline() { const ch = this.buffer[this.pos]; if (ch === "\n") return yield* this.pushCount(1); else if (ch === "\r" && this.charAt(1) === "\n") return yield* this.pushCount(2); else return 0; } *pushSpaces(allowTabs) { let i = this.pos - 1; let ch; do { ch = this.buffer[++i]; } while (ch === " " || allowTabs && ch === " "); const n = i - this.pos; if (n > 0) { yield this.buffer.substr(this.pos, n); this.pos = i; } return n; } *pushUntil(test) { let i = this.pos; let ch = this.buffer[i]; while (!test(ch)) ch = this.buffer[++i]; return yield* this.pushToIndex(i, false); } }; exports2.Lexer = Lexer; } }); // node_modules/yaml/dist/parse/line-counter.js var require_line_counter = __commonJS({ "node_modules/yaml/dist/parse/line-counter.js"(exports2) { "use strict"; var LineCounter = class { constructor() { this.lineStarts = []; this.addNewLine = (offset) => this.lineStarts.push(offset); this.linePos = (offset) => { let low = 0; let high = this.lineStarts.length; while (low < high) { const mid = low + high >> 1; if (this.lineStarts[mid] < offset) low = mid + 1; else high = mid; } if (this.lineStarts[low] === offset) return { line: low + 1, col: 1 }; if (low === 0) return { line: 0, col: offset }; const start = this.lineStarts[low - 1]; return { line: low, col: offset - start + 1 }; }; } }; exports2.LineCounter = LineCounter; } }); // node_modules/yaml/dist/parse/parser.js var require_parser2 = __commonJS({ "node_modules/yaml/dist/parse/parser.js"(exports2) { "use strict"; var node_process = require("process"); var cst = require_cst(); var lexer = require_lexer(); function includesToken(list, type) { for (let i = 0; i < list.length; ++i) if (list[i].type === type) return true; return false; } function findNonEmptyIndex(list) { for (let i = 0; i < list.length; ++i) { switch (list[i].type) { case "space": case "comment": case "newline": break; default: return i; } } return -1; } function isFlowToken(token) { switch (token?.type) { case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": case "flow-collection": return true; default: return false; } } function getPrevProps(parent) { switch (parent.type) { case "document": return parent.start; case "block-map": { const it = parent.items[parent.items.length - 1]; return it.sep ?? it.start; } case "block-seq": return parent.items[parent.items.length - 1].start; /* istanbul ignore next should not happen */ default: return []; } } function getFirstKeyStartProps(prev) { if (prev.length === 0) return []; let i = prev.length; loop: while (--i >= 0) { switch (prev[i].type) { case "doc-start": case "explicit-key-ind": case "map-value-ind": case "seq-item-ind": case "newline": break loop; } } while (prev[++i]?.type === "space") { } return prev.splice(i, prev.length); } function fixFlowSeqItems(fc) { if (fc.start.type === "flow-seq-start") { for (const it of fc.items) { if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { if (it.key) it.value = it.key; delete it.key; if (isFlowToken(it.value)) { if (it.value.end) Array.prototype.push.apply(it.value.end, it.sep); else it.value.end = it.sep; } else Array.prototype.push.apply(it.start, it.sep); delete it.sep; } } } } var Parser = class { /** * @param onNewLine - If defined, called separately with the start position of * each new line (in `parse()`, including the start of input). */ constructor(onNewLine) { this.atNewLine = true; this.atScalar = false; this.indent = 0; this.offset = 0; this.onKeyLine = false; this.stack = []; this.source = ""; this.type = ""; this.lexer = new lexer.Lexer(); this.onNewLine = onNewLine; } /** * Parse `source` as a YAML stream. * If `incomplete`, a part of the last line may be left as a buffer for the next call. * * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. * * @returns A generator of tokens representing each directive, document, and other structure. */ *parse(source, incomplete = false) { if (this.onNewLine && this.offset === 0) this.onNewLine(0); for (const lexeme of this.lexer.lex(source, incomplete)) yield* this.next(lexeme); if (!incomplete) yield* this.end(); } /** * Advance the parser by the `source` of one lexical token. */ *next(source) { this.source = source; if (node_process.env.LOG_TOKENS) console.log("|", cst.prettyToken(source)); if (this.atScalar) { this.atScalar = false; yield* this.step(); this.offset += source.length; return; } const type = cst.tokenType(source); if (!type) { const message = `Not a YAML token: ${source}`; yield* this.pop({ type: "error", offset: this.offset, message, source }); this.offset += source.length; } else if (type === "scalar") { this.atNewLine = false; this.atScalar = true; this.type = "scalar"; } else { this.type = type; yield* this.step(); switch (type) { case "newline": this.atNewLine = true; this.indent = 0; if (this.onNewLine) this.onNewLine(this.offset + source.length); break; case "space": if (this.atNewLine && source[0] === " ") this.indent += source.length; break; case "explicit-key-ind": case "map-value-ind": case "seq-item-ind": if (this.atNewLine) this.indent += source.length; break; case "doc-mode": case "flow-error-end": return; default: this.atNewLine = false; } this.offset += source.length; } } /** Call at end of input to push out any remaining constructions */ *end() { while (this.stack.length > 0) yield* this.pop(); } get sourceToken() { const st = { type: this.type, offset: this.offset, indent: this.indent, source: this.source }; return st; } *step() { const top = this.peek(1); if (this.type === "doc-end" && top?.type !== "doc-end") { while (this.stack.length > 0) yield* this.pop(); this.stack.push({ type: "doc-end", offset: this.offset, source: this.source }); return; } if (!top) return yield* this.stream(); switch (top.type) { case "document": return yield* this.document(top); case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": return yield* this.scalar(top); case "block-scalar": return yield* this.blockScalar(top); case "block-map": return yield* this.blockMap(top); case "block-seq": return yield* this.blockSequence(top); case "flow-collection": return yield* this.flowCollection(top); case "doc-end": return yield* this.documentEnd(top); } yield* this.pop(); } peek(n) { return this.stack[this.stack.length - n]; } *pop(error48) { const token = error48 ?? this.stack.pop(); if (!token) { const message = "Tried to pop an empty stack"; yield { type: "error", offset: this.offset, source: "", message }; } else if (this.stack.length === 0) { yield token; } else { const top = this.peek(1); if (token.type === "block-scalar") { token.indent = "indent" in top ? top.indent : 0; } else if (token.type === "flow-collection" && top.type === "document") { token.indent = 0; } if (token.type === "flow-collection") fixFlowSeqItems(token); switch (top.type) { case "document": top.value = token; break; case "block-scalar": top.props.push(token); break; case "block-map": { const it = top.items[top.items.length - 1]; if (it.value) { top.items.push({ start: [], key: token, sep: [] }); this.onKeyLine = true; return; } else if (it.sep) { it.value = token; } else { Object.assign(it, { key: token, sep: [] }); this.onKeyLine = !it.explicitKey; return; } break; } case "block-seq": { const it = top.items[top.items.length - 1]; if (it.value) top.items.push({ start: [], value: token }); else it.value = token; break; } case "flow-collection": { const it = top.items[top.items.length - 1]; if (!it || it.value) top.items.push({ start: [], key: token, sep: [] }); else if (it.sep) it.value = token; else Object.assign(it, { key: token, sep: [] }); return; } /* istanbul ignore next should not happen */ default: yield* this.pop(); yield* this.pop(token); } if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { const last = token.items[token.items.length - 1]; if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { if (top.type === "document") top.end = last.start; else top.items.push({ start: last.start }); token.items.splice(-1, 1); } } } } *stream() { switch (this.type) { case "directive-line": yield { type: "directive", offset: this.offset, source: this.source }; return; case "byte-order-mark": case "space": case "comment": case "newline": yield this.sourceToken; return; case "doc-mode": case "doc-start": { const doc = { type: "document", offset: this.offset, start: [] }; if (this.type === "doc-start") doc.start.push(this.sourceToken); this.stack.push(doc); return; } } yield { type: "error", offset: this.offset, message: `Unexpected ${this.type} token in YAML stream`, source: this.source }; } *document(doc) { if (doc.value) return yield* this.lineEnd(doc); switch (this.type) { case "doc-start": { if (findNonEmptyIndex(doc.start) !== -1) { yield* this.pop(); yield* this.step(); } else doc.start.push(this.sourceToken); return; } case "anchor": case "tag": case "space": case "comment": case "newline": doc.start.push(this.sourceToken); return; } const bv = this.startBlockValue(doc); if (bv) this.stack.push(bv); else { yield { type: "error", offset: this.offset, message: `Unexpected ${this.type} token in YAML document`, source: this.source }; } } *scalar(scalar) { if (this.type === "map-value-ind") { const prev = getPrevProps(this.peek(2)); const start = getFirstKeyStartProps(prev); let sep; if (scalar.end) { sep = scalar.end; sep.push(this.sourceToken); delete scalar.end; } else sep = [this.sourceToken]; const map2 = { type: "block-map", offset: scalar.offset, indent: scalar.indent, items: [{ start, key: scalar, sep }] }; this.onKeyLine = true; this.stack[this.stack.length - 1] = map2; } else yield* this.lineEnd(scalar); } *blockScalar(scalar) { switch (this.type) { case "space": case "comment": case "newline": scalar.props.push(this.sourceToken); return; case "scalar": scalar.source = this.source; this.atNewLine = true; this.indent = 0; if (this.onNewLine) { let nl = this.source.indexOf("\n") + 1; while (nl !== 0) { this.onNewLine(this.offset + nl); nl = this.source.indexOf("\n", nl) + 1; } } yield* this.pop(); break; /* istanbul ignore next should not happen */ default: yield* this.pop(); yield* this.step(); } } *blockMap(map2) { const it = map2.items[map2.items.length - 1]; switch (this.type) { case "newline": this.onKeyLine = false; if (it.value) { const end = "end" in it.value ? it.value.end : void 0; const last = Array.isArray(end) ? end[end.length - 1] : void 0; if (last?.type === "comment") end?.push(this.sourceToken); else map2.items.push({ start: [this.sourceToken] }); } else if (it.sep) { it.sep.push(this.sourceToken); } else { it.start.push(this.sourceToken); } return; case "space": case "comment": if (it.value) { map2.items.push({ start: [this.sourceToken] }); } else if (it.sep) { it.sep.push(this.sourceToken); } else { if (this.atIndentedComment(it.start, map2.indent)) { const prev = map2.items[map2.items.length - 2]; const end = prev?.value?.end; if (Array.isArray(end)) { Array.prototype.push.apply(end, it.start); end.push(this.sourceToken); map2.items.pop(); return; } } it.start.push(this.sourceToken); } return; } if (this.indent >= map2.indent) { const atMapIndent = !this.onKeyLine && this.indent === map2.indent; const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; let start = []; if (atNextItem && it.sep && !it.value) { const nl = []; for (let i = 0; i < it.sep.length; ++i) { const st = it.sep[i]; switch (st.type) { case "newline": nl.push(i); break; case "space": break; case "comment": if (st.indent > map2.indent) nl.length = 0; break; default: nl.length = 0; } } if (nl.length >= 2) start = it.sep.splice(nl[1]); } switch (this.type) { case "anchor": case "tag": if (atNextItem || it.value) { start.push(this.sourceToken); map2.items.push({ start }); this.onKeyLine = true; } else if (it.sep) { it.sep.push(this.sourceToken); } else { it.start.push(this.sourceToken); } return; case "explicit-key-ind": if (!it.sep && !it.explicitKey) { it.start.push(this.sourceToken); it.explicitKey = true; } else if (atNextItem || it.value) { start.push(this.sourceToken); map2.items.push({ start, explicitKey: true }); } else { this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: [this.sourceToken], explicitKey: true }] }); } this.onKeyLine = true; return; case "map-value-ind": if (it.explicitKey) { if (!it.sep) { if (includesToken(it.start, "newline")) { Object.assign(it, { key: null, sep: [this.sourceToken] }); } else { const start2 = getFirstKeyStartProps(it.start); this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: start2, key: null, sep: [this.sourceToken] }] }); } } else if (it.value) { map2.items.push({ start: [], key: null, sep: [this.sourceToken] }); } else if (includesToken(it.sep, "map-value-ind")) { this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start, key: null, sep: [this.sourceToken] }] }); } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { const start2 = getFirstKeyStartProps(it.start); const key = it.key; const sep = it.sep; sep.push(this.sourceToken); delete it.key; delete it.sep; this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: start2, key, sep }] }); } else if (start.length > 0) { it.sep = it.sep.concat(start, this.sourceToken); } else { it.sep.push(this.sourceToken); } } else { if (!it.sep) { Object.assign(it, { key: null, sep: [this.sourceToken] }); } else if (it.value || atNextItem) { map2.items.push({ start, key: null, sep: [this.sourceToken] }); } else if (includesToken(it.sep, "map-value-ind")) { this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: [], key: null, sep: [this.sourceToken] }] }); } else { it.sep.push(this.sourceToken); } } this.onKeyLine = true; return; case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { const fs = this.flowScalar(this.type); if (atNextItem || it.value) { map2.items.push({ start, key: fs, sep: [] }); this.onKeyLine = true; } else if (it.sep) { this.stack.push(fs); } else { Object.assign(it, { key: fs, sep: [] }); this.onKeyLine = true; } return; } default: { const bv = this.startBlockValue(map2); if (bv) { if (bv.type === "block-seq") { if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { yield* this.pop({ type: "error", offset: this.offset, message: "Unexpected block-seq-ind on same line with key", source: this.source }); return; } } else if (atMapIndent) { map2.items.push({ start }); } this.stack.push(bv); return; } } } } yield* this.pop(); yield* this.step(); } *blockSequence(seq) { const it = seq.items[seq.items.length - 1]; switch (this.type) { case "newline": if (it.value) { const end = "end" in it.value ? it.value.end : void 0; const last = Array.isArray(end) ? end[end.length - 1] : void 0; if (last?.type === "comment") end?.push(this.sourceToken); else seq.items.push({ start: [this.sourceToken] }); } else it.start.push(this.sourceToken); return; case "space": case "comment": if (it.value) seq.items.push({ start: [this.sourceToken] }); else { if (this.atIndentedComment(it.start, seq.indent)) { const prev = seq.items[seq.items.length - 2]; const end = prev?.value?.end; if (Array.isArray(end)) { Array.prototype.push.apply(end, it.start); end.push(this.sourceToken); seq.items.pop(); return; } } it.start.push(this.sourceToken); } return; case "anchor": case "tag": if (it.value || this.indent <= seq.indent) break; it.start.push(this.sourceToken); return; case "seq-item-ind": if (this.indent !== seq.indent) break; if (it.value || includesToken(it.start, "seq-item-ind")) seq.items.push({ start: [this.sourceToken] }); else it.start.push(this.sourceToken); return; } if (this.indent > seq.indent) { const bv = this.startBlockValue(seq); if (bv) { this.stack.push(bv); return; } } yield* this.pop(); yield* this.step(); } *flowCollection(fc) { const it = fc.items[fc.items.length - 1]; if (this.type === "flow-error-end") { let top; do { yield* this.pop(); top = this.peek(1); } while (top?.type === "flow-collection"); } else if (fc.end.length === 0) { switch (this.type) { case "comma": case "explicit-key-ind": if (!it || it.sep) fc.items.push({ start: [this.sourceToken] }); else it.start.push(this.sourceToken); return; case "map-value-ind": if (!it || it.value) fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); else if (it.sep) it.sep.push(this.sourceToken); else Object.assign(it, { key: null, sep: [this.sourceToken] }); return; case "space": case "comment": case "newline": case "anchor": case "tag": if (!it || it.value) fc.items.push({ start: [this.sourceToken] }); else if (it.sep) it.sep.push(this.sourceToken); else it.start.push(this.sourceToken); return; case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { const fs = this.flowScalar(this.type); if (!it || it.value) fc.items.push({ start: [], key: fs, sep: [] }); else if (it.sep) this.stack.push(fs); else Object.assign(it, { key: fs, sep: [] }); return; } case "flow-map-end": case "flow-seq-end": fc.end.push(this.sourceToken); return; } const bv = this.startBlockValue(fc); if (bv) this.stack.push(bv); else { yield* this.pop(); yield* this.step(); } } else { const parent = this.peek(2); if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { yield* this.pop(); yield* this.step(); } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { const prev = getPrevProps(parent); const start = getFirstKeyStartProps(prev); fixFlowSeqItems(fc); const sep = fc.end.splice(1, fc.end.length); sep.push(this.sourceToken); const map2 = { type: "block-map", offset: fc.offset, indent: fc.indent, items: [{ start, key: fc, sep }] }; this.onKeyLine = true; this.stack[this.stack.length - 1] = map2; } else { yield* this.lineEnd(fc); } } } flowScalar(type) { if (this.onNewLine) { let nl = this.source.indexOf("\n") + 1; while (nl !== 0) { this.onNewLine(this.offset + nl); nl = this.source.indexOf("\n", nl) + 1; } } return { type, offset: this.offset, indent: this.indent, source: this.source }; } startBlockValue(parent) { switch (this.type) { case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": return this.flowScalar(this.type); case "block-scalar-header": return { type: "block-scalar", offset: this.offset, indent: this.indent, props: [this.sourceToken], source: "" }; case "flow-map-start": case "flow-seq-start": return { type: "flow-collection", offset: this.offset, indent: this.indent, start: this.sourceToken, items: [], end: [] }; case "seq-item-ind": return { type: "block-seq", offset: this.offset, indent: this.indent, items: [{ start: [this.sourceToken] }] }; case "explicit-key-ind": { this.onKeyLine = true; const prev = getPrevProps(parent); const start = getFirstKeyStartProps(prev); start.push(this.sourceToken); return { type: "block-map", offset: this.offset, indent: this.indent, items: [{ start, explicitKey: true }] }; } case "map-value-ind": { this.onKeyLine = true; const prev = getPrevProps(parent); const start = getFirstKeyStartProps(prev); return { type: "block-map", offset: this.offset, indent: this.indent, items: [{ start, key: null, sep: [this.sourceToken] }] }; } } return null; } atIndentedComment(start, indent) { if (this.type !== "comment") return false; if (this.indent <= indent) return false; return start.every((st) => st.type === "newline" || st.type === "space"); } *documentEnd(docEnd) { if (this.type !== "doc-mode") { if (docEnd.end) docEnd.end.push(this.sourceToken); else docEnd.end = [this.sourceToken]; if (this.type === "newline") yield* this.pop(); } } *lineEnd(token) { switch (this.type) { case "comma": case "doc-start": case "doc-end": case "flow-seq-end": case "flow-map-end": case "map-value-ind": yield* this.pop(); yield* this.step(); break; case "newline": this.onKeyLine = false; // fallthrough case "space": case "comment": default: if (token.end) token.end.push(this.sourceToken); else token.end = [this.sourceToken]; if (this.type === "newline") yield* this.pop(); } } }; exports2.Parser = Parser; } }); // node_modules/yaml/dist/public-api.js var require_public_api = __commonJS({ "node_modules/yaml/dist/public-api.js"(exports2) { "use strict"; var composer = require_composer(); var Document = require_Document(); var errors = require_errors(); var log = require_log(); var identity = require_identity(); var lineCounter = require_line_counter(); var parser = require_parser2(); function parseOptions(options) { const prettyErrors = options.prettyErrors !== false; const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null; return { lineCounter: lineCounter$1, prettyErrors }; } function parseAllDocuments(source, options = {}) { const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); const parser$1 = new parser.Parser(lineCounter2?.addNewLine); const composer$1 = new composer.Composer(options); const docs = Array.from(composer$1.compose(parser$1.parse(source))); if (prettyErrors && lineCounter2) for (const doc of docs) { doc.errors.forEach(errors.prettifyError(source, lineCounter2)); doc.warnings.forEach(errors.prettifyError(source, lineCounter2)); } if (docs.length > 0) return docs; return Object.assign([], { empty: true }, composer$1.streamInfo()); } function parseDocument(source, options = {}) { const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); const parser$1 = new parser.Parser(lineCounter2?.addNewLine); const composer$1 = new composer.Composer(options); let doc = null; for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) { if (!doc) doc = _doc; else if (doc.options.logLevel !== "silent") { doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); break; } } if (prettyErrors && lineCounter2) { doc.errors.forEach(errors.prettifyError(source, lineCounter2)); doc.warnings.forEach(errors.prettifyError(source, lineCounter2)); } return doc; } function parse3(src, reviver, options) { let _reviver = void 0; if (typeof reviver === "function") { _reviver = reviver; } else if (options === void 0 && reviver && typeof reviver === "object") { options = reviver; } const doc = parseDocument(src, options); if (!doc) return null; doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning)); if (doc.errors.length > 0) { if (doc.options.logLevel !== "silent") throw doc.errors[0]; else doc.errors = []; } return doc.toJS(Object.assign({ reviver: _reviver }, options)); } function stringify(value, replacer, options) { let _replacer = null; if (typeof replacer === "function" || Array.isArray(replacer)) { _replacer = replacer; } else if (options === void 0 && replacer) { options = replacer; } if (typeof options === "string") options = options.length; if (typeof options === "number") { const indent = Math.round(options); options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; } if (value === void 0) { const { keepUndefined } = options ?? replacer ?? {}; if (!keepUndefined) return void 0; } if (identity.isDocument(value) && !_replacer) return value.toString(options); return new Document.Document(value, _replacer, options).toString(options); } exports2.parse = parse3; exports2.parseAllDocuments = parseAllDocuments; exports2.parseDocument = parseDocument; exports2.stringify = stringify; } }); // node_modules/yaml/dist/index.js var require_dist4 = __commonJS({ "node_modules/yaml/dist/index.js"(exports2) { "use strict"; var composer = require_composer(); var Document = require_Document(); var Schema = require_Schema(); var errors = require_errors(); var Alias = require_Alias(); var identity = require_identity(); var Pair = require_Pair(); var Scalar = require_Scalar(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var cst = require_cst(); var lexer = require_lexer(); var lineCounter = require_line_counter(); var parser = require_parser2(); var publicApi = require_public_api(); var visit = require_visit(); exports2.Composer = composer.Composer; exports2.Document = Document.Document; exports2.Schema = Schema.Schema; exports2.YAMLError = errors.YAMLError; exports2.YAMLParseError = errors.YAMLParseError; exports2.YAMLWarning = errors.YAMLWarning; exports2.Alias = Alias.Alias; exports2.isAlias = identity.isAlias; exports2.isCollection = identity.isCollection; exports2.isDocument = identity.isDocument; exports2.isMap = identity.isMap; exports2.isNode = identity.isNode; exports2.isPair = identity.isPair; exports2.isScalar = identity.isScalar; exports2.isSeq = identity.isSeq; exports2.Pair = Pair.Pair; exports2.Scalar = Scalar.Scalar; exports2.YAMLMap = YAMLMap.YAMLMap; exports2.YAMLSeq = YAMLSeq.YAMLSeq; exports2.CST = cst; exports2.Lexer = lexer.Lexer; exports2.LineCounter = lineCounter.LineCounter; exports2.Parser = parser.Parser; exports2.parse = publicApi.parse; exports2.parseAllDocuments = publicApi.parseAllDocuments; exports2.parseDocument = publicApi.parseDocument; exports2.stringify = publicApi.stringify; exports2.visit = visit.visit; exports2.visitAsync = visit.visitAsync; } }); // node_modules/json5/lib/unicode.js var require_unicode = __commonJS({ "node_modules/json5/lib/unicode.js"(exports2, module2) { module2.exports.Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; module2.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]/; module2.exports.ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; } }); // node_modules/json5/lib/util.js var require_util2 = __commonJS({ "node_modules/json5/lib/util.js"(exports2, module2) { var unicode = require_unicode(); module2.exports = { isSpaceSeparator(c) { return typeof c === "string" && unicode.Space_Separator.test(c); }, isIdStartChar(c) { return typeof c === "string" && (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "$" || c === "_" || unicode.ID_Start.test(c)); }, isIdContinueChar(c) { return typeof c === "string" && (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c >= "0" && c <= "9" || c === "$" || c === "_" || c === "\u200C" || c === "\u200D" || unicode.ID_Continue.test(c)); }, isDigit(c) { return typeof c === "string" && /[0-9]/.test(c); }, isHexDigit(c) { return typeof c === "string" && /[0-9A-Fa-f]/.test(c); } }; } }); // node_modules/json5/lib/parse.js var require_parse = __commonJS({ "node_modules/json5/lib/parse.js"(exports2, module2) { var util2 = require_util2(); var source; var parseState; var stack; var pos; var line; var column; var token; var key; var root; module2.exports = function parse3(text, reviver) { source = String(text); parseState = "start"; stack = []; pos = 0; line = 1; column = 0; token = void 0; key = void 0; root = void 0; do { token = lex(); parseStates[parseState](); } while (token.type !== "eof"); if (typeof reviver === "function") { return internalize({ "": root }, "", reviver); } return root; }; function internalize(holder, name, reviver) { const value = holder[name]; if (value != null && typeof value === "object") { if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { const key2 = String(i); const replacement = internalize(value, key2, reviver); if (replacement === void 0) { delete value[key2]; } else { Object.defineProperty(value, key2, { value: replacement, writable: true, enumerable: true, configurable: true }); } } } else { for (const key2 in value) { const replacement = internalize(value, key2, reviver); if (replacement === void 0) { delete value[key2]; } else { Object.defineProperty(value, key2, { value: replacement, writable: true, enumerable: true, configurable: true }); } } } } return reviver.call(holder, name, value); } var lexState; var buffer; var doubleQuote; var sign; var c; function lex() { lexState = "default"; buffer = ""; doubleQuote = false; sign = 1; for (; ; ) { c = peek(); const token2 = lexStates[lexState](); if (token2) { return token2; } } } function peek() { if (source[pos]) { return String.fromCodePoint(source.codePointAt(pos)); } } function read() { const c2 = peek(); if (c2 === "\n") { line++; column = 0; } else if (c2) { column += c2.length; } else { column++; } if (c2) { pos += c2.length; } return c2; } var lexStates = { default() { switch (c) { case " ": case "\v": case "\f": case " ": case "\xA0": case "\uFEFF": case "\n": case "\r": case "\u2028": case "\u2029": read(); return; case "/": read(); lexState = "comment"; return; case void 0: read(); return newToken("eof"); } if (util2.isSpaceSeparator(c)) { read(); return; } return lexStates[parseState](); }, comment() { switch (c) { case "*": read(); lexState = "multiLineComment"; return; case "/": read(); lexState = "singleLineComment"; return; } throw invalidChar(read()); }, multiLineComment() { switch (c) { case "*": read(); lexState = "multiLineCommentAsterisk"; return; case void 0: throw invalidChar(read()); } read(); }, multiLineCommentAsterisk() { switch (c) { case "*": read(); return; case "/": read(); lexState = "default"; return; case void 0: throw invalidChar(read()); } read(); lexState = "multiLineComment"; }, singleLineComment() { switch (c) { case "\n": case "\r": case "\u2028": case "\u2029": read(); lexState = "default"; return; case void 0: read(); return newToken("eof"); } read(); }, value() { switch (c) { case "{": case "[": return newToken("punctuator", read()); case "n": read(); literal2("ull"); return newToken("null", null); case "t": read(); literal2("rue"); return newToken("boolean", true); case "f": read(); literal2("alse"); return newToken("boolean", false); case "-": case "+": if (read() === "-") { sign = -1; } lexState = "sign"; return; case ".": buffer = read(); lexState = "decimalPointLeading"; return; case "0": buffer = read(); lexState = "zero"; return; case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": buffer = read(); lexState = "decimalInteger"; return; case "I": read(); literal2("nfinity"); return newToken("numeric", Infinity); case "N": read(); literal2("aN"); return newToken("numeric", NaN); case '"': case "'": doubleQuote = read() === '"'; buffer = ""; lexState = "string"; return; } throw invalidChar(read()); }, identifierNameStartEscape() { if (c !== "u") { throw invalidChar(read()); } read(); const u = unicodeEscape(); switch (u) { case "$": case "_": break; default: if (!util2.isIdStartChar(u)) { throw invalidIdentifier(); } break; } buffer += u; lexState = "identifierName"; }, identifierName() { switch (c) { case "$": case "_": case "\u200C": case "\u200D": buffer += read(); return; case "\\": read(); lexState = "identifierNameEscape"; return; } if (util2.isIdContinueChar(c)) { buffer += read(); return; } return newToken("identifier", buffer); }, identifierNameEscape() { if (c !== "u") { throw invalidChar(read()); } read(); const u = unicodeEscape(); switch (u) { case "$": case "_": case "\u200C": case "\u200D": break; default: if (!util2.isIdContinueChar(u)) { throw invalidIdentifier(); } break; } buffer += u; lexState = "identifierName"; }, sign() { switch (c) { case ".": buffer = read(); lexState = "decimalPointLeading"; return; case "0": buffer = read(); lexState = "zero"; return; case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": buffer = read(); lexState = "decimalInteger"; return; case "I": read(); literal2("nfinity"); return newToken("numeric", sign * Infinity); case "N": read(); literal2("aN"); return newToken("numeric", NaN); } throw invalidChar(read()); }, zero() { switch (c) { case ".": buffer += read(); lexState = "decimalPoint"; return; case "e": case "E": buffer += read(); lexState = "decimalExponent"; return; case "x": case "X": buffer += read(); lexState = "hexadecimal"; return; } return newToken("numeric", sign * 0); }, decimalInteger() { switch (c) { case ".": buffer += read(); lexState = "decimalPoint"; return; case "e": case "E": buffer += read(); lexState = "decimalExponent"; return; } if (util2.isDigit(c)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, decimalPointLeading() { if (util2.isDigit(c)) { buffer += read(); lexState = "decimalFraction"; return; } throw invalidChar(read()); }, decimalPoint() { switch (c) { case "e": case "E": buffer += read(); lexState = "decimalExponent"; return; } if (util2.isDigit(c)) { buffer += read(); lexState = "decimalFraction"; return; } return newToken("numeric", sign * Number(buffer)); }, decimalFraction() { switch (c) { case "e": case "E": buffer += read(); lexState = "decimalExponent"; return; } if (util2.isDigit(c)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, decimalExponent() { switch (c) { case "+": case "-": buffer += read(); lexState = "decimalExponentSign"; return; } if (util2.isDigit(c)) { buffer += read(); lexState = "decimalExponentInteger"; return; } throw invalidChar(read()); }, decimalExponentSign() { if (util2.isDigit(c)) { buffer += read(); lexState = "decimalExponentInteger"; return; } throw invalidChar(read()); }, decimalExponentInteger() { if (util2.isDigit(c)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, hexadecimal() { if (util2.isHexDigit(c)) { buffer += read(); lexState = "hexadecimalInteger"; return; } throw invalidChar(read()); }, hexadecimalInteger() { if (util2.isHexDigit(c)) { buffer += read(); return; } return newToken("numeric", sign * Number(buffer)); }, string() { switch (c) { case "\\": read(); buffer += escape2(); return; case '"': if (doubleQuote) { read(); return newToken("string", buffer); } buffer += read(); return; case "'": if (!doubleQuote) { read(); return newToken("string", buffer); } buffer += read(); return; case "\n": case "\r": throw invalidChar(read()); case "\u2028": case "\u2029": separatorChar(c); break; case void 0: throw invalidChar(read()); } buffer += read(); }, start() { switch (c) { case "{": case "[": return newToken("punctuator", read()); } lexState = "value"; }, beforePropertyName() { switch (c) { case "$": case "_": buffer = read(); lexState = "identifierName"; return; case "\\": read(); lexState = "identifierNameStartEscape"; return; case "}": return newToken("punctuator", read()); case '"': case "'": doubleQuote = read() === '"'; lexState = "string"; return; } if (util2.isIdStartChar(c)) { buffer += read(); lexState = "identifierName"; return; } throw invalidChar(read()); }, afterPropertyName() { if (c === ":") { return newToken("punctuator", read()); } throw invalidChar(read()); }, beforePropertyValue() { lexState = "value"; }, afterPropertyValue() { switch (c) { case ",": case "}": return newToken("punctuator", read()); } throw invalidChar(read()); }, beforeArrayValue() { if (c === "]") { return newToken("punctuator", read()); } lexState = "value"; }, afterArrayValue() { switch (c) { case ",": case "]": return newToken("punctuator", read()); } throw invalidChar(read()); }, end() { throw invalidChar(read()); } }; function newToken(type, value) { return { type, value, line, column }; } function literal2(s) { for (const c2 of s) { const p = peek(); if (p !== c2) { throw invalidChar(read()); } read(); } } function escape2() { const c2 = peek(); switch (c2) { case "b": read(); return "\b"; case "f": read(); return "\f"; case "n": read(); return "\n"; case "r": read(); return "\r"; case "t": read(); return " "; case "v": read(); return "\v"; case "0": read(); if (util2.isDigit(peek())) { throw invalidChar(read()); } return "\0"; case "x": read(); return hexEscape(); case "u": read(); return unicodeEscape(); case "\n": case "\u2028": case "\u2029": read(); return ""; case "\r": read(); if (peek() === "\n") { read(); } return ""; case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": throw invalidChar(read()); case void 0: throw invalidChar(read()); } return read(); } function hexEscape() { let buffer2 = ""; let c2 = peek(); if (!util2.isHexDigit(c2)) { throw invalidChar(read()); } buffer2 += read(); c2 = peek(); if (!util2.isHexDigit(c2)) { throw invalidChar(read()); } buffer2 += read(); return String.fromCodePoint(parseInt(buffer2, 16)); } function unicodeEscape() { let buffer2 = ""; let count = 4; while (count-- > 0) { const c2 = peek(); if (!util2.isHexDigit(c2)) { throw invalidChar(read()); } buffer2 += read(); } return String.fromCodePoint(parseInt(buffer2, 16)); } var parseStates = { start() { if (token.type === "eof") { throw invalidEOF(); } push(); }, beforePropertyName() { switch (token.type) { case "identifier": case "string": key = token.value; parseState = "afterPropertyName"; return; case "punctuator": pop(); return; case "eof": throw invalidEOF(); } }, afterPropertyName() { if (token.type === "eof") { throw invalidEOF(); } parseState = "beforePropertyValue"; }, beforePropertyValue() { if (token.type === "eof") { throw invalidEOF(); } push(); }, beforeArrayValue() { if (token.type === "eof") { throw invalidEOF(); } if (token.type === "punctuator" && token.value === "]") { pop(); return; } push(); }, afterPropertyValue() { if (token.type === "eof") { throw invalidEOF(); } switch (token.value) { case ",": parseState = "beforePropertyName"; return; case "}": pop(); } }, afterArrayValue() { if (token.type === "eof") { throw invalidEOF(); } switch (token.value) { case ",": parseState = "beforeArrayValue"; return; case "]": pop(); } }, end() { } }; function push() { let value; switch (token.type) { case "punctuator": switch (token.value) { case "{": value = {}; break; case "[": value = []; break; } break; case "null": case "boolean": case "numeric": case "string": value = token.value; break; } if (root === void 0) { root = value; } else { const parent = stack[stack.length - 1]; if (Array.isArray(parent)) { parent.push(value); } else { Object.defineProperty(parent, key, { value, writable: true, enumerable: true, configurable: true }); } } if (value !== null && typeof value === "object") { stack.push(value); if (Array.isArray(value)) { parseState = "beforeArrayValue"; } else { parseState = "beforePropertyName"; } } else { const current = stack[stack.length - 1]; if (current == null) { parseState = "end"; } else if (Array.isArray(current)) { parseState = "afterArrayValue"; } else { parseState = "afterPropertyValue"; } } } function pop() { stack.pop(); const current = stack[stack.length - 1]; if (current == null) { parseState = "end"; } else if (Array.isArray(current)) { parseState = "afterArrayValue"; } else { parseState = "afterPropertyValue"; } } function invalidChar(c2) { if (c2 === void 0) { return syntaxError2(`JSON5: invalid end of input at ${line}:${column}`); } return syntaxError2(`JSON5: invalid character '${formatChar(c2)}' at ${line}:${column}`); } function invalidEOF() { return syntaxError2(`JSON5: invalid end of input at ${line}:${column}`); } function invalidIdentifier() { column -= 5; return syntaxError2(`JSON5: invalid identifier character at ${line}:${column}`); } function separatorChar(c2) { console.warn(`JSON5: '${formatChar(c2)}' in strings is not valid ECMAScript; consider escaping`); } function formatChar(c2) { const replacements = { "'": "\\'", '"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", " ": "\\t", "\v": "\\v", "\0": "\\0", "\u2028": "\\u2028", "\u2029": "\\u2029" }; if (replacements[c2]) { return replacements[c2]; } if (c2 < " ") { const hexString = c2.charCodeAt(0).toString(16); return "\\x" + ("00" + hexString).substring(hexString.length); } return c2; } function syntaxError2(message) { const err = new SyntaxError(message); err.lineNumber = line; err.columnNumber = column; return err; } } }); // node_modules/json5/lib/stringify.js var require_stringify2 = __commonJS({ "node_modules/json5/lib/stringify.js"(exports2, module2) { var util2 = require_util2(); module2.exports = function stringify(value, replacer, space) { const stack = []; let indent = ""; let propertyList; let replacerFunc; let gap = ""; let quote; if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) { space = replacer.space; quote = replacer.quote; replacer = replacer.replacer; } if (typeof replacer === "function") { replacerFunc = replacer; } else if (Array.isArray(replacer)) { propertyList = []; for (const v of replacer) { let item; if (typeof v === "string") { item = v; } else if (typeof v === "number" || v instanceof String || v instanceof Number) { item = String(v); } if (item !== void 0 && propertyList.indexOf(item) < 0) { propertyList.push(item); } } } if (space instanceof Number) { space = Number(space); } else if (space instanceof String) { space = String(space); } if (typeof space === "number") { if (space > 0) { space = Math.min(10, Math.floor(space)); gap = " ".substr(0, space); } } else if (typeof space === "string") { gap = space.substr(0, 10); } return serializeProperty("", { "": value }); function serializeProperty(key, holder) { let value2 = holder[key]; if (value2 != null) { if (typeof value2.toJSON5 === "function") { value2 = value2.toJSON5(key); } else if (typeof value2.toJSON === "function") { value2 = value2.toJSON(key); } } if (replacerFunc) { value2 = replacerFunc.call(holder, key, value2); } if (value2 instanceof Number) { value2 = Number(value2); } else if (value2 instanceof String) { value2 = String(value2); } else if (value2 instanceof Boolean) { value2 = value2.valueOf(); } switch (value2) { case null: return "null"; case true: return "true"; case false: return "false"; } if (typeof value2 === "string") { return quoteString(value2, false); } if (typeof value2 === "number") { return String(value2); } if (typeof value2 === "object") { return Array.isArray(value2) ? serializeArray(value2) : serializeObject(value2); } return void 0; } function quoteString(value2) { const quotes = { "'": 0.1, '"': 0.2 }; const replacements = { "'": "\\'", '"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", " ": "\\t", "\v": "\\v", "\0": "\\0", "\u2028": "\\u2028", "\u2029": "\\u2029" }; let product = ""; for (let i = 0; i < value2.length; i++) { const c = value2[i]; switch (c) { case "'": case '"': quotes[c]++; product += c; continue; case "\0": if (util2.isDigit(value2[i + 1])) { product += "\\x00"; continue; } } if (replacements[c]) { product += replacements[c]; continue; } if (c < " ") { let hexString = c.charCodeAt(0).toString(16); product += "\\x" + ("00" + hexString).substring(hexString.length); continue; } product += c; } const quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b); product = product.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]); return quoteChar + product + quoteChar; } function serializeObject(value2) { if (stack.indexOf(value2) >= 0) { throw TypeError("Converting circular structure to JSON5"); } stack.push(value2); let stepback = indent; indent = indent + gap; let keys = propertyList || Object.keys(value2); let partial2 = []; for (const key of keys) { const propertyString = serializeProperty(key, value2); if (propertyString !== void 0) { let member = serializeKey(key) + ":"; if (gap !== "") { member += " "; } member += propertyString; partial2.push(member); } } let final; if (partial2.length === 0) { final = "{}"; } else { let properties; if (gap === "") { properties = partial2.join(","); final = "{" + properties + "}"; } else { let separator = ",\n" + indent; properties = partial2.join(separator); final = "{\n" + indent + properties + ",\n" + stepback + "}"; } } stack.pop(); indent = stepback; return final; } function serializeKey(key) { if (key.length === 0) { return quoteString(key, true); } const firstChar = String.fromCodePoint(key.codePointAt(0)); if (!util2.isIdStartChar(firstChar)) { return quoteString(key, true); } for (let i = firstChar.length; i < key.length; i++) { if (!util2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { return quoteString(key, true); } } return key; } function serializeArray(value2) { if (stack.indexOf(value2) >= 0) { throw TypeError("Converting circular structure to JSON5"); } stack.push(value2); let stepback = indent; indent = indent + gap; let partial2 = []; for (let i = 0; i < value2.length; i++) { const propertyString = serializeProperty(String(i), value2); partial2.push(propertyString !== void 0 ? propertyString : "null"); } let final; if (partial2.length === 0) { final = "[]"; } else { if (gap === "") { let properties = partial2.join(","); final = "[" + properties + "]"; } else { let separator = ",\n" + indent; let properties = partial2.join(separator); final = "[\n" + indent + properties + ",\n" + stepback + "]"; } } stack.pop(); indent = stepback; return final; } }; } }); // node_modules/json5/lib/index.js var require_lib = __commonJS({ "node_modules/json5/lib/index.js"(exports2, module2) { var parse3 = require_parse(); var stringify = require_stringify2(); var JSON5 = { parse: parse3, stringify }; module2.exports = JSON5; } }); // node_modules/source-map/lib/base64.js var require_base64 = __commonJS({ "node_modules/source-map/lib/base64.js"(exports2) { var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); exports2.encode = function(number4) { if (0 <= number4 && number4 < intToCharMap.length) { return intToCharMap[number4]; } throw new TypeError("Must be between 0 and 63: " + number4); }; exports2.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; }; } }); // node_modules/source-map/lib/base64-vlq.js var require_base64_vlq = __commonJS({ "node_modules/source-map/lib/base64-vlq.js"(exports2) { var base643 = 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; } exports2.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 += base643.encode(digit); } while (vlq > 0); return encoded; }; exports2.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 = base643.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; }; } }); // node_modules/source-map/lib/util.js var require_util3 = __commonJS({ "node_modules/source-map/lib/util.js"(exports2) { 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.'); } } exports2.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports2.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url2 = ""; if (aParsedUrl.scheme) { url2 += aParsedUrl.scheme + ":"; } url2 += "//"; if (aParsedUrl.auth) { url2 += aParsedUrl.auth + "@"; } if (aParsedUrl.host) { url2 += aParsedUrl.host; } if (aParsedUrl.port) { url2 += ":" + aParsedUrl.port; } if (aParsedUrl.path) { url2 += aParsedUrl.path; } return url2; } exports2.urlGenerate = urlGenerate; function normalize(aPath) { var path = aPath; var url2 = urlParse(aPath); if (url2) { if (!url2.path) { return aPath; } path = url2.path; } var isAbsolute = exports2.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === ".") { parts.splice(i, 1); } else if (part === "..") { up++; } else if (up > 0) { if (part === "") { parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join("/"); if (path === "") { path = isAbsolute ? "/" : "."; } if (url2) { url2.path = path; return urlGenerate(url2); } return path; } exports2.normalize = normalize; function join(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; } exports2.join = join; exports2.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 index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports2.relative = relative; var supportsNullProto = (function() { var obj = /* @__PURE__ */ Object.create(null); return !("__proto__" in obj); })(); function identity(s) { return s; } function toSetString(aStr) { if (isProtoString(aStr)) { return "$" + aStr; } return aStr; } exports2.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports2.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9) { return false; } if (s.charCodeAt(length - 1) !== 95 || s.charCodeAt(length - 2) !== 95 || s.charCodeAt(length - 3) !== 111 || s.charCodeAt(length - 4) !== 116 || s.charCodeAt(length - 5) !== 111 || s.charCodeAt(length - 6) !== 114 || s.charCodeAt(length - 7) !== 112 || s.charCodeAt(length - 8) !== 95 || s.charCodeAt(length - 9) !== 95) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 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); } exports2.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); } exports2.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); } exports2.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; function parseSourceMapInput(str) { return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, "")); } exports2.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 index = parsed.path.lastIndexOf("/"); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports2.computeSourceURL = computeSourceURL; } }); // node_modules/source-map/lib/array-set.js var require_array_set = __commonJS({ "node_modules/source-map/lib/array-set.js"(exports2) { 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 set2 = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set2.add(aArray[i], aAllowDuplicates); } return set2; }; 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(); }; exports2.ArraySet = ArraySet; } }); // node_modules/source-map/lib/mapping-list.js var require_mapping_list = __commonJS({ "node_modules/source-map/lib/mapping-list.js"(exports2) { 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; }; exports2.MappingList = MappingList; } }); // node_modules/source-map/lib/source-map-generator.js var require_source_map_generator = __commonJS({ "node_modules/source-map/lib/source-map-generator.js"(exports2) { 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 i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = ""; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ";"; previousGeneratedLine++; } } else { if (i > 0) { if (!util2.compareByGeneratedPositionsInflated(mapping, mappings[i - 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()); }; exports2.SourceMapGenerator = SourceMapGenerator; } }); // node_modules/source-map/lib/binary-search.js var require_binary_search = __commonJS({ "node_modules/source-map/lib/binary-search.js"(exports2) { exports2.GREATEST_LOWER_BOUND = 1; exports2.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 == exports2.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 == exports2.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } exports2.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch( -1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports2.GREATEST_LOWER_BOUND ); if (index < 0) { return -1; } while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; } }); // node_modules/source-map/lib/quick-sort.js var require_quick_sort = __commonJS({ "node_modules/source-map/lib/quick-sort.js"(exports2) { function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } function randomIntInRange(low, high) { return Math.round(low + Math.random() * (high - low)); } function doQuickSort(ary, comparator, p, r) { if (p < r) { var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } exports2.quickSort = function(ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; } }); // node_modules/source-map/lib/source-map-consumer.js var require_source_map_consumer = __commonJS({ "node_modules/source-map/lib/source-map-consumer.js"(exports2) { 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, index) { var c = aStr.charAt(index); 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 index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND ); if (index >= 0) { var mapping = this._originalMappings[index]; 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[++index]; } } 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[++index]; } } } return mappings; }; exports2.SourceMapConsumer = SourceMapConsumer; function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util2.parseSourceMapInput(aSourceMap); } var version2 = 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 file2 = util2.getArg(sourceMap, "file", null); if (version2 != this._version) { throw new Error("Unsupported version: " + version2); } 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(s) { return util2.computeSourceURL(sourceRoot, s, aSourceMapURL); }); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this._sourceMapURL = aSourceMapURL; this.file = file2; } 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 i; for (i = 0; i < this._absoluteSources.length; ++i) { if (this._absoluteSources[i] == aSource) { return i; } } 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(s) { return util2.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); }); var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; 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 index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment2, end, value; while (index < length) { if (aStr.charAt(index) === ";") { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ",") { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment2 = cachedSegments[str]; if (segment2) { index += str.length; } else { segment2 = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment2.push(value); } if (segment2.length === 2) { throw new Error("Found a source, but no line and column"); } if (segment2.length === 3) { throw new Error("Found a source and line, but no column"); } cachedSegments[str] = segment2; } mapping.generatedColumn = previousGeneratedColumn + segment2[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment2.length > 1) { mapping.source = previousSource + segment2[1]; previousSource += segment2[1]; mapping.originalLine = previousOriginalLine + segment2[2]; previousOriginalLine = mapping.originalLine; mapping.originalLine += 1; mapping.originalColumn = previousOriginalColumn + segment2[3]; previousOriginalColumn = mapping.originalColumn; if (segment2.length > 4) { mapping.name = previousName + segment2[4]; previousName += segment2[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 index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 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 index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util2.compareByGeneratedPositionsDeflated, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; 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 index = this._findSourceIndex(aSource); if (index >= 0) { return this.sourcesContent[index]; } var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util2.relative(this.sourceRoot, relativeSource); } var url2; if (this.sourceRoot != null && (url2 = util2.urlParse(this.sourceRoot))) { var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); if (url2.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; } if ((!url2.path || url2.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 index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; 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 }; }; exports2.BasicSourceMapConsumer = BasicSourceMapConsumer; function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util2.parseSourceMapInput(aSourceMap); } var version2 = util2.getArg(sourceMap, "version"); var sections = util2.getArg(sourceMap, "sections"); if (version2 != this._version) { throw new Error("Unsupported version: " + version2); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function(s) { if (s.url) { throw new Error("Support for url field in sections not implemented."); } var offset = util2.getArg(s, "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: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util2.getArg(s, "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 i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].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(s) { return s.consumer.hasContentsOfAllSources(); }); }; IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; 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 i = 0; i < this._sections.length; i++) { var section = this._sections[i]; 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 i = 0; i < this._sections.length; i++) { var section = this._sections[i]; 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); }; exports2.IndexedSourceMapConsumer = IndexedSourceMapConsumer; } }); // node_modules/source-map/lib/source-node.js var require_source_node = __commonJS({ "node_modules/source-map/lib/source-node.js"(exports2) { 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 i = aChunk.length - 1; i >= 0; i--) { this.prepend(aChunk[i]); } } 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 i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; 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 i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len - 1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); 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 i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util2.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; 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 }; }; exports2.SourceNode = SourceNode; } }); // node_modules/source-map/source-map.js var require_source_map = __commonJS({ "node_modules/source-map/source-map.js"(exports2) { exports2.SourceMapGenerator = require_source_map_generator().SourceMapGenerator; exports2.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer; exports2.SourceNode = require_source_node().SourceNode; } }); // node_modules/buffer-from/index.js var require_buffer_from = __commonJS({ "node_modules/buffer-from/index.js"(exports2, module2) { var toString = Object.prototype.toString; var isModern = typeof Buffer !== "undefined" && 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(string4, 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(string4, encoding) : new Buffer(string4, 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); } module2.exports = bufferFrom; } }); // node_modules/source-map-support/source-map-support.js var require_source_map_support = __commonJS({ "node_modules/source-map-support/source-map-support.js"(exports2, module2) { var SourceMapConsumer = require_source_map().SourceMapConsumer; var path = require("path"); var fs; try { fs = require("fs"); if (!fs.existsSync || !fs.readFileSync) { fs = null; } } catch (err) { } 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 globalProcessVersion() { if (typeof process === "object" && process !== null) { return process.version; } else { return ""; } } function globalProcessStderr() { if (typeof process === "object" && process !== null) { return process.stderr; } } function globalProcessExit(code) { if (typeof process === "object" && process !== null && typeof process.exit === "function") { return process.exit(code); } } function handlerExec(list) { return function(arg) { for (var i = 0; i < list.length; i++) { var ret = list[i](arg); if (ret) { return ret; } } return null; }; } var retrieveFile = handlerExec(retrieveFileHandlers); retrieveFileHandlers.push(function(path2) { path2 = path2.trim(); if (/^file:/.test(path2)) { path2 = path2.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) { return drive ? "" : ( // file:///C:/dir/file -> C:/dir/file "/" ); }); } if (path2 in fileContentsCache) { return fileContentsCache[path2]; } var contents = ""; try { if (!fs) { var xhr = new XMLHttpRequest(); xhr.open( "GET", path2, /** async */ false ); xhr.send(null); if (xhr.readyState === 4 && xhr.status === 200) { contents = xhr.responseText; } } else if (fs.existsSync(path2)) { contents = fs.readFileSync(path2, "utf8"); } } catch (er) { } return fileContentsCache[path2] = contents; }); function supportRelativeURL(file2, url2) { if (!file2) return url2; var dir = path.dirname(file2); var match = /^\w+:\/\/[^\/]*/.exec(dir); var protocol = match ? match[0] : ""; var startPath = dir.slice(protocol.length); if (protocol && /^\/\w\:/.test(startPath)) { protocol += "/"; return protocol + path.resolve(dir.slice(protocol.length), url2).replace(/\\/g, "/"); } return protocol + path.resolve(dir.slice(protocol.length), url2); } 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 (e) { } } fileData = retrieveFile(source); var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; var lastMatch, match; while (match = re.exec(fileData)) lastMatch = match; 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, i) { var contents = sourceMap.map.sourcesContent[i]; if (contents) { var url2 = supportRelativeURL(sourceMap.url, source); fileContentsCache[url2] = 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 match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); if (match) { var position = mapSourcePosition({ source: match[2], line: +match[3], column: match[4] - 1 }); return "eval at " + match[1] + " (" + position.source + ":" + position.line + ":" + (position.column + 1) + ")"; } match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); if (match) { return "eval at " + match[1] + " (" + mapEvalOrigin(match[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 += ""; } 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 || ""); } } else if (isConstructor) { line += "new " + (functionName || ""); } else if (functionName) { line += functionName; } else { line += fileLocation; addSuffix = false; } if (addSuffix) { line += " (" + fileLocation + ")"; } return line; } function cloneCallSite(frame) { var object3 = {}; Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { object3[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; }); object3.toString = CallSiteToString; return object3; } 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 column = 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(globalProcessVersion()) ? 0 : 62; if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { column -= headerLength; } var position = mapSourcePosition({ source, line, column }); 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(error48, stack) { if (emptyCacheBetweenOperations) { fileContentsCache = {}; sourceMapCache = {}; } var name = error48.name || "Error"; var message = error48.message || ""; var errorString = name + ": " + message; var state = { nextPosition: null, curPosition: null }; var processedStack = []; for (var i = stack.length - 1; i >= 0; i--) { processedStack.push("\n at " + wrapCallSite(stack[i], state)); state.nextPosition = state.curPosition; } state.curPosition = state.nextPosition = null; return errorString + processedStack.reverse().join(""); } function getErrorSource(error48) { var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error48.stack); if (match) { var source = match[1]; var line = +match[2]; var column = +match[3]; var contents = fileContentsCache[source]; if (!contents && fs && fs.existsSync(source)) { try { contents = fs.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(column).join(" ") + "^"; } } } return null; } function printErrorAndExit(error48) { var source = getErrorSource(error48); var stderr = globalProcessStderr(); if (stderr && stderr._handle && stderr._handle.setBlocking) { stderr._handle.setBlocking(true); } if (source) { console.error(); console.error(source); } console.error(error48.stack); globalProcessExit(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); exports2.wrapCallSite = wrapCallSite; exports2.getErrorSource = getErrorSource; exports2.mapSourcePosition = mapSourcePosition; exports2.retrieveSourceMap = retrieveSourceMap; exports2.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(module2, "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(module2, "worker_threads"); if (worker_threads.isMainThread === false) { installHandler = false; } } catch (e) { } if (installHandler && hasGlobalProcessEventEmitter()) { uncaughtShimInstalled = true; shimEmitUncaughtException(); } } }; exports2.resetRetrieveHandlers = function() { retrieveFileHandlers.length = 0; retrieveMapHandlers.length = 0; retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); retrieveSourceMap = handlerExec(retrieveMapHandlers); retrieveFile = handlerExec(retrieveFileHandlers); }; } }); // node_modules/ansi-colors/symbols.js var require_symbols = __commonJS({ "node_modules/ansi-colors/symbols.js"(exports2, module2) { "use strict"; var isHyper = typeof process !== "undefined" && process.env.TERM_PROGRAM === "Hyper"; var isWindows = typeof process !== "undefined" && process.platform === "win32"; var isLinux = typeof process !== "undefined" && process.platform === "linux"; var common = { ballotDisabled: "\u2612", ballotOff: "\u2610", ballotOn: "\u2611", bullet: "\u2022", bulletWhite: "\u25E6", fullBlock: "\u2588", heart: "\u2764", identicalTo: "\u2261", line: "\u2500", mark: "\u203B", middot: "\xB7", minus: "\uFF0D", multiplication: "\xD7", obelus: "\xF7", pencilDownRight: "\u270E", pencilRight: "\u270F", pencilUpRight: "\u2710", percent: "%", pilcrow2: "\u2761", pilcrow: "\xB6", plusMinus: "\xB1", question: "?", section: "\xA7", starsOff: "\u2606", starsOn: "\u2605", upDownArrow: "\u2195" }; var windows = Object.assign({}, common, { check: "\u221A", cross: "\xD7", ellipsisLarge: "...", ellipsis: "...", info: "i", questionSmall: "?", pointer: ">", pointerSmall: "\xBB", radioOff: "( )", radioOn: "(*)", warning: "\u203C" }); var other = Object.assign({}, common, { ballotCross: "\u2718", check: "\u2714", cross: "\u2716", ellipsisLarge: "\u22EF", ellipsis: "\u2026", info: "\u2139", questionFull: "\uFF1F", questionSmall: "\uFE56", pointer: isLinux ? "\u25B8" : "\u276F", pointerSmall: isLinux ? "\u2023" : "\u203A", radioOff: "\u25EF", radioOn: "\u25C9", warning: "\u26A0" }); module2.exports = isWindows && !isHyper ? windows : other; Reflect.defineProperty(module2.exports, "common", { enumerable: false, value: common }); Reflect.defineProperty(module2.exports, "windows", { enumerable: false, value: windows }); Reflect.defineProperty(module2.exports, "other", { enumerable: false, value: other }); } }); // node_modules/ansi-colors/index.js var require_ansi_colors = __commonJS({ "node_modules/ansi-colors/index.js"(exports2, module2) { "use strict"; var isObject2 = (val) => val !== null && typeof val === "object" && !Array.isArray(val); var ANSI_REGEX = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g; var hasColor = () => { if (typeof process !== "undefined") { return process.env.FORCE_COLOR !== "0"; } return false; }; var create = () => { const colors2 = { enabled: hasColor(), visible: true, styles: {}, keys: {} }; const ansi = (style2) => { let open2 = style2.open = `\x1B[${style2.codes[0]}m`; let close = style2.close = `\x1B[${style2.codes[1]}m`; let regex = style2.regex = new RegExp(`\\u001b\\[${style2.codes[1]}m`, "g"); style2.wrap = (input, newline) => { if (input.includes(close)) input = input.replace(regex, close + open2); let output = open2 + input + close; return newline ? output.replace(/\r*\n/g, `${close}$&${open2}`) : output; }; return style2; }; const wrap = (style2, input, newline) => { return typeof style2 === "function" ? style2(input) : style2.wrap(input, newline); }; const style = (input, stack) => { if (input === "" || input == null) return ""; if (colors2.enabled === false) return input; if (colors2.visible === false) return ""; let str = "" + input; let nl = str.includes("\n"); let n = stack.length; if (n > 0 && stack.includes("unstyle")) { stack = [.../* @__PURE__ */ new Set(["unstyle", ...stack])].reverse(); } while (n-- > 0) str = wrap(colors2.styles[stack[n]], str, nl); return str; }; const define = (name, codes, type) => { colors2.styles[name] = ansi({ name, codes }); let keys = colors2.keys[type] || (colors2.keys[type] = []); keys.push(name); Reflect.defineProperty(colors2, name, { configurable: true, enumerable: true, set(value) { colors2.alias(name, value); }, get() { let color = (input) => style(input, color.stack); Reflect.setPrototypeOf(color, colors2); color.stack = this.stack ? this.stack.concat(name) : [name]; return color; } }); }; define("reset", [0, 0], "modifier"); define("bold", [1, 22], "modifier"); define("dim", [2, 22], "modifier"); define("italic", [3, 23], "modifier"); define("underline", [4, 24], "modifier"); define("inverse", [7, 27], "modifier"); define("hidden", [8, 28], "modifier"); define("strikethrough", [9, 29], "modifier"); define("black", [30, 39], "color"); define("red", [31, 39], "color"); define("green", [32, 39], "color"); define("yellow", [33, 39], "color"); define("blue", [34, 39], "color"); define("magenta", [35, 39], "color"); define("cyan", [36, 39], "color"); define("white", [37, 39], "color"); define("gray", [90, 39], "color"); define("grey", [90, 39], "color"); define("bgBlack", [40, 49], "bg"); define("bgRed", [41, 49], "bg"); define("bgGreen", [42, 49], "bg"); define("bgYellow", [43, 49], "bg"); define("bgBlue", [44, 49], "bg"); define("bgMagenta", [45, 49], "bg"); define("bgCyan", [46, 49], "bg"); define("bgWhite", [47, 49], "bg"); define("blackBright", [90, 39], "bright"); define("redBright", [91, 39], "bright"); define("greenBright", [92, 39], "bright"); define("yellowBright", [93, 39], "bright"); define("blueBright", [94, 39], "bright"); define("magentaBright", [95, 39], "bright"); define("cyanBright", [96, 39], "bright"); define("whiteBright", [97, 39], "bright"); define("bgBlackBright", [100, 49], "bgBright"); define("bgRedBright", [101, 49], "bgBright"); define("bgGreenBright", [102, 49], "bgBright"); define("bgYellowBright", [103, 49], "bgBright"); define("bgBlueBright", [104, 49], "bgBright"); define("bgMagentaBright", [105, 49], "bgBright"); define("bgCyanBright", [106, 49], "bgBright"); define("bgWhiteBright", [107, 49], "bgBright"); colors2.ansiRegex = ANSI_REGEX; colors2.hasColor = colors2.hasAnsi = (str) => { colors2.ansiRegex.lastIndex = 0; return typeof str === "string" && str !== "" && colors2.ansiRegex.test(str); }; colors2.alias = (name, color) => { let fn = typeof color === "string" ? colors2[color] : color; if (typeof fn !== "function") { throw new TypeError("Expected alias to be the name of an existing color (string) or a function"); } if (!fn.stack) { Reflect.defineProperty(fn, "name", { value: name }); colors2.styles[name] = fn; fn.stack = [name]; } Reflect.defineProperty(colors2, name, { configurable: true, enumerable: true, set(value) { colors2.alias(name, value); }, get() { let color2 = (input) => style(input, color2.stack); Reflect.setPrototypeOf(color2, colors2); color2.stack = this.stack ? this.stack.concat(fn.stack) : fn.stack; return color2; } }); }; colors2.theme = (custom2) => { if (!isObject2(custom2)) throw new TypeError("Expected theme to be an object"); for (let name of Object.keys(custom2)) { colors2.alias(name, custom2[name]); } return colors2; }; colors2.alias("unstyle", (str) => { if (typeof str === "string" && str !== "") { colors2.ansiRegex.lastIndex = 0; return str.replace(colors2.ansiRegex, ""); } return ""; }); colors2.alias("noop", (str) => str); colors2.none = colors2.clear = colors2.noop; colors2.stripColor = colors2.unstyle; colors2.symbols = require_symbols(); colors2.define = define; return colors2; }; module2.exports = create(); module2.exports.create = create; } }); // node_modules/enquirer/lib/utils.js var require_utils2 = __commonJS({ "node_modules/enquirer/lib/utils.js"(exports2) { "use strict"; var toString = Object.prototype.toString; var colors2 = require_ansi_colors(); var called = false; var fns = []; var complements = { "yellow": "blue", "cyan": "red", "green": "magenta", "black": "white", "blue": "yellow", "red": "cyan", "magenta": "green", "white": "black" }; exports2.longest = (arr, prop) => { return arr.reduce((a, v) => Math.max(a, prop ? v[prop].length : v.length), 0); }; exports2.hasColor = (str) => !!str && colors2.hasColor(str); var isObject2 = exports2.isObject = (val) => { return val !== null && typeof val === "object" && !Array.isArray(val); }; exports2.nativeType = (val) => { return toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, ""); }; exports2.isAsyncFn = (val) => { return exports2.nativeType(val) === "asyncfunction"; }; exports2.isPrimitive = (val) => { return val != null && typeof val !== "object" && typeof val !== "function"; }; exports2.resolve = (context, value, ...rest) => { if (typeof value === "function") { return value.call(context, ...rest); } return value; }; exports2.scrollDown = (choices = []) => [...choices.slice(1), choices[0]]; exports2.scrollUp = (choices = []) => [choices.pop(), ...choices]; exports2.reorder = (arr = []) => { let res = arr.slice(); res.sort((a, b) => { if (a.index > b.index) return 1; if (a.index < b.index) return -1; return 0; }); return res; }; exports2.swap = (arr, index, pos) => { let len = arr.length; let idx = pos === len ? 0 : pos < 0 ? len - 1 : pos; let choice = arr[index]; arr[index] = arr[idx]; arr[idx] = choice; }; exports2.width = (stream, fallback = 80) => { let columns = stream && stream.columns ? stream.columns : fallback; if (stream && typeof stream.getWindowSize === "function") { columns = stream.getWindowSize()[0]; } if (process.platform === "win32") { return columns - 1; } return columns; }; exports2.height = (stream, fallback = 20) => { let rows = stream && stream.rows ? stream.rows : fallback; if (stream && typeof stream.getWindowSize === "function") { rows = stream.getWindowSize()[1]; } return rows; }; exports2.wordWrap = (str, options = {}) => { if (!str) return str; if (typeof options === "number") { options = { width: options }; } let { indent = "", newline = "\n" + indent, width = 80 } = options; let spaces = (newline + indent).match(/[^\S\n]/g) || []; width -= spaces.length; let source = `.{1,${width}}([\\s\\u200B]+|$)|[^\\s\\u200B]+?([\\s\\u200B]+|$)`; let output = str.trim(); let regex = new RegExp(source, "g"); let lines = output.match(regex) || []; lines = lines.map((line) => line.replace(/\n$/, "")); if (options.padEnd) lines = lines.map((line) => line.padEnd(width, " ")); if (options.padStart) lines = lines.map((line) => line.padStart(width, " ")); return indent + lines.join(newline); }; exports2.unmute = (color) => { let name = color.stack.find((n) => colors2.keys.color.includes(n)); if (name) { return colors2[name]; } let bg = color.stack.find((n) => n.slice(2) === "bg"); if (bg) { return colors2[name.slice(2)]; } return (str) => str; }; exports2.pascal = (str) => str ? str[0].toUpperCase() + str.slice(1) : ""; exports2.inverse = (color) => { if (!color || !color.stack) return color; let name = color.stack.find((n) => colors2.keys.color.includes(n)); if (name) { let col = colors2["bg" + exports2.pascal(name)]; return col ? col.black : color; } let bg = color.stack.find((n) => n.slice(0, 2) === "bg"); if (bg) { return colors2[bg.slice(2).toLowerCase()] || color; } return colors2.none; }; exports2.complement = (color) => { if (!color || !color.stack) return color; let name = color.stack.find((n) => colors2.keys.color.includes(n)); let bg = color.stack.find((n) => n.slice(0, 2) === "bg"); if (name && !bg) { return colors2[complements[name] || name]; } if (bg) { let lower = bg.slice(2).toLowerCase(); let comp = complements[lower]; if (!comp) return color; return colors2["bg" + exports2.pascal(comp)] || color; } return colors2.none; }; exports2.meridiem = (date5) => { let hours = date5.getHours(); let minutes = date5.getMinutes(); let ampm = hours >= 12 ? "pm" : "am"; hours = hours % 12; let hrs = hours === 0 ? 12 : hours; let min = minutes < 10 ? "0" + minutes : minutes; return hrs + ":" + min + " " + ampm; }; exports2.set = (obj = {}, prop = "", val) => { return prop.split(".").reduce((acc, k, i, arr) => { let value = arr.length - 1 > i ? acc[k] || {} : val; if (!exports2.isObject(value) && i < arr.length - 1) value = {}; return acc[k] = value; }, obj); }; exports2.get = (obj = {}, prop = "", fallback) => { let value = obj[prop] == null ? prop.split(".").reduce((acc, k) => acc && acc[k], obj) : obj[prop]; return value == null ? fallback : value; }; exports2.mixin = (target, b) => { if (!isObject2(target)) return b; if (!isObject2(b)) return target; for (let key of Object.keys(b)) { let desc = Object.getOwnPropertyDescriptor(b, key); if (desc.hasOwnProperty("value")) { if (target.hasOwnProperty(key) && isObject2(desc.value)) { let existing = Object.getOwnPropertyDescriptor(target, key); if (isObject2(existing.value)) { target[key] = exports2.merge({}, target[key], b[key]); } else { Reflect.defineProperty(target, key, desc); } } else { Reflect.defineProperty(target, key, desc); } } else { Reflect.defineProperty(target, key, desc); } } return target; }; exports2.merge = (...args) => { let target = {}; for (let ele of args) exports2.mixin(target, ele); return target; }; exports2.mixinEmitter = (obj, emitter) => { let proto = emitter.constructor.prototype; for (let key of Object.keys(proto)) { let val = proto[key]; if (typeof val === "function") { exports2.define(obj, key, val.bind(emitter)); } else { exports2.define(obj, key, val); } } }; exports2.onExit = (callback) => { const onExit2 = (quit, code) => { if (called) return; called = true; fns.forEach((fn) => fn()); if (quit === true) { process.exit(128 + code); } }; if (fns.length === 0) { process.once("SIGTERM", onExit2.bind(null, true, 15)); process.once("SIGINT", onExit2.bind(null, true, 2)); process.once("exit", onExit2); } fns.push(callback); }; exports2.define = (obj, key, value) => { Reflect.defineProperty(obj, key, { value }); }; exports2.defineExport = (obj, key, fn) => { let custom2; Reflect.defineProperty(obj, key, { enumerable: true, configurable: true, set(val) { custom2 = val; }, get() { return custom2 ? custom2() : fn(); } }); }; } }); // node_modules/enquirer/lib/combos.js var require_combos = __commonJS({ "node_modules/enquirer/lib/combos.js"(exports2) { "use strict"; exports2.ctrl = { a: "first", b: "backward", c: "cancel", d: "deleteForward", e: "last", f: "forward", g: "reset", i: "tab", k: "cutForward", l: "reset", n: "newItem", m: "cancel", j: "submit", p: "search", r: "remove", s: "save", u: "undo", w: "cutLeft", x: "toggleCursor", v: "paste" }; exports2.shift = { up: "shiftUp", down: "shiftDown", left: "shiftLeft", right: "shiftRight", tab: "prev" }; exports2.fn = { up: "pageUp", down: "pageDown", left: "pageLeft", right: "pageRight", delete: "deleteForward" }; exports2.option = { b: "backward", f: "forward", d: "cutRight", left: "cutLeft", up: "altUp", down: "altDown" }; exports2.keys = { pageup: "pageUp", // + (mac), (windows) pagedown: "pageDown", // + (mac), (windows) home: "home", // + (mac), (windows) end: "end", // + (mac), (windows) cancel: "cancel", delete: "deleteForward", backspace: "delete", down: "down", enter: "submit", escape: "cancel", left: "left", space: "space", number: "number", return: "submit", right: "right", tab: "next", up: "up" }; } }); // node_modules/enquirer/lib/keypress.js var require_keypress = __commonJS({ "node_modules/enquirer/lib/keypress.js"(exports2, module2) { "use strict"; var readline = require("readline"); var combos = require_combos(); var metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/; var fnKeyRe = /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/; var keyName = { /* xterm/gnome ESC O letter */ "OP": "f1", "OQ": "f2", "OR": "f3", "OS": "f4", /* xterm/rxvt ESC [ number ~ */ "[11~": "f1", "[12~": "f2", "[13~": "f3", "[14~": "f4", /* from Cygwin and used in libuv */ "[[A": "f1", "[[B": "f2", "[[C": "f3", "[[D": "f4", "[[E": "f5", /* common */ "[15~": "f5", "[17~": "f6", "[18~": "f7", "[19~": "f8", "[20~": "f9", "[21~": "f10", "[23~": "f11", "[24~": "f12", /* xterm ESC [ letter */ "[A": "up", "[B": "down", "[C": "right", "[D": "left", "[E": "clear", "[F": "end", "[H": "home", /* xterm/gnome ESC O letter */ "OA": "up", "OB": "down", "OC": "right", "OD": "left", "OE": "clear", "OF": "end", "OH": "home", /* xterm/rxvt ESC [ number ~ */ "[1~": "home", "[2~": "insert", "[3~": "delete", "[4~": "end", "[5~": "pageup", "[6~": "pagedown", /* putty */ "[[5~": "pageup", "[[6~": "pagedown", /* rxvt */ "[7~": "home", "[8~": "end", /* rxvt keys with modifiers */ "[a": "up", "[b": "down", "[c": "right", "[d": "left", "[e": "clear", "[2$": "insert", "[3$": "delete", "[5$": "pageup", "[6$": "pagedown", "[7$": "home", "[8$": "end", "Oa": "up", "Ob": "down", "Oc": "right", "Od": "left", "Oe": "clear", "[2^": "insert", "[3^": "delete", "[5^": "pageup", "[6^": "pagedown", "[7^": "home", "[8^": "end", /* misc. */ "[Z": "tab" }; function isShiftKey(code) { return ["[a", "[b", "[c", "[d", "[e", "[2$", "[3$", "[5$", "[6$", "[7$", "[8$", "[Z"].includes(code); } function isCtrlKey(code) { return ["Oa", "Ob", "Oc", "Od", "Oe", "[2^", "[3^", "[5^", "[6^", "[7^", "[8^"].includes(code); } var keypress = (s = "", event = {}) => { let parts; let key = { name: event.name, ctrl: false, meta: false, shift: false, option: false, sequence: s, raw: s, ...event }; if (Buffer.isBuffer(s)) { if (s[0] > 127 && s[1] === void 0) { s[0] -= 128; s = "\x1B" + String(s); } else { s = String(s); } } else if (s !== void 0 && typeof s !== "string") { s = String(s); } else if (!s) { s = key.sequence || ""; } key.sequence = key.sequence || s || key.name; if (s === "\r") { key.raw = void 0; key.name = "return"; } else if (s === "\n") { key.name = "enter"; } else if (s === " ") { key.name = "tab"; } else if (s === "\b" || s === "\x7F" || s === "\x1B\x7F" || s === "\x1B\b") { key.name = "backspace"; key.meta = s.charAt(0) === "\x1B"; } else if (s === "\x1B" || s === "\x1B\x1B") { key.name = "escape"; key.meta = s.length === 2; } else if (s === " " || s === "\x1B ") { key.name = "space"; key.meta = s.length === 2; } else if (s <= "") { key.name = String.fromCharCode(s.charCodeAt(0) + "a".charCodeAt(0) - 1); key.ctrl = true; } else if (s.length === 1 && s >= "0" && s <= "9") { key.name = "number"; } else if (s.length === 1 && s >= "a" && s <= "z") { key.name = s; } else if (s.length === 1 && s >= "A" && s <= "Z") { key.name = s.toLowerCase(); key.shift = true; } else if (parts = metaKeyCodeRe.exec(s)) { key.meta = true; key.shift = /^[A-Z]$/.test(parts[1]); } else if (parts = fnKeyRe.exec(s)) { let segs = [...s]; if (segs[0] === "\x1B" && segs[1] === "\x1B") { key.option = true; } let code = [parts[1], parts[2], parts[4], parts[6]].filter(Boolean).join(""); let modifier = (parts[3] || parts[5] || 1) - 1; key.ctrl = !!(modifier & 4); key.meta = !!(modifier & 10); key.shift = !!(modifier & 1); key.code = code; key.name = keyName[code]; key.shift = isShiftKey(code) || key.shift; key.ctrl = isCtrlKey(code) || key.ctrl; } return key; }; keypress.listen = (options = {}, onKeypress) => { let { stdin } = options; if (!stdin || stdin !== process.stdin && !stdin.isTTY) { throw new Error("Invalid stream passed"); } let rl = readline.createInterface({ terminal: true, input: stdin }); readline.emitKeypressEvents(stdin, rl); let on = (buf, key) => onKeypress(buf, keypress(buf, key), rl); let isRaw = stdin.isRaw; if (stdin.isTTY) stdin.setRawMode(true); stdin.on("keypress", on); rl.resume(); let off = () => { if (stdin.isTTY) stdin.setRawMode(isRaw); stdin.removeListener("keypress", on); rl.pause(); rl.close(); }; return off; }; keypress.action = (buf, key, customActions) => { let obj = { ...combos, ...customActions }; if (key.ctrl) { key.action = obj.ctrl[key.name]; return key; } if (key.option && obj.option) { key.action = obj.option[key.name]; return key; } if (key.shift) { key.action = obj.shift[key.name]; return key; } key.action = obj.keys[key.name]; return key; }; module2.exports = keypress; } }); // node_modules/enquirer/lib/timer.js var require_timer = __commonJS({ "node_modules/enquirer/lib/timer.js"(exports2, module2) { "use strict"; module2.exports = (prompt) => { prompt.timers = prompt.timers || {}; let timers = prompt.options.timers; if (!timers) return; for (let key of Object.keys(timers)) { let opts = timers[key]; if (typeof opts === "number") { opts = { interval: opts }; } create(prompt, key, opts); } }; function create(prompt, name, options = {}) { let timer = prompt.timers[name] = { name, start: Date.now(), ms: 0, tick: 0 }; let ms = options.interval || 120; timer.frames = options.frames || []; timer.loading = true; let interval = setInterval(() => { timer.ms = Date.now() - timer.start; timer.tick++; prompt.render(); }, ms); timer.stop = () => { timer.loading = false; clearInterval(interval); }; Reflect.defineProperty(timer, "interval", { value: interval }); prompt.once("close", () => timer.stop()); return timer.stop; } } }); // node_modules/enquirer/lib/state.js var require_state = __commonJS({ "node_modules/enquirer/lib/state.js"(exports2, module2) { "use strict"; var { define, width } = require_utils2(); var State = class { constructor(prompt) { let options = prompt.options; define(this, "_prompt", prompt); this.type = prompt.type; this.name = prompt.name; this.message = ""; this.header = ""; this.footer = ""; this.error = ""; this.hint = ""; this.input = ""; this.cursor = 0; this.index = 0; this.lines = 0; this.tick = 0; this.prompt = ""; this.buffer = ""; this.width = width(options.stdout || process.stdout); Object.assign(this, options); this.name = this.name || this.message; this.message = this.message || this.name; this.symbols = prompt.symbols; this.styles = prompt.styles; this.required = /* @__PURE__ */ new Set(); this.cancelled = false; this.submitted = false; } clone() { let state = { ...this }; state.status = this.status; state.buffer = Buffer.from(state.buffer); delete state.clone; return state; } set color(val) { this._color = val; } get color() { let styles = this.prompt.styles; if (this.cancelled) return styles.cancelled; if (this.submitted) return styles.submitted; let color = this._color || styles[this.status]; return typeof color === "function" ? color : styles.pending; } set loading(value) { this._loading = value; } get loading() { if (typeof this._loading === "boolean") return this._loading; if (this.loadingChoices) return "choices"; return false; } get status() { if (this.cancelled) return "cancelled"; if (this.submitted) return "submitted"; return "pending"; } }; module2.exports = State; } }); // node_modules/enquirer/lib/styles.js var require_styles2 = __commonJS({ "node_modules/enquirer/lib/styles.js"(exports2, module2) { "use strict"; var utils = require_utils2(); var colors2 = require_ansi_colors(); var styles = { default: colors2.noop, noop: colors2.noop, /** * Modifiers */ set inverse(custom2) { this._inverse = custom2; }, get inverse() { return this._inverse || utils.inverse(this.primary); }, set complement(custom2) { this._complement = custom2; }, get complement() { return this._complement || utils.complement(this.primary); }, /** * Main color */ primary: colors2.cyan, /** * Main palette */ success: colors2.green, danger: colors2.magenta, strong: colors2.bold, warning: colors2.yellow, muted: colors2.dim, disabled: colors2.gray, dark: colors2.dim.gray, underline: colors2.underline, set info(custom2) { this._info = custom2; }, get info() { return this._info || this.primary; }, set em(custom2) { this._em = custom2; }, get em() { return this._em || this.primary.underline; }, set heading(custom2) { this._heading = custom2; }, get heading() { return this._heading || this.muted.underline; }, /** * Statuses */ set pending(custom2) { this._pending = custom2; }, get pending() { return this._pending || this.primary; }, set submitted(custom2) { this._submitted = custom2; }, get submitted() { return this._submitted || this.success; }, set cancelled(custom2) { this._cancelled = custom2; }, get cancelled() { return this._cancelled || this.danger; }, /** * Special styling */ set typing(custom2) { this._typing = custom2; }, get typing() { return this._typing || this.dim; }, set placeholder(custom2) { this._placeholder = custom2; }, get placeholder() { return this._placeholder || this.primary.dim; }, set highlight(custom2) { this._highlight = custom2; }, get highlight() { return this._highlight || this.inverse; } }; styles.merge = (options = {}) => { if (options.styles && typeof options.styles.enabled === "boolean") { colors2.enabled = options.styles.enabled; } if (options.styles && typeof options.styles.visible === "boolean") { colors2.visible = options.styles.visible; } let result = utils.merge({}, styles, options.styles); delete result.merge; for (let key of Object.keys(colors2)) { if (!result.hasOwnProperty(key)) { Reflect.defineProperty(result, key, { get: () => colors2[key] }); } } for (let key of Object.keys(colors2.styles)) { if (!result.hasOwnProperty(key)) { Reflect.defineProperty(result, key, { get: () => colors2[key] }); } } return result; }; module2.exports = styles; } }); // node_modules/enquirer/lib/symbols.js var require_symbols2 = __commonJS({ "node_modules/enquirer/lib/symbols.js"(exports2, module2) { "use strict"; var isWindows = process.platform === "win32"; var colors2 = require_ansi_colors(); var utils = require_utils2(); var symbols = { ...colors2.symbols, upDownDoubleArrow: "\u21D5", upDownDoubleArrow2: "\u2B0D", upDownArrow: "\u2195", asterisk: "*", asterism: "\u2042", bulletWhite: "\u25E6", electricArrow: "\u2301", ellipsisLarge: "\u22EF", ellipsisSmall: "\u2026", fullBlock: "\u2588", identicalTo: "\u2261", indicator: colors2.symbols.check, leftAngle: "\u2039", mark: "\u203B", minus: "\u2212", multiplication: "\xD7", obelus: "\xF7", percent: "%", pilcrow: "\xB6", pilcrow2: "\u2761", pencilUpRight: "\u2710", pencilDownRight: "\u270E", pencilRight: "\u270F", plus: "+", plusMinus: "\xB1", pointRight: "\u261E", rightAngle: "\u203A", section: "\xA7", hexagon: { off: "\u2B21", on: "\u2B22", disabled: "\u2B22" }, ballot: { on: "\u2611", off: "\u2610", disabled: "\u2612" }, stars: { on: "\u2605", off: "\u2606", disabled: "\u2606" }, folder: { on: "\u25BC", off: "\u25B6", disabled: "\u25B6" }, prefix: { pending: colors2.symbols.question, submitted: colors2.symbols.check, cancelled: colors2.symbols.cross }, separator: { pending: colors2.symbols.pointerSmall, submitted: colors2.symbols.middot, cancelled: colors2.symbols.middot }, radio: { off: isWindows ? "( )" : "\u25EF", on: isWindows ? "(*)" : "\u25C9", disabled: isWindows ? "(|)" : "\u24BE" }, numbers: ["\u24EA", "\u2460", "\u2461", "\u2462", "\u2463", "\u2464", "\u2465", "\u2466", "\u2467", "\u2468", "\u2469", "\u246A", "\u246B", "\u246C", "\u246D", "\u246E", "\u246F", "\u2470", "\u2471", "\u2472", "\u2473", "\u3251", "\u3252", "\u3253", "\u3254", "\u3255", "\u3256", "\u3257", "\u3258", "\u3259", "\u325A", "\u325B", "\u325C", "\u325D", "\u325E", "\u325F", "\u32B1", "\u32B2", "\u32B3", "\u32B4", "\u32B5", "\u32B6", "\u32B7", "\u32B8", "\u32B9", "\u32BA", "\u32BB", "\u32BC", "\u32BD", "\u32BE", "\u32BF"] }; symbols.merge = (options) => { let result = utils.merge({}, colors2.symbols, symbols, options.symbols); delete result.merge; return result; }; module2.exports = symbols; } }); // node_modules/enquirer/lib/theme.js var require_theme = __commonJS({ "node_modules/enquirer/lib/theme.js"(exports2, module2) { "use strict"; var styles = require_styles2(); var symbols = require_symbols2(); var utils = require_utils2(); module2.exports = (prompt) => { prompt.options = utils.merge({}, prompt.options.theme, prompt.options); prompt.symbols = symbols.merge(prompt.options); prompt.styles = styles.merge(prompt.options); }; } }); // node_modules/enquirer/lib/ansi.js var require_ansi = __commonJS({ "node_modules/enquirer/lib/ansi.js"(exports2, module2) { "use strict"; var isTerm = process.env.TERM_PROGRAM === "Apple_Terminal"; var colors2 = require_ansi_colors(); var utils = require_utils2(); var ansi = module2.exports = exports2; var ESC = "\x1B["; var BEL = "\x07"; var hidden = false; var code = ansi.code = { bell: BEL, beep: BEL, beginning: `${ESC}G`, down: `${ESC}J`, esc: ESC, getPosition: `${ESC}6n`, hide: `${ESC}?25l`, line: `${ESC}2K`, lineEnd: `${ESC}K`, lineStart: `${ESC}1K`, restorePosition: ESC + (isTerm ? "8" : "u"), savePosition: ESC + (isTerm ? "7" : "s"), screen: `${ESC}2J`, show: `${ESC}?25h`, up: `${ESC}1J` }; var cursor = ansi.cursor = { get hidden() { return hidden; }, hide() { hidden = true; return code.hide; }, show() { hidden = false; return code.show; }, forward: (count = 1) => `${ESC}${count}C`, backward: (count = 1) => `${ESC}${count}D`, nextLine: (count = 1) => `${ESC}E`.repeat(count), prevLine: (count = 1) => `${ESC}F`.repeat(count), up: (count = 1) => count ? `${ESC}${count}A` : "", down: (count = 1) => count ? `${ESC}${count}B` : "", right: (count = 1) => count ? `${ESC}${count}C` : "", left: (count = 1) => count ? `${ESC}${count}D` : "", to(x, y) { return y ? `${ESC}${y + 1};${x + 1}H` : `${ESC}${x + 1}G`; }, move(x = 0, y = 0) { let res = ""; res += x < 0 ? cursor.left(-x) : x > 0 ? cursor.right(x) : ""; res += y < 0 ? cursor.up(-y) : y > 0 ? cursor.down(y) : ""; return res; }, restore(state = {}) { let { after, cursor: cursor2, initial, input, prompt, size, value } = state; initial = utils.isPrimitive(initial) ? String(initial) : ""; input = utils.isPrimitive(input) ? String(input) : ""; value = utils.isPrimitive(value) ? String(value) : ""; if (size) { let codes = ansi.cursor.up(size) + ansi.cursor.to(prompt.length); let diff2 = input.length - cursor2; if (diff2 > 0) { codes += ansi.cursor.left(diff2); } return codes; } if (value || after) { let pos = !input && !!initial ? -initial.length : -input.length + cursor2; if (after) pos -= after.length; if (input === "" && initial && !prompt.includes(initial)) { pos += initial.length; } return ansi.cursor.move(pos); } } }; var erase = ansi.erase = { screen: code.screen, up: code.up, down: code.down, line: code.line, lineEnd: code.lineEnd, lineStart: code.lineStart, lines(n) { let str = ""; for (let i = 0; i < n; i++) { str += ansi.erase.line + (i < n - 1 ? ansi.cursor.up(1) : ""); } if (n) str += ansi.code.beginning; return str; } }; ansi.clear = (input = "", columns = process.stdout.columns) => { if (!columns) return erase.line + cursor.to(0); let width = (str) => [...colors2.unstyle(str)].length; let lines = input.split(/\r?\n/); let rows = 0; for (let line of lines) { rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / columns); } return (erase.line + cursor.prevLine()).repeat(rows - 1) + erase.line + cursor.to(0); }; } }); // node_modules/enquirer/lib/prompt.js var require_prompt = __commonJS({ "node_modules/enquirer/lib/prompt.js"(exports2, module2) { "use strict"; var Events = require("events"); var colors2 = require_ansi_colors(); var keypress = require_keypress(); var timer = require_timer(); var State = require_state(); var theme = require_theme(); var utils = require_utils2(); var ansi = require_ansi(); var Prompt = class _Prompt extends Events { constructor(options = {}) { super(); this.name = options.name; this.type = options.type; this.options = options; theme(this); timer(this); this.state = new State(this); this.initial = [options.initial, options.default].find((v) => v != null); this.stdout = options.stdout || process.stdout; this.stdin = options.stdin || process.stdin; this.scale = options.scale || 1; this.term = this.options.term || process.env.TERM_PROGRAM; this.margin = margin(this.options.margin); this.setMaxListeners(0); setOptions(this); } async keypress(input, event = {}) { this.keypressed = true; let key = keypress.action(input, keypress(input, event), this.options.actions); this.state.keypress = key; this.emit("keypress", input, key); this.emit("state", this.state.clone()); let fn = this.options[key.action] || this[key.action] || this.dispatch; if (typeof fn === "function") { return await fn.call(this, input, key); } this.alert(); } alert() { delete this.state.alert; if (this.options.show === false) { this.emit("alert"); } else { this.stdout.write(ansi.code.beep); } } cursorHide() { this.stdout.write(ansi.cursor.hide()); utils.onExit(() => this.cursorShow()); } cursorShow() { this.stdout.write(ansi.cursor.show()); } write(str) { if (!str) return; if (this.stdout && this.state.show !== false) { this.stdout.write(str); } this.state.buffer += str; } clear(lines = 0) { let buffer = this.state.buffer; this.state.buffer = ""; if (!buffer && !lines || this.options.show === false) return; this.stdout.write(ansi.cursor.down(lines) + ansi.clear(buffer, this.width)); } restore() { if (this.state.closed || this.options.show === false) return; let { prompt, after, rest } = this.sections(); let { cursor, initial = "", input = "", value = "" } = this; let size = this.state.size = rest.length; let state = { after, cursor, initial, input, prompt, size, value }; let codes = ansi.cursor.restore(state); if (codes) { this.stdout.write(codes); } } sections() { let { buffer, input, prompt } = this.state; prompt = colors2.unstyle(prompt); let buf = colors2.unstyle(buffer); let idx = buf.indexOf(prompt); let header = buf.slice(0, idx); let rest = buf.slice(idx); let lines = rest.split("\n"); let first = lines[0]; let last = lines[lines.length - 1]; let promptLine = prompt + (input ? " " + input : ""); let len = promptLine.length; let after = len < first.length ? first.slice(len + 1) : ""; return { header, prompt: first, after, rest: lines.slice(1), last }; } async submit() { this.state.submitted = true; this.state.validating = true; if (this.options.onSubmit) { await this.options.onSubmit.call(this, this.name, this.value, this); } let result = this.state.error || await this.validate(this.value, this.state); if (result !== true) { let error48 = "\n" + this.symbols.pointer + " "; if (typeof result === "string") { error48 += result.trim(); } else { error48 += "Invalid input"; } this.state.error = "\n" + this.styles.danger(error48); this.state.submitted = false; await this.render(); await this.alert(); this.state.validating = false; this.state.error = void 0; return; } this.state.validating = false; await this.render(); await this.close(); this.value = await this.result(this.value); this.emit("submit", this.value); } async cancel(err) { this.state.cancelled = this.state.submitted = true; await this.render(); await this.close(); if (typeof this.options.onCancel === "function") { await this.options.onCancel.call(this, this.name, this.value, this); } this.emit("cancel", await this.error(err)); } async close() { this.state.closed = true; try { let sections = this.sections(); let lines = Math.ceil(sections.prompt.length / this.width); if (sections.rest) { this.write(ansi.cursor.down(sections.rest.length)); } this.write("\n".repeat(lines)); } catch (err) { } this.emit("close"); } start() { if (!this.stop && this.options.show !== false) { this.stop = keypress.listen(this, this.keypress.bind(this)); this.once("close", this.stop); } } async skip() { this.skipped = this.options.skip === true; if (typeof this.options.skip === "function") { this.skipped = await this.options.skip.call(this, this.name, this.value); } return this.skipped; } async initialize() { let { format, options, result } = this; this.format = () => format.call(this, this.value); this.result = () => result.call(this, this.value); if (typeof options.initial === "function") { this.initial = await options.initial.call(this, this); } if (typeof options.onRun === "function") { await options.onRun.call(this, this); } if (typeof options.onSubmit === "function") { let onSubmit = options.onSubmit.bind(this); let submit = this.submit.bind(this); delete this.options.onSubmit; this.submit = async () => { await onSubmit(this.name, this.value, this); return submit(); }; } await this.start(); await this.render(); } render() { throw new Error("expected prompt to have a custom render method"); } run() { return new Promise(async (resolve, reject) => { this.once("submit", resolve); this.once("cancel", reject); if (await this.skip()) { this.render = () => { }; return this.submit(); } await this.initialize(); this.emit("run"); }); } async element(name, choice, i) { let { options, state, symbols, timers } = this; let timer2 = timers && timers[name]; state.timer = timer2; let value = options[name] || state[name] || symbols[name]; let val = choice && choice[name] != null ? choice[name] : await value; if (val === "") return val; let res = await this.resolve(val, state, choice, i); if (!res && choice && choice[name]) { return this.resolve(value, state, choice, i); } return res; } async prefix() { let element = await this.element("prefix") || this.symbols; let timer2 = this.timers && this.timers.prefix; let state = this.state; state.timer = timer2; if (utils.isObject(element)) element = element[state.status] || element.pending; if (!utils.hasColor(element)) { let style = this.styles[state.status] || this.styles.pending; return style(element); } return element; } async message() { let message = await this.element("message"); if (!utils.hasColor(message)) { return this.styles.strong(message); } return message; } async separator() { let element = await this.element("separator") || this.symbols; let timer2 = this.timers && this.timers.separator; let state = this.state; state.timer = timer2; let value = element[state.status] || element.pending || state.separator; let ele = await this.resolve(value, state); if (utils.isObject(ele)) ele = ele[state.status] || ele.pending; if (!utils.hasColor(ele)) { return this.styles.muted(ele); } return ele; } async pointer(choice, i) { let val = await this.element("pointer", choice, i); if (typeof val === "string" && utils.hasColor(val)) { return val; } if (val) { let styles = this.styles; let focused = this.index === i; let style = focused ? styles.primary : (val2) => val2; let ele = await this.resolve(val[focused ? "on" : "off"] || val, this.state); let styled = !utils.hasColor(ele) ? style(ele) : ele; return focused ? styled : " ".repeat(ele.length); } } async indicator(choice, i) { let val = await this.element("indicator", choice, i); if (typeof val === "string" && utils.hasColor(val)) { return val; } if (val) { let styles = this.styles; let enabled = choice.enabled === true; let style = enabled ? styles.success : styles.dark; let ele = val[enabled ? "on" : "off"] || val; return !utils.hasColor(ele) ? style(ele) : ele; } return ""; } body() { return null; } footer() { if (this.state.status === "pending") { return this.element("footer"); } } header() { if (this.state.status === "pending") { return this.element("header"); } } async hint() { if (this.state.status === "pending" && !this.isValue(this.state.input)) { let hint = await this.element("hint"); if (!utils.hasColor(hint)) { return this.styles.muted(hint); } return hint; } } error(err) { return !this.state.submitted ? err || this.state.error : ""; } format(value) { return value; } result(value) { return value; } validate(value) { if (this.options.required === true) { return this.isValue(value); } return true; } isValue(value) { return value != null && value !== ""; } resolve(value, ...args) { return utils.resolve(this, value, ...args); } get base() { return _Prompt.prototype; } get style() { return this.styles[this.state.status]; } get height() { return this.options.rows || utils.height(this.stdout, 25); } get width() { return this.options.columns || utils.width(this.stdout, 80); } get size() { return { width: this.width, height: this.height }; } set cursor(value) { this.state.cursor = value; } get cursor() { return this.state.cursor; } set input(value) { this.state.input = value; } get input() { return this.state.input; } set value(value) { this.state.value = value; } get value() { let { input, value } = this.state; let result = [value, input].find(this.isValue.bind(this)); return this.isValue(result) ? result : this.initial; } static get prompt() { return (options) => new this(options).run(); } }; function setOptions(prompt) { let isValidKey = (key) => { return prompt[key] === void 0 || typeof prompt[key] === "function"; }; let ignore = [ "actions", "choices", "initial", "margin", "roles", "styles", "symbols", "theme", "timers", "value" ]; let ignoreFn = [ "body", "footer", "error", "header", "hint", "indicator", "message", "prefix", "separator", "skip" ]; for (let key of Object.keys(prompt.options)) { if (ignore.includes(key)) continue; if (/^on[A-Z]/.test(key)) continue; let option = prompt.options[key]; if (typeof option === "function" && isValidKey(key)) { if (!ignoreFn.includes(key)) { prompt[key] = option.bind(prompt); } } else if (typeof prompt[key] !== "function") { prompt[key] = option; } } } function margin(value) { if (typeof value === "number") { value = [value, value, value, value]; } let arr = [].concat(value || []); let pad = (i) => i % 2 === 0 ? "\n" : " "; let res = []; for (let i = 0; i < 4; i++) { let char = pad(i); if (arr[i]) { res.push(char.repeat(arr[i])); } else { res.push(""); } } return res; } module2.exports = Prompt; } }); // node_modules/enquirer/lib/roles.js var require_roles = __commonJS({ "node_modules/enquirer/lib/roles.js"(exports2, module2) { "use strict"; var utils = require_utils2(); var roles = { default(prompt, choice) { return choice; }, checkbox(prompt, choice) { throw new Error("checkbox role is not implemented yet"); }, editable(prompt, choice) { throw new Error("editable role is not implemented yet"); }, expandable(prompt, choice) { throw new Error("expandable role is not implemented yet"); }, heading(prompt, choice) { choice.disabled = ""; choice.indicator = [choice.indicator, " "].find((v) => v != null); choice.message = choice.message || ""; return choice; }, input(prompt, choice) { throw new Error("input role is not implemented yet"); }, option(prompt, choice) { return roles.default(prompt, choice); }, radio(prompt, choice) { throw new Error("radio role is not implemented yet"); }, separator(prompt, choice) { choice.disabled = ""; choice.indicator = [choice.indicator, " "].find((v) => v != null); choice.message = choice.message || prompt.symbols.line.repeat(5); return choice; }, spacer(prompt, choice) { return choice; } }; module2.exports = (name, options = {}) => { let role = utils.merge({}, roles, options.roles); return role[name] || role.default; }; } }); // node_modules/enquirer/lib/types/array.js var require_array = __commonJS({ "node_modules/enquirer/lib/types/array.js"(exports2, module2) { "use strict"; var colors2 = require_ansi_colors(); var Prompt = require_prompt(); var roles = require_roles(); var utils = require_utils2(); var { reorder, scrollUp, scrollDown, isObject: isObject2, swap } = utils; var ArrayPrompt = class extends Prompt { constructor(options) { super(options); this.cursorHide(); this.maxSelected = options.maxSelected || Infinity; this.multiple = options.multiple || false; this.initial = options.initial || 0; this.delay = options.delay || 0; this.longest = 0; this.num = ""; } async initialize() { if (typeof this.options.initial === "function") { this.initial = await this.options.initial.call(this); } await this.reset(true); await super.initialize(); } async reset() { let { choices, initial, autofocus, suggest } = this.options; this.state._choices = []; this.state.choices = []; this.choices = await Promise.all(await this.toChoices(choices)); this.choices.forEach((ch) => ch.enabled = false); if (typeof suggest !== "function" && this.selectable.length === 0) { throw new Error("At least one choice must be selectable"); } if (isObject2(initial)) initial = Object.keys(initial); if (Array.isArray(initial)) { if (autofocus != null) this.index = this.findIndex(autofocus); initial.forEach((v) => this.enable(this.find(v))); await this.render(); } else { if (autofocus != null) initial = autofocus; if (typeof initial === "string") initial = this.findIndex(initial); if (typeof initial === "number" && initial > -1) { this.index = Math.max(0, Math.min(initial, this.choices.length)); this.enable(this.find(this.index)); } } if (this.isDisabled(this.focused)) { await this.down(); } } async toChoices(value, parent) { this.state.loadingChoices = true; let choices = []; let index = 0; let toChoices = async (items, parent2) => { if (typeof items === "function") items = await items.call(this); if (items instanceof Promise) items = await items; for (let i = 0; i < items.length; i++) { let choice = items[i] = await this.toChoice(items[i], index++, parent2); choices.push(choice); if (choice.choices) { await toChoices(choice.choices, choice); } } return choices; }; return toChoices(value, parent).then((choices2) => { this.state.loadingChoices = false; return choices2; }); } async toChoice(ele, i, parent) { if (typeof ele === "function") ele = await ele.call(this, this); if (ele instanceof Promise) ele = await ele; if (typeof ele === "string") ele = { name: ele }; if (ele.normalized) return ele; ele.normalized = true; let origVal = ele.value; let role = roles(ele.role, this.options); ele = role(this, ele); if (typeof ele.disabled === "string" && !ele.hint) { ele.hint = ele.disabled; ele.disabled = true; } if (ele.disabled === true && ele.hint == null) { ele.hint = "(disabled)"; } if (ele.index != null) return ele; ele.name = ele.name || ele.key || ele.title || ele.value || ele.message; ele.message = ele.message || ele.name || ""; ele.value = [ele.value, ele.name].find(this.isValue.bind(this)); ele.input = ""; ele.index = i; ele.cursor = 0; utils.define(ele, "parent", parent); ele.level = parent ? parent.level + 1 : 1; if (ele.indent == null) { ele.indent = parent ? parent.indent + " " : ele.indent || ""; } ele.path = parent ? parent.path + "." + ele.name : ele.name; ele.enabled = !!(this.multiple && !this.isDisabled(ele) && (ele.enabled || this.isSelected(ele))); if (!this.isDisabled(ele)) { this.longest = Math.max(this.longest, colors2.unstyle(ele.message).length); } let choice = { ...ele }; ele.reset = (input = choice.input, value = choice.value) => { for (let key of Object.keys(choice)) ele[key] = choice[key]; ele.input = input; ele.value = value; }; if (origVal == null && typeof ele.initial === "function") { ele.input = await ele.initial.call(this, this.state, ele, i); } return ele; } async onChoice(choice, i) { this.emit("choice", choice, i, this); if (typeof choice.onChoice === "function") { await choice.onChoice.call(this, this.state, choice, i); } } async addChoice(ele, i, parent) { let choice = await this.toChoice(ele, i, parent); this.choices.push(choice); this.index = this.choices.length - 1; this.limit = this.choices.length; return choice; } async newItem(item, i, parent) { let ele = { name: "New choice name?", editable: true, newChoice: true, ...item }; let choice = await this.addChoice(ele, i, parent); choice.updateChoice = () => { delete choice.newChoice; choice.name = choice.message = choice.input; choice.input = ""; choice.cursor = 0; }; return this.render(); } indent(choice) { if (choice.indent == null) { return choice.level > 1 ? " ".repeat(choice.level - 1) : ""; } return choice.indent; } dispatch(s, key) { if (this.multiple && this[key.name]) return this[key.name](); this.alert(); } focus(choice, enabled) { if (typeof enabled !== "boolean") enabled = choice.enabled; if (enabled && !choice.enabled && this.selected.length >= this.maxSelected) { return this.alert(); } this.index = choice.index; choice.enabled = enabled && !this.isDisabled(choice); return choice; } space() { if (!this.multiple) return this.alert(); this.toggle(this.focused); return this.render(); } a() { if (this.maxSelected < this.choices.length) return this.alert(); let enabled = this.selectable.every((ch) => ch.enabled); this.choices.forEach((ch) => ch.enabled = !enabled); return this.render(); } i() { if (this.choices.length - this.selected.length > this.maxSelected) { return this.alert(); } this.choices.forEach((ch) => ch.enabled = !ch.enabled); return this.render(); } g(choice = this.focused) { if (!this.choices.some((ch) => !!ch.parent)) return this.a(); this.toggle(choice.parent && !choice.choices ? choice.parent : choice); return this.render(); } toggle(choice, enabled) { if (!choice.enabled && this.selected.length >= this.maxSelected) { return this.alert(); } if (typeof enabled !== "boolean") enabled = !choice.enabled; choice.enabled = enabled; if (choice.choices) { choice.choices.forEach((ch) => this.toggle(ch, enabled)); } let parent = choice.parent; while (parent) { let choices = parent.choices.filter((ch) => this.isDisabled(ch)); parent.enabled = choices.every((ch) => ch.enabled === true); parent = parent.parent; } reset(this, this.choices); this.emit("toggle", choice, this); return choice; } enable(choice) { if (this.selected.length >= this.maxSelected) return this.alert(); choice.enabled = !this.isDisabled(choice); choice.choices && choice.choices.forEach(this.enable.bind(this)); return choice; } disable(choice) { choice.enabled = false; choice.choices && choice.choices.forEach(this.disable.bind(this)); return choice; } number(n) { this.num += n; let number4 = (num) => { let i = Number(num); if (i > this.choices.length - 1) return this.alert(); let focused = this.focused; let choice = this.choices.find((ch) => i === ch.index); if (!choice.enabled && this.selected.length >= this.maxSelected) { return this.alert(); } if (this.visible.indexOf(choice) === -1) { let choices = reorder(this.choices); let actualIdx = choices.indexOf(choice); if (focused.index > actualIdx) { let start = choices.slice(actualIdx, actualIdx + this.limit); let end = choices.filter((ch) => !start.includes(ch)); this.choices = start.concat(end); } else { let pos = actualIdx - this.limit + 1; this.choices = choices.slice(pos).concat(choices.slice(0, pos)); } } this.index = this.choices.indexOf(choice); this.toggle(this.focused); return this.render(); }; clearTimeout(this.numberTimeout); return new Promise((resolve) => { let len = this.choices.length; let num = this.num; let handle = (val = false, res) => { clearTimeout(this.numberTimeout); if (val) res = number4(num); this.num = ""; resolve(res); }; if (num === "0" || num.length === 1 && Number(num + "0") > len) { return handle(true); } if (Number(num) > len) { return handle(false, this.alert()); } this.numberTimeout = setTimeout(() => handle(true), this.delay); }); } home() { this.choices = reorder(this.choices); this.index = 0; return this.render(); } end() { let pos = this.choices.length - this.limit; let choices = reorder(this.choices); this.choices = choices.slice(pos).concat(choices.slice(0, pos)); this.index = this.limit - 1; return this.render(); } first() { this.index = 0; return this.render(); } last() { this.index = this.visible.length - 1; return this.render(); } prev() { if (this.visible.length <= 1) return this.alert(); return this.up(); } next() { if (this.visible.length <= 1) return this.alert(); return this.down(); } right() { if (this.cursor >= this.input.length) return this.alert(); this.cursor++; return this.render(); } left() { if (this.cursor <= 0) return this.alert(); this.cursor--; return this.render(); } up() { let len = this.choices.length; let vis = this.visible.length; let idx = this.index; if (this.options.scroll === false && idx === 0) { return this.alert(); } if (len > vis && idx === 0) { return this.scrollUp(); } this.index = (idx - 1 % len + len) % len; if (this.isDisabled()) { return this.up(); } return this.render(); } down() { let len = this.choices.length; let vis = this.visible.length; let idx = this.index; if (this.options.scroll === false && idx === vis - 1) { return this.alert(); } if (len > vis && idx === vis - 1) { return this.scrollDown(); } this.index = (idx + 1) % len; if (this.isDisabled()) { return this.down(); } return this.render(); } scrollUp(i = 0) { this.choices = scrollUp(this.choices); this.index = i; if (this.isDisabled()) { return this.up(); } return this.render(); } scrollDown(i = this.visible.length - 1) { this.choices = scrollDown(this.choices); this.index = i; if (this.isDisabled()) { return this.down(); } return this.render(); } async shiftUp() { if (this.options.sort === true) { this.sorting = true; this.swap(this.index - 1); await this.up(); this.sorting = false; return; } return this.scrollUp(this.index); } async shiftDown() { if (this.options.sort === true) { this.sorting = true; this.swap(this.index + 1); await this.down(); this.sorting = false; return; } return this.scrollDown(this.index); } pageUp() { if (this.visible.length <= 1) return this.alert(); this.limit = Math.max(this.limit - 1, 0); this.index = Math.min(this.limit - 1, this.index); this._limit = this.limit; if (this.isDisabled()) { return this.up(); } return this.render(); } pageDown() { if (this.visible.length >= this.choices.length) return this.alert(); this.index = Math.max(0, this.index); this.limit = Math.min(this.limit + 1, this.choices.length); this._limit = this.limit; if (this.isDisabled()) { return this.down(); } return this.render(); } swap(pos) { swap(this.choices, this.index, pos); } isDisabled(choice = this.focused) { let keys = ["disabled", "collapsed", "hidden", "completing", "readonly"]; if (choice && keys.some((key) => choice[key] === true)) { return true; } return choice && choice.role === "heading"; } isEnabled(choice = this.focused) { if (Array.isArray(choice)) return choice.every((ch) => this.isEnabled(ch)); if (choice.choices) { let choices = choice.choices.filter((ch) => !this.isDisabled(ch)); return choice.enabled && choices.every((ch) => this.isEnabled(ch)); } return choice.enabled && !this.isDisabled(choice); } isChoice(choice, value) { return choice.name === value || choice.index === Number(value); } isSelected(choice) { if (Array.isArray(this.initial)) { return this.initial.some((value) => this.isChoice(choice, value)); } return this.isChoice(choice, this.initial); } map(names = [], prop = "value") { return [].concat(names || []).reduce((acc, name) => { acc[name] = this.find(name, prop); return acc; }, {}); } filter(value, prop) { let isChoice = (ele, i) => [ele.name, i].includes(value); let fn = typeof value === "function" ? value : isChoice; let choices = this.options.multiple ? this.state._choices : this.choices; let result = choices.filter(fn); if (prop) { return result.map((ch) => ch[prop]); } return result; } find(value, prop) { if (isObject2(value)) return prop ? value[prop] : value; let isChoice = (ele, i) => [ele.name, i].includes(value); let fn = typeof value === "function" ? value : isChoice; let choice = this.choices.find(fn); if (choice) { return prop ? choice[prop] : choice; } } findIndex(value) { return this.choices.indexOf(this.find(value)); } async submit() { let choice = this.focused; if (!choice) return this.alert(); if (choice.newChoice) { if (!choice.input) return this.alert(); choice.updateChoice(); return this.render(); } if (this.choices.some((ch) => ch.newChoice)) { return this.alert(); } let { reorder: reorder2, sort } = this.options; let multi = this.multiple === true; let value = this.selected; if (value === void 0) { return this.alert(); } if (Array.isArray(value) && reorder2 !== false && sort !== true) { value = utils.reorder(value); } this.value = multi ? value.map((ch) => ch.name) : value.name; return super.submit(); } set choices(choices = []) { this.state._choices = this.state._choices || []; this.state.choices = choices; for (let choice of choices) { if (!this.state._choices.some((ch) => ch.name === choice.name)) { this.state._choices.push(choice); } } if (!this._initial && this.options.initial) { this._initial = true; let init = this.initial; if (typeof init === "string" || typeof init === "number") { let choice = this.find(init); if (choice) { this.initial = choice.index; this.focus(choice, true); } } } } get choices() { return reset(this, this.state.choices || []); } set visible(visible) { this.state.visible = visible; } get visible() { return (this.state.visible || this.choices).slice(0, this.limit); } set limit(num) { this.state.limit = num; } get limit() { let { state, options, choices } = this; let limit = state.limit || this._limit || options.limit || choices.length; return Math.min(limit, this.height); } set value(value) { super.value = value; } get value() { if (typeof super.value !== "string" && super.value === this.initial) { return this.input; } return super.value; } set index(i) { this.state.index = i; } get index() { return Math.max(0, this.state ? this.state.index : 0); } get enabled() { return this.filter(this.isEnabled.bind(this)); } get focused() { let choice = this.choices[this.index]; if (choice && this.state.submitted && this.multiple !== true) { choice.enabled = true; } return choice; } get selectable() { return this.choices.filter((choice) => !this.isDisabled(choice)); } get selected() { return this.multiple ? this.enabled : this.focused; } }; function reset(prompt, choices) { if (choices instanceof Promise) return choices; if (typeof choices === "function") { if (utils.isAsyncFn(choices)) return choices; choices = choices.call(prompt, prompt); } for (let choice of choices) { if (Array.isArray(choice.choices)) { let items = choice.choices.filter((ch) => !prompt.isDisabled(ch)); choice.enabled = items.every((ch) => ch.enabled === true); } if (prompt.isDisabled(choice) === true) { delete choice.enabled; } } return choices; } module2.exports = ArrayPrompt; } }); // node_modules/enquirer/lib/prompts/select.js var require_select = __commonJS({ "node_modules/enquirer/lib/prompts/select.js"(exports2, module2) { "use strict"; var ArrayPrompt = require_array(); var utils = require_utils2(); var SelectPrompt = class extends ArrayPrompt { constructor(options) { super(options); this.emptyError = this.options.emptyError || "No items were selected"; } async dispatch(s, key) { if (this.multiple) { return this[key.name] ? await this[key.name](s, key) : await super.dispatch(s, key); } this.alert(); } separator() { if (this.options.separator) return super.separator(); let sep = this.styles.muted(this.symbols.ellipsis); return this.state.submitted ? super.separator() : sep; } pointer(choice, i) { return !this.multiple || this.options.pointer ? super.pointer(choice, i) : ""; } indicator(choice, i) { return this.multiple ? super.indicator(choice, i) : ""; } choiceMessage(choice, i) { let message = this.resolve(choice.message, this.state, choice, i); if (choice.role === "heading" && !utils.hasColor(message)) { message = this.styles.strong(message); } return this.resolve(message, this.state, choice, i); } choiceSeparator() { return ":"; } async renderChoice(choice, i) { await this.onChoice(choice, i); let focused = this.index === i; let pointer = await this.pointer(choice, i); let check2 = await this.indicator(choice, i) + (choice.pad || ""); let hint = await this.resolve(choice.hint, this.state, choice, i); if (hint && !utils.hasColor(hint)) { hint = this.styles.muted(hint); } let ind = this.indent(choice); let msg = await this.choiceMessage(choice, i); let line = () => [this.margin[3], ind + pointer + check2, msg, this.margin[1], hint].filter(Boolean).join(" "); if (choice.role === "heading") { return line(); } if (choice.disabled) { if (!utils.hasColor(msg)) { msg = this.styles.disabled(msg); } return line(); } if (focused) { msg = this.styles.em(msg); } return line(); } async renderChoices() { if (this.state.loading === "choices") { return this.styles.warning("Loading choices"); } if (this.state.submitted) return ""; let choices = this.visible.map(async (ch, i) => await this.renderChoice(ch, i)); let visible = await Promise.all(choices); if (!visible.length) visible.push(this.styles.danger("No matching choices")); let result = this.margin[0] + visible.join("\n"); let header; if (this.options.choicesHeader) { header = await this.resolve(this.options.choicesHeader, this.state); } return [header, result].filter(Boolean).join("\n"); } format() { if (!this.state.submitted || this.state.cancelled) return ""; if (Array.isArray(this.selected)) { return this.selected.map((choice) => this.styles.primary(choice.name)).join(", "); } return this.styles.primary(this.selected.name); } async render() { let { submitted, size } = this.state; let prompt = ""; let header = await this.header(); let prefix = await this.prefix(); let separator = await this.separator(); let message = await this.message(); if (this.options.promptLine !== false) { prompt = [prefix, message, separator, ""].join(" "); this.state.prompt = prompt; } let output = await this.format(); let help = await this.error() || await this.hint(); let body = await this.renderChoices(); let footer = await this.footer(); if (output) prompt += output; if (help && !prompt.includes(help)) prompt += " " + help; if (submitted && !output && !body.trim() && this.multiple && this.emptyError != null) { prompt += this.styles.danger(this.emptyError); } this.clear(size); this.write([header, prompt, body, footer].filter(Boolean).join("\n")); this.write(this.margin[2]); this.restore(); } }; module2.exports = SelectPrompt; } }); // node_modules/enquirer/lib/prompts/autocomplete.js var require_autocomplete = __commonJS({ "node_modules/enquirer/lib/prompts/autocomplete.js"(exports2, module2) { "use strict"; var Select = require_select(); var highlight = (input, color) => { let val = input.toLowerCase(); return (str) => { let s = str.toLowerCase(); let i = s.indexOf(val); let colored = color(str.slice(i, i + val.length)); return i >= 0 ? str.slice(0, i) + colored + str.slice(i + val.length) : str; }; }; var AutoComplete = class extends Select { constructor(options) { super(options); this.cursorShow(); } moveCursor(n) { this.state.cursor += n; } dispatch(ch) { return this.append(ch); } space(ch) { return this.options.multiple ? super.space(ch) : this.append(ch); } append(ch) { let { cursor, input } = this.state; this.input = input.slice(0, cursor) + ch + input.slice(cursor); this.moveCursor(1); return this.complete(); } delete() { let { cursor, input } = this.state; if (!input) return this.alert(); this.input = input.slice(0, cursor - 1) + input.slice(cursor); this.moveCursor(-1); return this.complete(); } deleteForward() { let { cursor, input } = this.state; if (input[cursor] === void 0) return this.alert(); this.input = `${input}`.slice(0, cursor) + `${input}`.slice(cursor + 1); return this.complete(); } number(ch) { return this.append(ch); } async complete() { this.completing = true; this.choices = await this.suggest(this.input, this.state._choices); this.state.limit = void 0; this.index = Math.min(Math.max(this.visible.length - 1, 0), this.index); await this.render(); this.completing = false; } suggest(input = this.input, choices = this.state._choices) { if (typeof this.options.suggest === "function") { return this.options.suggest.call(this, input, choices); } let str = input.toLowerCase(); return choices.filter((ch) => ch.message.toLowerCase().includes(str)); } pointer() { return ""; } format() { if (!this.focused) return this.input; if (this.options.multiple && this.state.submitted) { return this.selected.map((ch) => this.styles.primary(ch.message)).join(", "); } if (this.state.submitted) { let value = this.value = this.input = this.focused.value; return this.styles.primary(value); } return this.input; } async render() { if (this.state.status !== "pending") return super.render(); let style = this.options.highlight ? this.options.highlight.bind(this) : this.styles.placeholder; let color = highlight(this.input, style); let choices = this.choices; this.choices = choices.map((ch) => ({ ...ch, message: color(ch.message) })); await super.render(); this.choices = choices; } submit() { if (this.options.multiple) { this.value = this.selected.map((ch) => ch.name); } return super.submit(); } }; module2.exports = AutoComplete; } }); // node_modules/enquirer/lib/placeholder.js var require_placeholder = __commonJS({ "node_modules/enquirer/lib/placeholder.js"(exports2, module2) { "use strict"; var utils = require_utils2(); module2.exports = (prompt, options = {}) => { prompt.cursorHide(); let { input = "", initial = "", pos, showCursor = true, color } = options; let style = color || prompt.styles.placeholder; let inverse = utils.inverse(prompt.styles.primary); let blinker = (str) => inverse(prompt.styles.black(str)); let output = input; let char = " "; let reverse = blinker(char); if (prompt.blink && prompt.blink.off === true) { blinker = (str) => str; reverse = ""; } if (showCursor && pos === 0 && initial === "" && input === "") { return blinker(char); } if (showCursor && pos === 0 && (input === initial || input === "")) { return blinker(initial[0]) + style(initial.slice(1)); } initial = utils.isPrimitive(initial) ? `${initial}` : ""; input = utils.isPrimitive(input) ? `${input}` : ""; let placeholder = initial && initial.startsWith(input) && initial !== input; let cursor = placeholder ? blinker(initial[input.length]) : reverse; if (pos !== input.length && showCursor === true) { output = input.slice(0, pos) + blinker(input[pos]) + input.slice(pos + 1); cursor = ""; } if (showCursor === false) { cursor = ""; } if (placeholder) { let raw = prompt.styles.unstyle(output + cursor); return output + cursor + style(initial.slice(raw.length)); } return output + cursor; }; } }); // node_modules/enquirer/lib/prompts/form.js var require_form = __commonJS({ "node_modules/enquirer/lib/prompts/form.js"(exports2, module2) { "use strict"; var colors2 = require_ansi_colors(); var SelectPrompt = require_select(); var placeholder = require_placeholder(); var FormPrompt = class extends SelectPrompt { constructor(options) { super({ ...options, multiple: true }); this.type = "form"; this.initial = this.options.initial; this.align = [this.options.align, "right"].find((v) => v != null); this.emptyError = ""; this.values = {}; } async reset(first) { await super.reset(); if (first === true) this._index = this.index; this.index = this._index; this.values = {}; this.choices.forEach((choice) => choice.reset && choice.reset()); return this.render(); } dispatch(char) { return !!char && this.append(char); } append(char) { let choice = this.focused; if (!choice) return this.alert(); let { cursor, input } = choice; choice.value = choice.input = input.slice(0, cursor) + char + input.slice(cursor); choice.cursor++; return this.render(); } delete() { let choice = this.focused; if (!choice || choice.cursor <= 0) return this.alert(); let { cursor, input } = choice; choice.value = choice.input = input.slice(0, cursor - 1) + input.slice(cursor); choice.cursor--; return this.render(); } deleteForward() { let choice = this.focused; if (!choice) return this.alert(); let { cursor, input } = choice; if (input[cursor] === void 0) return this.alert(); let str = `${input}`.slice(0, cursor) + `${input}`.slice(cursor + 1); choice.value = choice.input = str; return this.render(); } right() { let choice = this.focused; if (!choice) return this.alert(); if (choice.cursor >= choice.input.length) return this.alert(); choice.cursor++; return this.render(); } left() { let choice = this.focused; if (!choice) return this.alert(); if (choice.cursor <= 0) return this.alert(); choice.cursor--; return this.render(); } space(ch, key) { return this.dispatch(ch, key); } number(ch, key) { return this.dispatch(ch, key); } next() { let ch = this.focused; if (!ch) return this.alert(); let { initial, input } = ch; if (initial && initial.startsWith(input) && input !== initial) { ch.value = ch.input = initial; ch.cursor = ch.value.length; return this.render(); } return super.next(); } prev() { let ch = this.focused; if (!ch) return this.alert(); if (ch.cursor === 0) return super.prev(); ch.value = ch.input = ""; ch.cursor = 0; return this.render(); } separator() { return ""; } format(value) { return !this.state.submitted ? super.format(value) : ""; } pointer() { return ""; } indicator(choice) { return choice.input ? "\u29BF" : "\u2299"; } async choiceSeparator(choice, i) { let sep = await this.resolve(choice.separator, this.state, choice, i) || ":"; return sep ? " " + this.styles.disabled(sep) : ""; } async renderChoice(choice, i) { await this.onChoice(choice, i); let { state, styles } = this; let { cursor, initial = "", name, hint, input = "" } = choice; let { muted, submitted, primary, danger } = styles; let help = hint; let focused = this.index === i; let validate2 = choice.validate || (() => true); let sep = await this.choiceSeparator(choice, i); let msg = choice.message; if (this.align === "right") msg = msg.padStart(this.longest + 1, " "); if (this.align === "left") msg = msg.padEnd(this.longest + 1, " "); let value = this.values[name] = input || initial; let color = input ? "success" : "dark"; if (await validate2.call(choice, value, this.state) !== true) { color = "danger"; } let style = styles[color]; let indicator = style(await this.indicator(choice, i)) + (choice.pad || ""); let indent = this.indent(choice); let line = () => [indent, indicator, msg + sep, input, help].filter(Boolean).join(" "); if (state.submitted) { msg = colors2.unstyle(msg); input = submitted(input); help = ""; return line(); } if (choice.format) { input = await choice.format.call(this, input, choice, i); } else { let color2 = this.styles.muted; let options = { input, initial, pos: cursor, showCursor: focused, color: color2 }; input = placeholder(this, options); } if (!this.isValue(input)) { input = this.styles.muted(this.symbols.ellipsis); } if (choice.result) { this.values[name] = await choice.result.call(this, value, choice, i); } if (focused) { msg = primary(msg); } if (choice.error) { input += (input ? " " : "") + danger(choice.error.trim()); } else if (choice.hint) { input += (input ? " " : "") + muted(choice.hint.trim()); } return line(); } async submit() { this.value = this.values; return super.base.submit.call(this); } }; module2.exports = FormPrompt; } }); // node_modules/enquirer/lib/types/auth.js var require_auth = __commonJS({ "node_modules/enquirer/lib/types/auth.js"(exports2, module2) { "use strict"; var FormPrompt = require_form(); var defaultAuthenticate = () => { throw new Error("expected prompt to have a custom authenticate method"); }; var factory = (authenticate = defaultAuthenticate) => { class AuthPrompt extends FormPrompt { constructor(options) { super(options); } async submit() { this.value = await authenticate.call(this, this.values, this.state); super.base.submit.call(this); } static create(authenticate2) { return factory(authenticate2); } } return AuthPrompt; }; module2.exports = factory(); } }); // node_modules/enquirer/lib/prompts/basicauth.js var require_basicauth = __commonJS({ "node_modules/enquirer/lib/prompts/basicauth.js"(exports2, module2) { "use strict"; var AuthPrompt = require_auth(); function defaultAuthenticate(value, state) { if (value.username === this.options.username && value.password === this.options.password) { return true; } return false; } var factory = (authenticate = defaultAuthenticate) => { const choices = [ { name: "username", message: "username" }, { name: "password", message: "password", format(input) { if (this.options.showPassword) { return input; } let color = this.state.submitted ? this.styles.primary : this.styles.muted; return color(this.symbols.asterisk.repeat(input.length)); } } ]; class BasicAuthPrompt extends AuthPrompt.create(authenticate) { constructor(options) { super({ ...options, choices }); } static create(authenticate2) { return factory(authenticate2); } } return BasicAuthPrompt; }; module2.exports = factory(); } }); // node_modules/enquirer/lib/types/boolean.js var require_boolean = __commonJS({ "node_modules/enquirer/lib/types/boolean.js"(exports2, module2) { "use strict"; var Prompt = require_prompt(); var { isPrimitive, hasColor } = require_utils2(); var BooleanPrompt = class extends Prompt { constructor(options) { super(options); this.cursorHide(); } async initialize() { let initial = await this.resolve(this.initial, this.state); this.input = await this.cast(initial); await super.initialize(); } dispatch(ch) { if (!this.isValue(ch)) return this.alert(); this.input = ch; return this.submit(); } format(value) { let { styles, state } = this; return !state.submitted ? styles.primary(value) : styles.success(value); } cast(input) { return this.isTrue(input); } isTrue(input) { return /^[ty1]/i.test(input); } isFalse(input) { return /^[fn0]/i.test(input); } isValue(value) { return isPrimitive(value) && (this.isTrue(value) || this.isFalse(value)); } async hint() { if (this.state.status === "pending") { let hint = await this.element("hint"); if (!hasColor(hint)) { return this.styles.muted(hint); } return hint; } } async render() { let { input, size } = this.state; let prefix = await this.prefix(); let sep = await this.separator(); let msg = await this.message(); let hint = this.styles.muted(this.default); let promptLine = [prefix, msg, hint, sep].filter(Boolean).join(" "); this.state.prompt = promptLine; let header = await this.header(); let value = this.value = this.cast(input); let output = await this.format(value); let help = await this.error() || await this.hint(); let footer = await this.footer(); if (help && !promptLine.includes(help)) output += " " + help; promptLine += " " + output; this.clear(size); this.write([header, promptLine, footer].filter(Boolean).join("\n")); this.restore(); } set value(value) { super.value = value; } get value() { return this.cast(super.value); } }; module2.exports = BooleanPrompt; } }); // node_modules/enquirer/lib/prompts/confirm.js var require_confirm = __commonJS({ "node_modules/enquirer/lib/prompts/confirm.js"(exports2, module2) { "use strict"; var BooleanPrompt = require_boolean(); var ConfirmPrompt = class extends BooleanPrompt { constructor(options) { super(options); this.default = this.options.default || (this.initial ? "(Y/n)" : "(y/N)"); } }; module2.exports = ConfirmPrompt; } }); // node_modules/enquirer/lib/prompts/editable.js var require_editable = __commonJS({ "node_modules/enquirer/lib/prompts/editable.js"(exports2, module2) { "use strict"; var Select = require_select(); var Form = require_form(); var form = Form.prototype; var Editable = class extends Select { constructor(options) { super({ ...options, multiple: true }); this.align = [this.options.align, "left"].find((v) => v != null); this.emptyError = ""; this.values = {}; } dispatch(char, key) { let choice = this.focused; let parent = choice.parent || {}; if (!choice.editable && !parent.editable) { if (char === "a" || char === "i") return super[char](); } return form.dispatch.call(this, char, key); } append(char, key) { return form.append.call(this, char, key); } delete(char, key) { return form.delete.call(this, char, key); } space(char) { return this.focused.editable ? this.append(char) : super.space(); } number(char) { return this.focused.editable ? this.append(char) : super.number(char); } next() { return this.focused.editable ? form.next.call(this) : super.next(); } prev() { return this.focused.editable ? form.prev.call(this) : super.prev(); } async indicator(choice, i) { let symbol2 = choice.indicator || ""; let value = choice.editable ? symbol2 : super.indicator(choice, i); return await this.resolve(value, this.state, choice, i) || ""; } indent(choice) { return choice.role === "heading" ? "" : choice.editable ? " " : " "; } async renderChoice(choice, i) { choice.indent = ""; if (choice.editable) return form.renderChoice.call(this, choice, i); return super.renderChoice(choice, i); } error() { return ""; } footer() { return this.state.error; } async validate() { let result = true; for (let choice of this.choices) { if (typeof choice.validate !== "function") { continue; } if (choice.role === "heading") { continue; } let val = choice.parent ? this.value[choice.parent.name] : this.value; if (choice.editable) { val = choice.value === choice.name ? choice.initial || "" : choice.value; } else if (!this.isDisabled(choice)) { val = choice.enabled === true; } result = await choice.validate(val, this.state); if (result !== true) { break; } } if (result !== true) { this.state.error = typeof result === "string" ? result : "Invalid Input"; } return result; } submit() { if (this.focused.newChoice === true) return super.submit(); if (this.choices.some((ch) => ch.newChoice)) { return this.alert(); } this.value = {}; for (let choice of this.choices) { let val = choice.parent ? this.value[choice.parent.name] : this.value; if (choice.role === "heading") { this.value[choice.name] = {}; continue; } if (choice.editable) { val[choice.name] = choice.value === choice.name ? choice.initial || "" : choice.value; } else if (!this.isDisabled(choice)) { val[choice.name] = choice.enabled === true; } } return this.base.submit.call(this); } }; module2.exports = Editable; } }); // node_modules/enquirer/lib/types/string.js var require_string2 = __commonJS({ "node_modules/enquirer/lib/types/string.js"(exports2, module2) { "use strict"; var Prompt = require_prompt(); var placeholder = require_placeholder(); var { isPrimitive } = require_utils2(); var StringPrompt = class extends Prompt { constructor(options) { super(options); this.initial = isPrimitive(this.initial) ? String(this.initial) : ""; if (this.initial) this.cursorHide(); this.state.prevCursor = 0; this.state.clipboard = []; } async keypress(input, key = {}) { let prev = this.state.prevKeypress; this.state.prevKeypress = key; if (this.options.multiline === true && key.name === "return") { if (!prev || prev.name !== "return") { return this.append("\n", key); } } return super.keypress(input, key); } moveCursor(n) { this.cursor += n; } reset() { this.input = this.value = ""; this.cursor = 0; return this.render(); } dispatch(ch, key) { if (!ch || key.ctrl || key.code) return this.alert(); this.append(ch); } append(ch) { let { cursor, input } = this.state; this.input = `${input}`.slice(0, cursor) + ch + `${input}`.slice(cursor); this.moveCursor(String(ch).length); this.render(); } insert(str) { this.append(str); } delete() { let { cursor, input } = this.state; if (cursor <= 0) return this.alert(); this.input = `${input}`.slice(0, cursor - 1) + `${input}`.slice(cursor); this.moveCursor(-1); this.render(); } deleteForward() { let { cursor, input } = this.state; if (input[cursor] === void 0) return this.alert(); this.input = `${input}`.slice(0, cursor) + `${input}`.slice(cursor + 1); this.render(); } cutForward() { let pos = this.cursor; if (this.input.length <= pos) return this.alert(); this.state.clipboard.push(this.input.slice(pos)); this.input = this.input.slice(0, pos); this.render(); } cutLeft() { let pos = this.cursor; if (pos === 0) return this.alert(); let before = this.input.slice(0, pos); let after = this.input.slice(pos); let words = before.split(" "); this.state.clipboard.push(words.pop()); this.input = words.join(" "); this.cursor = this.input.length; this.input += after; this.render(); } paste() { if (!this.state.clipboard.length) return this.alert(); this.insert(this.state.clipboard.pop()); this.render(); } toggleCursor() { if (this.state.prevCursor) { this.cursor = this.state.prevCursor; this.state.prevCursor = 0; } else { this.state.prevCursor = this.cursor; this.cursor = 0; } this.render(); } first() { this.cursor = 0; this.render(); } last() { this.cursor = this.input.length - 1; this.render(); } next() { let init = this.initial != null ? String(this.initial) : ""; if (!init || !init.startsWith(this.input)) return this.alert(); this.input = this.initial; this.cursor = this.initial.length; this.render(); } prev() { if (!this.input) return this.alert(); this.reset(); } backward() { return this.left(); } forward() { return this.right(); } right() { if (this.cursor >= this.input.length) return this.alert(); this.moveCursor(1); return this.render(); } left() { if (this.cursor <= 0) return this.alert(); this.moveCursor(-1); return this.render(); } isValue(value) { return !!value; } async format(input = this.value) { let initial = await this.resolve(this.initial, this.state); if (!this.state.submitted) { return placeholder(this, { input, initial, pos: this.cursor }); } return this.styles.submitted(input || initial); } async render() { let size = this.state.size; let prefix = await this.prefix(); let separator = await this.separator(); let message = await this.message(); let prompt = [prefix, message, separator].filter(Boolean).join(" "); this.state.prompt = prompt; let header = await this.header(); let output = await this.format(); let help = await this.error() || await this.hint(); let footer = await this.footer(); if (help && !output.includes(help)) output += " " + help; prompt += " " + output; this.clear(size); this.write([header, prompt, footer].filter(Boolean).join("\n")); this.restore(); } }; module2.exports = StringPrompt; } }); // node_modules/enquirer/lib/completer.js var require_completer = __commonJS({ "node_modules/enquirer/lib/completer.js"(exports2, module2) { "use strict"; var unique = (arr) => arr.filter((v, i) => arr.lastIndexOf(v) === i); var compact = (arr) => unique(arr).filter(Boolean); module2.exports = (action, data = {}, value = "") => { let { past = [], present = "" } = data; let rest, prev; switch (action) { case "prev": case "undo": rest = past.slice(0, past.length - 1); prev = past[past.length - 1] || ""; return { past: compact([value, ...rest]), present: prev }; case "next": case "redo": rest = past.slice(1); prev = past[0] || ""; return { past: compact([...rest, value]), present: prev }; case "save": return { past: compact([...past, value]), present: "" }; case "remove": prev = compact(past.filter((v) => v !== value)); present = ""; if (prev.length) { present = prev.pop(); } return { past: prev, present }; default: { throw new Error(`Invalid action: "${action}"`); } } }; } }); // node_modules/enquirer/lib/prompts/input.js var require_input = __commonJS({ "node_modules/enquirer/lib/prompts/input.js"(exports2, module2) { "use strict"; var Prompt = require_string2(); var completer = require_completer(); var Input = class extends Prompt { constructor(options) { super(options); let history = this.options.history; if (history && history.store) { let initial = history.values || this.initial; this.autosave = !!history.autosave; this.store = history.store; this.data = this.store.get("values") || { past: [], present: initial }; this.initial = this.data.present || this.data.past[this.data.past.length - 1]; } } completion(action) { if (!this.store) return this.alert(); this.data = completer(action, this.data, this.input); if (!this.data.present) return this.alert(); this.input = this.data.present; this.cursor = this.input.length; return this.render(); } altUp() { return this.completion("prev"); } altDown() { return this.completion("next"); } prev() { this.save(); return super.prev(); } save() { if (!this.store) return; this.data = completer("save", this.data, this.input); this.store.set("values", this.data); } submit() { if (this.store && this.autosave === true) { this.save(); } return super.submit(); } }; module2.exports = Input; } }); // node_modules/enquirer/lib/prompts/invisible.js var require_invisible = __commonJS({ "node_modules/enquirer/lib/prompts/invisible.js"(exports2, module2) { "use strict"; var StringPrompt = require_string2(); var InvisiblePrompt = class extends StringPrompt { format() { return ""; } }; module2.exports = InvisiblePrompt; } }); // node_modules/enquirer/lib/prompts/list.js var require_list = __commonJS({ "node_modules/enquirer/lib/prompts/list.js"(exports2, module2) { "use strict"; var StringPrompt = require_string2(); var ListPrompt = class extends StringPrompt { constructor(options = {}) { super(options); this.sep = this.options.separator || /, */; this.initial = options.initial || ""; } split(input = this.value) { return input ? String(input).split(this.sep) : []; } format() { let style = this.state.submitted ? this.styles.primary : (val) => val; return this.list.map(style).join(", "); } async submit(value) { let result = this.state.error || await this.validate(this.list, this.state); if (result !== true) { this.state.error = result; return super.submit(); } this.value = this.list; return super.submit(); } get list() { return this.split(); } }; module2.exports = ListPrompt; } }); // node_modules/enquirer/lib/prompts/multiselect.js var require_multiselect = __commonJS({ "node_modules/enquirer/lib/prompts/multiselect.js"(exports2, module2) { "use strict"; var Select = require_select(); var MultiSelect = class extends Select { constructor(options) { super({ ...options, multiple: true }); } }; module2.exports = MultiSelect; } }); // node_modules/enquirer/lib/types/number.js var require_number = __commonJS({ "node_modules/enquirer/lib/types/number.js"(exports2, module2) { "use strict"; var StringPrompt = require_string2(); var NumberPrompt = class extends StringPrompt { constructor(options = {}) { super({ style: "number", ...options }); this.min = this.isValue(options.min) ? this.toNumber(options.min) : -Infinity; this.max = this.isValue(options.max) ? this.toNumber(options.max) : Infinity; this.delay = options.delay != null ? options.delay : 1e3; this.float = options.float !== false; this.round = options.round === true || options.float === false; this.major = options.major || 10; this.minor = options.minor || 1; this.initial = options.initial != null ? options.initial : ""; this.input = String(this.initial); this.cursor = this.input.length; this.cursorShow(); } append(ch) { if (!/[-+.]/.test(ch) || ch === "." && this.input.includes(".")) { return this.alert("invalid number"); } return super.append(ch); } number(ch) { return super.append(ch); } next() { if (this.input && this.input !== this.initial) return this.alert(); if (!this.isValue(this.initial)) return this.alert(); this.input = this.initial; this.cursor = String(this.initial).length; return this.render(); } up(number4) { let step = number4 || this.minor; let num = this.toNumber(this.input); if (num > this.max + step) return this.alert(); this.input = `${num + step}`; return this.render(); } down(number4) { let step = number4 || this.minor; let num = this.toNumber(this.input); if (num < this.min - step) return this.alert(); this.input = `${num - step}`; return this.render(); } shiftDown() { return this.down(this.major); } shiftUp() { return this.up(this.major); } format(input = this.input) { if (typeof this.options.format === "function") { return this.options.format.call(this, input); } return this.styles.info(input); } toNumber(value = "") { return this.float ? +value : Math.round(+value); } isValue(value) { return /^[-+]?[0-9]+((\.)|(\.[0-9]+))?$/.test(value); } submit() { let value = [this.input, this.initial].find((v) => this.isValue(v)); this.value = this.toNumber(value || 0); return super.submit(); } }; module2.exports = NumberPrompt; } }); // node_modules/enquirer/lib/prompts/numeral.js var require_numeral = __commonJS({ "node_modules/enquirer/lib/prompts/numeral.js"(exports2, module2) { module2.exports = require_number(); } }); // node_modules/enquirer/lib/prompts/password.js var require_password = __commonJS({ "node_modules/enquirer/lib/prompts/password.js"(exports2, module2) { "use strict"; var StringPrompt = require_string2(); var PasswordPrompt = class extends StringPrompt { constructor(options) { super(options); this.cursorShow(); } format(input = this.input) { if (!this.keypressed) return ""; let color = this.state.submitted ? this.styles.primary : this.styles.muted; return color(this.symbols.asterisk.repeat(input.length)); } }; module2.exports = PasswordPrompt; } }); // node_modules/enquirer/lib/prompts/scale.js var require_scale = __commonJS({ "node_modules/enquirer/lib/prompts/scale.js"(exports2, module2) { "use strict"; var colors2 = require_ansi_colors(); var ArrayPrompt = require_array(); var utils = require_utils2(); var LikertScale = class extends ArrayPrompt { constructor(options = {}) { super(options); this.widths = [].concat(options.messageWidth || 50); this.align = [].concat(options.align || "left"); this.linebreak = options.linebreak || false; this.edgeLength = options.edgeLength || 3; this.newline = options.newline || "\n "; let start = options.startNumber || 1; if (typeof this.scale === "number") { this.scaleKey = false; this.scale = Array(this.scale).fill(0).map((v, i) => ({ name: i + start })); } } async reset() { this.tableized = false; await super.reset(); return this.render(); } tableize() { if (this.tableized === true) return; this.tableized = true; let longest = 0; for (let ch of this.choices) { longest = Math.max(longest, ch.message.length); ch.scaleIndex = ch.initial || 2; ch.scale = []; for (let i = 0; i < this.scale.length; i++) { ch.scale.push({ index: i }); } } this.widths[0] = Math.min(this.widths[0], longest + 3); } async dispatch(s, key) { if (this.multiple) { return this[key.name] ? await this[key.name](s, key) : await super.dispatch(s, key); } this.alert(); } heading(msg, item, i) { return this.styles.strong(msg); } separator() { return this.styles.muted(this.symbols.ellipsis); } right() { let choice = this.focused; if (choice.scaleIndex >= this.scale.length - 1) return this.alert(); choice.scaleIndex++; return this.render(); } left() { let choice = this.focused; if (choice.scaleIndex <= 0) return this.alert(); choice.scaleIndex--; return this.render(); } indent() { return ""; } format() { if (this.state.submitted) { let values = this.choices.map((ch) => this.styles.info(ch.index)); return values.join(", "); } return ""; } pointer() { return ""; } /** * Render the scale "Key". Something like: * @return {String} */ renderScaleKey() { if (this.scaleKey === false) return ""; if (this.state.submitted) return ""; let scale = this.scale.map((item) => ` ${item.name} - ${item.message}`); let key = ["", ...scale].map((item) => this.styles.muted(item)); return key.join("\n"); } /** * Render the heading row for the scale. * @return {String} */ renderScaleHeading(max) { let keys = this.scale.map((ele) => ele.name); if (typeof this.options.renderScaleHeading === "function") { keys = this.options.renderScaleHeading.call(this, max); } let diff2 = this.scaleLength - keys.join("").length; let spacing = Math.round(diff2 / (keys.length - 1)); let names = keys.map((key) => this.styles.strong(key)); let headings = names.join(" ".repeat(spacing)); let padding = " ".repeat(this.widths[0]); return this.margin[3] + padding + this.margin[1] + headings; } /** * Render a scale indicator => â—¯ or â—‰ by default */ scaleIndicator(choice, item, i) { if (typeof this.options.scaleIndicator === "function") { return this.options.scaleIndicator.call(this, choice, item, i); } let enabled = choice.scaleIndex === item.index; if (item.disabled) return this.styles.hint(this.symbols.radio.disabled); if (enabled) return this.styles.success(this.symbols.radio.on); return this.symbols.radio.off; } /** * Render the actual scale => ◯────◯────◉────◯────◯ */ renderScale(choice, i) { let scale = choice.scale.map((item) => this.scaleIndicator(choice, item, i)); let padding = this.term === "Hyper" ? "" : " "; return scale.join(padding + this.symbols.line.repeat(this.edgeLength)); } /** * Render a choice, including scale => * "The website is easy to navigate. ◯───◯───◉───◯───◯" */ async renderChoice(choice, i) { await this.onChoice(choice, i); let focused = this.index === i; let pointer = await this.pointer(choice, i); let hint = await choice.hint; if (hint && !utils.hasColor(hint)) { hint = this.styles.muted(hint); } let pad = (str) => this.margin[3] + str.replace(/\s+$/, "").padEnd(this.widths[0], " "); let newline = this.newline; let ind = this.indent(choice); let message = await this.resolve(choice.message, this.state, choice, i); let scale = await this.renderScale(choice, i); let margin = this.margin[1] + this.margin[3]; this.scaleLength = colors2.unstyle(scale).length; this.widths[0] = Math.min(this.widths[0], this.width - this.scaleLength - margin.length); let msg = utils.wordWrap(message, { width: this.widths[0], newline }); let lines = msg.split("\n").map((line) => pad(line) + this.margin[1]); if (focused) { scale = this.styles.info(scale); lines = lines.map((line) => this.styles.info(line)); } lines[0] += scale; if (this.linebreak) lines.push(""); return [ind + pointer, lines.join("\n")].filter(Boolean); } async renderChoices() { if (this.state.submitted) return ""; this.tableize(); let choices = this.visible.map(async (ch, i) => await this.renderChoice(ch, i)); let visible = await Promise.all(choices); let heading = await this.renderScaleHeading(); return this.margin[0] + [heading, ...visible.map((v) => v.join(" "))].join("\n"); } async render() { let { submitted, size } = this.state; let prefix = await this.prefix(); let separator = await this.separator(); let message = await this.message(); let prompt = ""; if (this.options.promptLine !== false) { prompt = [prefix, message, separator, ""].join(" "); this.state.prompt = prompt; } let header = await this.header(); let output = await this.format(); let key = await this.renderScaleKey(); let help = await this.error() || await this.hint(); let body = await this.renderChoices(); let footer = await this.footer(); let err = this.emptyError; if (output) prompt += output; if (help && !prompt.includes(help)) prompt += " " + help; if (submitted && !output && !body.trim() && this.multiple && err != null) { prompt += this.styles.danger(err); } this.clear(size); this.write([header, prompt, key, body, footer].filter(Boolean).join("\n")); if (!this.state.submitted) { this.write(this.margin[2]); } this.restore(); } submit() { this.value = {}; for (let choice of this.choices) { this.value[choice.name] = choice.scaleIndex; } return this.base.submit.call(this); } }; module2.exports = LikertScale; } }); // node_modules/enquirer/lib/interpolate.js var require_interpolate = __commonJS({ "node_modules/enquirer/lib/interpolate.js"(exports2, module2) { "use strict"; var colors2 = require_ansi_colors(); var clean = (str = "") => { return typeof str === "string" ? str.replace(/^['"]|['"]$/g, "") : ""; }; var Item = class { constructor(token) { this.name = token.key; this.field = token.field || {}; this.value = clean(token.initial || this.field.initial || ""); this.message = token.message || this.name; this.cursor = 0; this.input = ""; this.lines = []; } }; var tokenize2 = async (options = {}, defaults = {}, fn = (token) => token) => { let unique = /* @__PURE__ */ new Set(); let fields = options.fields || []; let input = options.template; let tabstops = []; let items = []; let keys = []; let line = 1; if (typeof input === "function") { input = await input(); } let i = -1; let next = () => input[++i]; let peek = () => input[i + 1]; let push = (token) => { token.line = line; tabstops.push(token); }; push({ type: "bos", value: "" }); while (i < input.length - 1) { let value = next(); if (/^[^\S\n ]$/.test(value)) { push({ type: "text", value }); continue; } if (value === "\n") { push({ type: "newline", value }); line++; continue; } if (value === "\\") { value += next(); push({ type: "text", value }); continue; } if ((value === "$" || value === "#" || value === "{") && peek() === "{") { let n = next(); value += n; let token = { type: "template", open: value, inner: "", close: "", value }; let ch; while (ch = next()) { if (ch === "}") { if (peek() === "}") ch += next(); token.value += ch; token.close = ch; break; } if (ch === ":") { token.initial = ""; token.key = token.inner; } else if (token.initial !== void 0) { token.initial += ch; } token.value += ch; token.inner += ch; } token.template = token.open + (token.initial || token.inner) + token.close; token.key = token.key || token.inner; if (defaults.hasOwnProperty(token.key)) { token.initial = defaults[token.key]; } token = fn(token); push(token); keys.push(token.key); unique.add(token.key); let item = items.find((item2) => item2.name === token.key); token.field = fields.find((ch2) => ch2.name === token.key); if (!item) { item = new Item(token); items.push(item); } item.lines.push(token.line - 1); continue; } let last = tabstops[tabstops.length - 1]; if (last.type === "text" && last.line === line) { last.value += value; } else { push({ type: "text", value }); } } push({ type: "eos", value: "" }); return { input, tabstops, unique, keys, items }; }; module2.exports = async (prompt) => { let options = prompt.options; let required2 = new Set(options.required === true ? [] : options.required || []); let defaults = { ...options.values, ...options.initial }; let { tabstops, items, keys } = await tokenize2(options, defaults); let result = createFn("result", prompt, options); let format = createFn("format", prompt, options); let isValid2 = createFn("validate", prompt, options, true); let isVal = prompt.isValue.bind(prompt); return async (state = {}, submitted = false) => { let index = 0; state.required = required2; state.items = items; state.keys = keys; state.output = ""; let validate2 = async (value, state2, item, index2) => { let error48 = await isValid2(value, state2, item, index2); if (error48 === false) { return "Invalid field " + item.name; } return error48; }; for (let token of tabstops) { let value = token.value; let key = token.key; if (token.type !== "template") { if (value) state.output += value; continue; } if (token.type === "template") { let item = items.find((ch) => ch.name === key); if (options.required === true) { state.required.add(item.name); } let val = [item.input, state.values[item.value], item.value, value].find(isVal); let field = item.field || {}; let message = field.message || token.inner; if (submitted) { let error48 = await validate2(state.values[key], state, item, index); if (error48 && typeof error48 === "string" || error48 === false) { state.invalid.set(key, error48); continue; } state.invalid.delete(key); let res = await result(state.values[key], state, item, index); state.output += colors2.unstyle(res); continue; } item.placeholder = false; let before = value; value = await format(value, state, item, index); if (val !== value) { state.values[key] = val; value = prompt.styles.typing(val); state.missing.delete(message); } else { state.values[key] = void 0; val = `<${message}>`; value = prompt.styles.primary(val); item.placeholder = true; if (state.required.has(key)) { state.missing.add(message); } } if (state.missing.has(message) && state.validating) { value = prompt.styles.warning(val); } if (state.invalid.has(key) && state.validating) { value = prompt.styles.danger(val); } if (index === state.index) { if (before !== value) { value = prompt.styles.underline(value); } else { value = prompt.styles.heading(colors2.unstyle(value)); } } index++; } if (value) { state.output += value; } } let lines = state.output.split("\n").map((l) => " " + l); let len = items.length; let done = 0; for (let item of items) { if (state.invalid.has(item.name)) { item.lines.forEach((i) => { if (lines[i][0] !== " ") return; lines[i] = state.styles.danger(state.symbols.bullet) + lines[i].slice(1); }); } if (prompt.isValue(state.values[item.name])) { done++; } } state.completed = (done / len * 100).toFixed(0); state.output = lines.join("\n"); return state.output; }; }; function createFn(prop, prompt, options, fallback) { return (value, state, item, index) => { if (typeof item.field[prop] === "function") { return item.field[prop].call(prompt, value, state, item, index); } return [fallback, value].find((v) => prompt.isValue(v)); }; } } }); // node_modules/enquirer/lib/prompts/snippet.js var require_snippet = __commonJS({ "node_modules/enquirer/lib/prompts/snippet.js"(exports2, module2) { "use strict"; var colors2 = require_ansi_colors(); var interpolate = require_interpolate(); var Prompt = require_prompt(); var SnippetPrompt = class extends Prompt { constructor(options) { super(options); this.cursorHide(); this.reset(true); } async initialize() { this.interpolate = await interpolate(this); await super.initialize(); } async reset(first) { this.state.keys = []; this.state.invalid = /* @__PURE__ */ new Map(); this.state.missing = /* @__PURE__ */ new Set(); this.state.completed = 0; this.state.values = {}; if (first !== true) { await this.initialize(); await this.render(); } } moveCursor(n) { let item = this.getItem(); this.cursor += n; item.cursor += n; } dispatch(ch, key) { if (!key.code && !key.ctrl && ch != null && this.getItem()) { this.append(ch, key); return; } this.alert(); } append(ch, key) { let item = this.getItem(); let prefix = item.input.slice(0, this.cursor); let suffix = item.input.slice(this.cursor); this.input = item.input = `${prefix}${ch}${suffix}`; this.moveCursor(1); this.render(); } delete() { let item = this.getItem(); if (this.cursor <= 0 || !item.input) return this.alert(); let suffix = item.input.slice(this.cursor); let prefix = item.input.slice(0, this.cursor - 1); this.input = item.input = `${prefix}${suffix}`; this.moveCursor(-1); this.render(); } increment(i) { return i >= this.state.keys.length - 1 ? 0 : i + 1; } decrement(i) { return i <= 0 ? this.state.keys.length - 1 : i - 1; } first() { this.state.index = 0; this.render(); } last() { this.state.index = this.state.keys.length - 1; this.render(); } right() { if (this.cursor >= this.input.length) return this.alert(); this.moveCursor(1); this.render(); } left() { if (this.cursor <= 0) return this.alert(); this.moveCursor(-1); this.render(); } prev() { this.state.index = this.decrement(this.state.index); this.getItem(); this.render(); } next() { this.state.index = this.increment(this.state.index); this.getItem(); this.render(); } up() { this.prev(); } down() { this.next(); } format(value) { let color = this.state.completed < 100 ? this.styles.warning : this.styles.success; if (this.state.submitted === true && this.state.completed !== 100) { color = this.styles.danger; } return color(`${this.state.completed}% completed`); } async render() { let { index, keys = [], submitted, size } = this.state; let newline = [this.options.newline, "\n"].find((v) => v != null); let prefix = await this.prefix(); let separator = await this.separator(); let message = await this.message(); let prompt = [prefix, message, separator].filter(Boolean).join(" "); this.state.prompt = prompt; let header = await this.header(); let error48 = await this.error() || ""; let hint = await this.hint() || ""; let body = submitted ? "" : await this.interpolate(this.state); let key = this.state.key = keys[index] || ""; let input = await this.format(key); let footer = await this.footer(); if (input) prompt += " " + input; if (hint && !input && this.state.completed === 0) prompt += " " + hint; this.clear(size); let lines = [header, prompt, body, footer, error48.trim()]; this.write(lines.filter(Boolean).join(newline)); this.restore(); } getItem(name) { let { items, keys, index } = this.state; let item = items.find((ch) => ch.name === keys[index]); if (item && item.input != null) { this.input = item.input; this.cursor = item.cursor; } return item; } async submit() { if (typeof this.interpolate !== "function") await this.initialize(); await this.interpolate(this.state, true); let { invalid, missing, output, values } = this.state; if (invalid.size) { let err = ""; for (let [key, value] of invalid) err += `Invalid ${key}: ${value} `; this.state.error = err; return super.submit(); } if (missing.size) { this.state.error = "Required: " + [...missing.keys()].join(", "); return super.submit(); } let lines = colors2.unstyle(output).split("\n"); let result = lines.map((v) => v.slice(1)).join("\n"); this.value = { values, result }; return super.submit(); } }; module2.exports = SnippetPrompt; } }); // node_modules/enquirer/lib/prompts/sort.js var require_sort = __commonJS({ "node_modules/enquirer/lib/prompts/sort.js"(exports2, module2) { "use strict"; var hint = "(Use + to sort)"; var Prompt = require_select(); var Sort = class extends Prompt { constructor(options) { super({ ...options, reorder: false, sort: true, multiple: true }); this.state.hint = [this.options.hint, hint].find(this.isValue.bind(this)); } indicator() { return ""; } async renderChoice(choice, i) { let str = await super.renderChoice(choice, i); let sym = this.symbols.identicalTo + " "; let pre = this.index === i && this.sorting ? this.styles.muted(sym) : " "; if (this.options.drag === false) pre = ""; if (this.options.numbered === true) { return pre + `${i + 1} - ` + str; } return pre + str; } get selected() { return this.choices; } submit() { this.value = this.choices.map((choice) => choice.value); return super.submit(); } }; module2.exports = Sort; } }); // node_modules/enquirer/lib/prompts/survey.js var require_survey = __commonJS({ "node_modules/enquirer/lib/prompts/survey.js"(exports2, module2) { "use strict"; var ArrayPrompt = require_array(); var Survey = class extends ArrayPrompt { constructor(options = {}) { super(options); this.emptyError = options.emptyError || "No items were selected"; this.term = process.env.TERM_PROGRAM; if (!this.options.header) { let header = ["", "4 - Strongly Agree", "3 - Agree", "2 - Neutral", "1 - Disagree", "0 - Strongly Disagree", ""]; header = header.map((ele) => this.styles.muted(ele)); this.state.header = header.join("\n "); } } async toChoices(...args) { if (this.createdScales) return false; this.createdScales = true; let choices = await super.toChoices(...args); for (let choice of choices) { choice.scale = createScale(5, this.options); choice.scaleIdx = 2; } return choices; } dispatch() { this.alert(); } space() { let choice = this.focused; let ele = choice.scale[choice.scaleIdx]; let selected = ele.selected; choice.scale.forEach((e) => e.selected = false); ele.selected = !selected; return this.render(); } indicator() { return ""; } pointer() { return ""; } separator() { return this.styles.muted(this.symbols.ellipsis); } right() { let choice = this.focused; if (choice.scaleIdx >= choice.scale.length - 1) return this.alert(); choice.scaleIdx++; return this.render(); } left() { let choice = this.focused; if (choice.scaleIdx <= 0) return this.alert(); choice.scaleIdx--; return this.render(); } indent() { return " "; } async renderChoice(item, i) { await this.onChoice(item, i); let focused = this.index === i; let isHyper = this.term === "Hyper"; let n = !isHyper ? 8 : 9; let s = !isHyper ? " " : ""; let ln = this.symbols.line.repeat(n); let sp = " ".repeat(n + (isHyper ? 0 : 1)); let dot = (enabled) => (enabled ? this.styles.success("\u25C9") : "\u25EF") + s; let num = i + 1 + "."; let color = focused ? this.styles.heading : this.styles.noop; let msg = await this.resolve(item.message, this.state, item, i); let indent = this.indent(item); let scale = indent + item.scale.map((e, i2) => dot(i2 === item.scaleIdx)).join(ln); let val = (i2) => i2 === item.scaleIdx ? color(i2) : i2; let next = indent + item.scale.map((e, i2) => val(i2)).join(sp); let line = () => [num, msg].filter(Boolean).join(" "); let lines = () => [line(), scale, next, " "].filter(Boolean).join("\n"); if (focused) { scale = this.styles.cyan(scale); next = this.styles.cyan(next); } return lines(); } async renderChoices() { if (this.state.submitted) return ""; let choices = this.visible.map(async (ch, i) => await this.renderChoice(ch, i)); let visible = await Promise.all(choices); if (!visible.length) visible.push(this.styles.danger("No matching choices")); return visible.join("\n"); } format() { if (this.state.submitted) { let values = this.choices.map((ch) => this.styles.info(ch.scaleIdx)); return values.join(", "); } return ""; } async render() { let { submitted, size } = this.state; let prefix = await this.prefix(); let separator = await this.separator(); let message = await this.message(); let prompt = [prefix, message, separator].filter(Boolean).join(" "); this.state.prompt = prompt; let header = await this.header(); let output = await this.format(); let help = await this.error() || await this.hint(); let body = await this.renderChoices(); let footer = await this.footer(); if (output || !help) prompt += " " + output; if (help && !prompt.includes(help)) prompt += " " + help; if (submitted && !output && !body && this.multiple && this.type !== "form") { prompt += this.styles.danger(this.emptyError); } this.clear(size); this.write([prompt, header, body, footer].filter(Boolean).join("\n")); this.restore(); } submit() { this.value = {}; for (let choice of this.choices) { this.value[choice.name] = choice.scaleIdx; } return this.base.submit.call(this); } }; function createScale(n, options = {}) { if (Array.isArray(options.scale)) { return options.scale.map((ele) => ({ ...ele })); } let scale = []; for (let i = 1; i < n + 1; i++) scale.push({ i, selected: false }); return scale; } module2.exports = Survey; } }); // node_modules/enquirer/lib/prompts/text.js var require_text = __commonJS({ "node_modules/enquirer/lib/prompts/text.js"(exports2, module2) { module2.exports = require_input(); } }); // node_modules/enquirer/lib/prompts/toggle.js var require_toggle = __commonJS({ "node_modules/enquirer/lib/prompts/toggle.js"(exports2, module2) { "use strict"; var BooleanPrompt = require_boolean(); var TogglePrompt = class extends BooleanPrompt { async initialize() { await super.initialize(); this.value = this.initial = !!this.options.initial; this.disabled = this.options.disabled || "no"; this.enabled = this.options.enabled || "yes"; await this.render(); } reset() { this.value = this.initial; this.render(); } delete() { this.alert(); } toggle() { this.value = !this.value; this.render(); } enable() { if (this.value === true) return this.alert(); this.value = true; this.render(); } disable() { if (this.value === false) return this.alert(); this.value = false; this.render(); } up() { this.toggle(); } down() { this.toggle(); } right() { this.toggle(); } left() { this.toggle(); } next() { this.toggle(); } prev() { this.toggle(); } dispatch(ch = "", key) { switch (ch.toLowerCase()) { case " ": return this.toggle(); case "1": case "y": case "t": return this.enable(); case "0": case "n": case "f": return this.disable(); default: { return this.alert(); } } } format() { let active = (str) => this.styles.primary.underline(str); let value = [ this.value ? this.disabled : active(this.disabled), this.value ? active(this.enabled) : this.enabled ]; return value.join(this.styles.muted(" / ")); } async render() { let { size } = this.state; let header = await this.header(); let prefix = await this.prefix(); let separator = await this.separator(); let message = await this.message(); let output = await this.format(); let help = await this.error() || await this.hint(); let footer = await this.footer(); let prompt = [prefix, message, separator, output].join(" "); this.state.prompt = prompt; if (help && !prompt.includes(help)) prompt += " " + help; this.clear(size); this.write([header, prompt, footer].filter(Boolean).join("\n")); this.write(this.margin[2]); this.restore(); } }; module2.exports = TogglePrompt; } }); // node_modules/enquirer/lib/prompts/quiz.js var require_quiz = __commonJS({ "node_modules/enquirer/lib/prompts/quiz.js"(exports2, module2) { "use strict"; var SelectPrompt = require_select(); var Quiz = class extends SelectPrompt { constructor(options) { super(options); if (typeof this.options.correctChoice !== "number" || this.options.correctChoice < 0) { throw new Error("Please specify the index of the correct answer from the list of choices"); } } async toChoices(value, parent) { let choices = await super.toChoices(value, parent); if (choices.length < 2) { throw new Error("Please give at least two choices to the user"); } if (this.options.correctChoice > choices.length) { throw new Error("Please specify the index of the correct answer from the list of choices"); } return choices; } check(state) { return state.index === this.options.correctChoice; } async result(selected) { return { selectedAnswer: selected, correctAnswer: this.options.choices[this.options.correctChoice].value, correct: await this.check(this.state) }; } }; module2.exports = Quiz; } }); // node_modules/enquirer/lib/prompts/index.js var require_prompts = __commonJS({ "node_modules/enquirer/lib/prompts/index.js"(exports2) { "use strict"; var utils = require_utils2(); var define = (key, fn) => { utils.defineExport(exports2, key, fn); utils.defineExport(exports2, key.toLowerCase(), fn); }; define("AutoComplete", () => require_autocomplete()); define("BasicAuth", () => require_basicauth()); define("Confirm", () => require_confirm()); define("Editable", () => require_editable()); define("Form", () => require_form()); define("Input", () => require_input()); define("Invisible", () => require_invisible()); define("List", () => require_list()); define("MultiSelect", () => require_multiselect()); define("Numeral", () => require_numeral()); define("Password", () => require_password()); define("Scale", () => require_scale()); define("Select", () => require_select()); define("Snippet", () => require_snippet()); define("Sort", () => require_sort()); define("Survey", () => require_survey()); define("Text", () => require_text()); define("Toggle", () => require_toggle()); define("Quiz", () => require_quiz()); } }); // node_modules/enquirer/lib/types/index.js var require_types = __commonJS({ "node_modules/enquirer/lib/types/index.js"(exports2, module2) { module2.exports = { ArrayPrompt: require_array(), AuthPrompt: require_auth(), BooleanPrompt: require_boolean(), NumberPrompt: require_number(), StringPrompt: require_string2() }; } }); // node_modules/enquirer/index.js var require_enquirer = __commonJS({ "node_modules/enquirer/index.js"(exports2, module2) { "use strict"; var assert2 = require("assert"); var Events = require("events"); var utils = require_utils2(); var Enquirer = class extends Events { constructor(options, answers) { super(); this.options = utils.merge({}, options); this.answers = { ...answers }; } /** * Register a custom prompt type. * * ```js * const Enquirer = require('enquirer'); * const enquirer = new Enquirer(); * enquirer.register('customType', require('./custom-prompt')); * ``` * @name register() * @param {String} `type` * @param {Function|Prompt} `fn` `Prompt` class, or a function that returns a `Prompt` class. * @return {Object} Returns the Enquirer instance * @api public */ register(type, fn) { if (utils.isObject(type)) { for (let key of Object.keys(type)) this.register(key, type[key]); return this; } assert2.equal(typeof fn, "function", "expected a function"); let name = type.toLowerCase(); if (fn.prototype instanceof this.Prompt) { this.prompts[name] = fn; } else { this.prompts[name] = fn(this.Prompt, this); } return this; } /** * Prompt function that takes a "question" object or array of question objects, * and returns an object with responses from the user. * * ```js * const Enquirer = require('enquirer'); * const enquirer = new Enquirer(); * * const response = await enquirer.prompt({ * type: 'input', * name: 'username', * message: 'What is your username?' * }); * console.log(response); * ``` * @name prompt() * @param {Array|Object} `questions` Options objects for one or more prompts to run. * @return {Promise} Promise that returns an "answers" object with the user's responses. * @api public */ async prompt(questions = []) { for (let question of [].concat(questions)) { try { if (typeof question === "function") question = await question.call(this); await this.ask(utils.merge({}, this.options, question)); } catch (err) { return Promise.reject(err); } } return this.answers; } async ask(question) { if (typeof question === "function") { question = await question.call(this); } let opts = utils.merge({}, this.options, question); let { type, name } = question; let { set: set2, get } = utils; if (typeof type === "function") { type = await type.call(this, question, this.answers); } if (!type) return this.answers[name]; assert2(this.prompts[type], `Prompt "${type}" is not registered`); let prompt = new this.prompts[type](opts); let value = get(this.answers, name); prompt.state.answers = this.answers; prompt.enquirer = this; if (name) { prompt.on("submit", (value2) => { this.emit("answer", name, value2, prompt); set2(this.answers, name, value2); }); } let emit = prompt.emit.bind(prompt); prompt.emit = (...args) => { this.emit.call(this, ...args); return emit(...args); }; this.emit("prompt", prompt, this); if (opts.autofill && value != null) { prompt.value = prompt.input = value; if (opts.autofill === "show") { await prompt.submit(); } } else { value = prompt.value = await prompt.run(); } return value; } /** * Use an enquirer plugin. * * ```js * const Enquirer = require('enquirer'); * const enquirer = new Enquirer(); * const plugin = enquirer => { * // do stuff to enquire instance * }; * enquirer.use(plugin); * ``` * @name use() * @param {Function} `plugin` Plugin function that takes an instance of Enquirer. * @return {Object} Returns the Enquirer instance. * @api public */ use(plugin) { plugin.call(this, this); return this; } set Prompt(value) { this._Prompt = value; } get Prompt() { return this._Prompt || this.constructor.Prompt; } get prompts() { return this.constructor.prompts; } static set Prompt(value) { this._Prompt = value; } static get Prompt() { return this._Prompt || require_prompt(); } static get prompts() { return require_prompts(); } static get types() { return require_types(); } /** * Prompt function that takes a "question" object or array of question objects, * and returns an object with responses from the user. * * ```js * const { prompt } = require('enquirer'); * const response = await prompt({ * type: 'input', * name: 'username', * message: 'What is your username?' * }); * console.log(response); * ``` * @name Enquirer#prompt * @param {Array|Object} `questions` Options objects for one or more prompts to run. * @return {Promise} Promise that returns an "answers" object with the user's responses. * @api public */ static get prompt() { const fn = (questions, ...rest) => { let enquirer2 = new this(...rest); let emit = enquirer2.emit.bind(enquirer2); enquirer2.emit = (...args) => { fn.emit(...args); return emit(...args); }; return enquirer2.prompt(questions); }; utils.mixinEmitter(fn, new Events()); return fn; } }; utils.mixinEmitter(Enquirer, new Events()); var prompts = Enquirer.prompts; for (let name of Object.keys(prompts)) { let key = name.toLowerCase(); let run = (options) => new prompts[name](options).run(); Enquirer.prompt[key] = run; Enquirer[key] = run; if (!Enquirer[name]) { Reflect.defineProperty(Enquirer, name, { get: () => prompts[name] }); } } var exp = (name) => { utils.defineExport(Enquirer, name, () => Enquirer.types[name]); }; exp("ArrayPrompt"); exp("AuthPrompt"); exp("BooleanPrompt"); exp("NumberPrompt"); exp("StringPrompt"); module2.exports = Enquirer; } }); // node_modules/readdirp/node_modules/picomatch/lib/constants.js var require_constants6 = __commonJS({ "node_modules/readdirp/node_modules/picomatch/lib/constants.js"(exports2, module2) { "use strict"; var path = require("path"); var WIN_SLASH = "\\\\/"; var WIN_NO_SLASH = `[^${WIN_SLASH}]`; var DEFAULT_MAX_EXTGLOB_RECURSION = 0; var DOT_LITERAL = "\\."; var PLUS_LITERAL = "\\+"; var QMARK_LITERAL = "\\?"; var SLASH_LITERAL = "\\/"; var ONE_CHAR = "(?=.)"; var QMARK = "[^/]"; var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; var START_ANCHOR = `(?:^|${SLASH_LITERAL})`; var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; var NO_DOT = `(?!${DOT_LITERAL})`; var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; var STAR = `${QMARK}*?`; var POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR, START_ANCHOR }; var WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; var POSIX_REGEX_SOURCE = { __proto__: null, alnum: "a-zA-Z0-9", alpha: "a-zA-Z", ascii: "\\x00-\\x7F", blank: " \\t", cntrl: "\\x00-\\x1F\\x7F", digit: "0-9", graph: "\\x21-\\x7E", lower: "a-z", print: "\\x20-\\x7E ", punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", space: " \\t\\r\\n\\v\\f", upper: "A-Z", word: "A-Za-z0-9_", xdigit: "A-Fa-f0-9" }; module2.exports = { DEFAULT_MAX_EXTGLOB_RECURSION, MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { __proto__: null, "***": "*", "**/**": "**", "**/**/**": "**" }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` }, "?": { type: "qmark", open: "(?:", close: ")?" }, "+": { type: "plus", open: "(?:", close: ")+" }, "*": { type: "star", open: "(?:", close: ")*" }, "@": { type: "at", open: "(?:", close: ")" } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; } }); // node_modules/readdirp/node_modules/picomatch/lib/utils.js var require_utils3 = __commonJS({ "node_modules/readdirp/node_modules/picomatch/lib/utils.js"(exports2) { "use strict"; var path = require("path"); var win32 = process.platform === "win32"; var { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants6(); exports2.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); exports2.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); exports2.isRegexChar = (str) => str.length === 1 && exports2.hasRegexChars(str); exports2.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); exports2.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); exports2.removeBackslashes = (str) => { return str.replace(REGEX_REMOVE_BACKSLASH, (match) => { return match === "\\" ? "" : match; }); }; exports2.supportsLookbehinds = () => { const segs = process.version.slice(1).split(".").map(Number); if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { return true; } return false; }; exports2.isWindows = (options) => { if (options && typeof options.windows === "boolean") { return options.windows; } return win32 === true || path.sep === "\\"; }; exports2.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === "\\") return exports2.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports2.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith("./")) { output = output.slice(2); state.prefix = "./"; } return output; }; exports2.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? "" : "^"; const append = options.contains ? "" : "$"; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; } }); // node_modules/readdirp/node_modules/picomatch/lib/scan.js var require_scan = __commonJS({ "node_modules/readdirp/node_modules/picomatch/lib/scan.js"(exports2, module2) { "use strict"; var utils = require_utils3(); var { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ } = require_constants6(); var isPathSeparator = (code) => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; var depth = (token) => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; var scan = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: "", depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: "", depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT && index === start + 1) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ""; let glob = ""; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ""; glob = str; } else { base = str; } if (base && base !== "" && base !== "/" && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils.removeBackslashes(glob); if (base && backslashes === true) { base = utils.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== "") { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; module2.exports = scan; } }); // node_modules/readdirp/node_modules/picomatch/lib/parse.js var require_parse2 = __commonJS({ "node_modules/readdirp/node_modules/picomatch/lib/parse.js"(exports2, module2) { "use strict"; var constants = require_constants6(); var utils = require_utils3(); var { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants; var expandRange = (args, options) => { if (typeof options.expandRange === "function") { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join("-")}]`; try { new RegExp(value); } catch (ex) { return args.map((v) => utils.escapeRegex(v)).join(".."); } return value; }; var syntaxError2 = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; var splitTopLevel = (input) => { const parts = []; let bracket = 0; let paren = 0; let quote = 0; let value = ""; let escaped = false; for (const ch of input) { if (escaped === true) { value += ch; escaped = false; continue; } if (ch === "\\") { value += ch; escaped = true; continue; } if (ch === '"') { quote = quote === 1 ? 0 : 1; value += ch; continue; } if (quote === 0) { if (ch === "[") { bracket++; } else if (ch === "]" && bracket > 0) { bracket--; } else if (bracket === 0) { if (ch === "(") { paren++; } else if (ch === ")" && paren > 0) { paren--; } else if (ch === "|" && paren === 0) { parts.push(value); value = ""; continue; } } } value += ch; } parts.push(value); return parts; }; var isPlainBranch = (branch) => { let escaped = false; for (const ch of branch) { if (escaped === true) { escaped = false; continue; } if (ch === "\\") { escaped = true; continue; } if (/[?*+@!()[\]{}]/.test(ch)) { return false; } } return true; }; var normalizeSimpleBranch = (branch) => { let value = branch.trim(); let changed = true; while (changed === true) { changed = false; if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { value = value.slice(2, -1); changed = true; } } if (!isPlainBranch(value)) { return; } return value.replace(/\\(.)/g, "$1"); }; var hasRepeatedCharPrefixOverlap = (branches) => { const values = branches.map(normalizeSimpleBranch).filter(Boolean); for (let i = 0; i < values.length; i++) { for (let j = i + 1; j < values.length; j++) { const a = values[i]; const b = values[j]; const char = a[0]; if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { continue; } if (a === b || a.startsWith(b) || b.startsWith(a)) { return true; } } } return false; }; var parseRepeatedExtglob = (pattern, requireEnd = true) => { if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") { return; } let bracket = 0; let paren = 0; let quote = 0; let escaped = false; for (let i = 1; i < pattern.length; i++) { const ch = pattern[i]; if (escaped === true) { escaped = false; continue; } if (ch === "\\") { escaped = true; continue; } if (ch === '"') { quote = quote === 1 ? 0 : 1; continue; } if (quote === 1) { continue; } if (ch === "[") { bracket++; continue; } if (ch === "]" && bracket > 0) { bracket--; continue; } if (bracket > 0) { continue; } if (ch === "(") { paren++; continue; } if (ch === ")") { paren--; if (paren === 0) { if (requireEnd === true && i !== pattern.length - 1) { return; } return { type: pattern[0], body: pattern.slice(2, i), end: i }; } } } }; var getStarExtglobSequenceOutput = (pattern) => { let index = 0; const chars = []; while (index < pattern.length) { const match = parseRepeatedExtglob(pattern.slice(index), false); if (!match || match.type !== "*") { return; } const branches = splitTopLevel(match.body).map((branch2) => branch2.trim()); if (branches.length !== 1) { return; } const branch = normalizeSimpleBranch(branches[0]); if (!branch || branch.length !== 1) { return; } chars.push(branch); index += match.end + 1; } if (chars.length < 1) { return; } const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`; return `${source}*`; }; var repeatedExtglobRecursion = (pattern) => { let depth = 0; let value = pattern.trim(); let match = parseRepeatedExtglob(value); while (match) { depth++; value = match.body.trim(); match = parseRepeatedExtglob(value); } return depth; }; var analyzeRepeatedExtglob = (body, options) => { if (options.maxExtglobRecursion === false) { return { risky: false }; } const max = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants.DEFAULT_MAX_EXTGLOB_RECURSION; const branches = splitTopLevel(body).map((branch) => branch.trim()); if (branches.length > 1) { if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) { return { risky: true }; } } for (const branch of branches) { const safeOutput = getStarExtglobSequenceOutput(branch); if (safeOutput) { return { risky: true, safeOutput }; } if (repeatedExtglobRecursion(branch) > max) { return { risky: true }; } } return { risky: false }; }; var parse3 = (input, options) => { if (typeof input !== "string") { throw new TypeError("Expected a string"); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: "bos", value: "", output: opts.prepend || "" }; const tokens = [bos]; const capture = opts.capture ? "" : "?:"; const win32 = utils.isWindows(options); const PLATFORM_CHARS = constants.globChars(win32); const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = (opts2) => { return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? "" : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } if (typeof opts.noext === "boolean") { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: "", output: "", prefix: "", backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ""; const remaining = () => input.slice(state.index + 1); const consume = (value2 = "", num = 0) => { state.consumed += value2; state.index += num; }; const append = (token) => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = (type) => { state[type]++; stack.push(type); }; const decrement = (type) => { state[type]--; stack.pop(); }; const push = (tok) => { if (prev.type === "globstar") { const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = "star"; prev.value = "*"; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== "paren") { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === "text" && tok.type === "text") { prev.value += tok.value; prev.output = (prev.output || "") + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value2) => { const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" }; token.prev = prev; token.parens = state.parens; token.output = state.output; token.startIndex = state.index; token.tokensIndex = tokens.length; const output = (opts.capture ? "(" : "") + token.open; increment("parens"); push({ type, value: value2, output: state.output ? "" : ONE_CHAR }); push({ type: "paren", extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = (token) => { const literal2 = input.slice(token.startIndex, state.index + 1); const body = input.slice(token.startIndex + 2, state.index); const analysis = analyzeRepeatedExtglob(body, opts); if ((token.type === "plus" || token.type === "star") && analysis.risky) { const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0; const open2 = tokens[token.tokensIndex]; open2.type = "text"; open2.value = literal2; open2.output = safeOutput || utils.escapeRegex(literal2); for (let i = token.tokensIndex + 1; i < tokens.length; i++) { tokens[i].value = ""; tokens[i].output = ""; delete tokens[i].suffix; } state.output = token.output + open2.output; state.backtrack = true; push({ type: "paren", extglob: true, value, output: "" }); decrement("parens"); return; } let output = token.close + (opts.capture ? ")" : ""); let rest; if (token.type === "negate") { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes("/")) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { const expression = parse3(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === "bos") { state.negatedExtglob = true; } } push({ type: "paren", extglob: true, value, output }); decrement("parens"); }; if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc2, chars, first, rest, index) => { if (first === "\\") { backslashes = true; return m; } if (first === "?") { if (esc2) { return esc2 + first + (rest ? QMARK.repeat(rest.length) : ""); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ""); } return QMARK.repeat(chars.length); } if (first === ".") { return DOT_LITERAL.repeat(chars.length); } if (first === "*") { if (esc2) { return esc2 + first + (rest ? star : ""); } return star; } return esc2 ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ""); } else { output = output.replace(/\\+/g, (m) => { return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils.wrapOutput(output, state, options); return state; } while (!eos()) { value = advance(); if (value === "\0") { continue; } if (value === "\\") { const next = peek(); if (next === "/" && opts.bash !== true) { continue; } if (next === "." || next === ";") { continue; } if (!next) { value += "\\"; push({ type: "text", value }); continue; } const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += "\\"; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: "text", value }); continue; } } if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) { if (opts.posix !== false && value === ":") { const inner = prev.value.slice(1); if (inner.includes("[")) { prev.posix = true; if (inner.includes(":")) { const idx = prev.value.lastIndexOf("["); const pre = prev.value.slice(0, idx); const rest2 = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE[rest2]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") { value = `\\${value}`; } if (value === "]" && (prev.value === "[" || prev.value === "[^")) { value = `\\${value}`; } if (opts.posix === true && value === "!" && prev.value === "[") { value = "^"; } prev.value += value; append({ value }); continue; } if (state.quotes === 1 && value !== '"') { value = utils.escapeRegex(value); prev.value += value; append({ value }); continue; } if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: "text", value }); } continue; } if (value === "(") { increment("parens"); push({ type: "paren", value }); continue; } if (value === ")") { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError2("opening", "(")); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: "paren", value, output: state.parens ? ")" : "\\)" }); decrement("parens"); continue; } if (value === "[") { if (opts.nobracket === true || !remaining().includes("]")) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError2("closing", "]")); } value = `\\${value}`; } else { increment("brackets"); } push({ type: "bracket", value }); continue; } if (value === "]") { if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { push({ type: "text", value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError2("opening", "[")); } push({ type: "text", value, output: `\\${value}` }); continue; } decrement("brackets"); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) { value = `/${value}`; } prev.value += value; append({ value }); if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { continue; } const escaped = utils.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } if (value === "{" && opts.nobrace !== true) { increment("braces"); const open2 = { type: "brace", value, output: "(", outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open2); push(open2); continue; } if (value === "}") { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: "text", value, output: value }); continue; } let output = ")"; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === "brace") { break; } if (arr[i].type !== "dots") { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = "\\{"; value = output = "\\}"; state.output = out; for (const t of toks) { state.output += t.output || t.value; } } push({ type: "brace", value, output }); decrement("braces"); braces.pop(); continue; } if (value === "|") { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: "text", value }); continue; } if (value === ",") { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === "braces") { brace.comma = true; output = "|"; } push({ type: "comma", value, output }); continue; } if (value === "/") { if (prev.type === "dot" && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ""; state.output = ""; tokens.pop(); prev = bos; continue; } push({ type: "slash", value, output: SLASH_LITERAL }); continue; } if (value === ".") { if (state.braces > 0 && prev.type === "dot") { if (prev.value === ".") prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = "dots"; prev.output += value; prev.value += value; brace.dots = true; continue; } if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { push({ type: "text", value, output: DOT_LITERAL }); continue; } push({ type: "dot", value, output: DOT_LITERAL }); continue; } if (value === "?") { const isGroup = prev && prev.value === "("; if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { extglobOpen("qmark", value); continue; } if (prev && prev.type === "paren") { const next = peek(); let output = value; if (next === "<" && !utils.supportsLookbehinds()) { throw new Error("Node.js v10 or higher is required for regex lookbehinds"); } if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) { output = `\\${value}`; } push({ type: "text", value, output }); continue; } if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { push({ type: "qmark", value, output: QMARK_NO_DOT }); continue; } push({ type: "qmark", value, output: QMARK }); continue; } if (value === "!") { if (opts.noextglob !== true && peek() === "(") { if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { extglobOpen("negate", value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } if (value === "+") { if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { extglobOpen("plus", value); continue; } if (prev && prev.value === "(" || opts.regex === false) { push({ type: "plus", value, output: PLUS_LITERAL }); continue; } if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { push({ type: "plus", value }); continue; } push({ type: "plus", value: PLUS_LITERAL }); continue; } if (value === "@") { if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { push({ type: "at", extglob: true, value, output: "" }); continue; } push({ type: "text", value }); continue; } if (value !== "*") { if (value === "$" || value === "^") { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: "text", value }); continue; } if (prev && (prev.type === "globstar" || prev.star === true)) { prev.type = "star"; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen("star", value); continue; } if (prev.type === "star") { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === "slash" || prior.type === "bos"; const afterStar = before && (before.type === "star" || before.type === "globstar"); if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { push({ type: "star", value, output: "" }); continue; } const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) { push({ type: "star", value, output: "" }); continue; } while (rest.slice(0, 3) === "/**") { const after = input[state.index + 4]; if (after && after !== "/") { break; } rest = rest.slice(3); consume("/**", 3); } if (prior.type === "bos" && eos()) { prev.type = "globstar"; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = "globstar"; prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { const end = rest[1] !== void 0 ? "|$" : ""; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = "globstar"; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: "slash", value: "/", output: "" }); continue; } if (prior.type === "bos" && rest[0] === "/") { prev.type = "globstar"; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: "slash", value: "/", output: "" }); continue; } state.output = state.output.slice(0, -prev.output.length); prev.type = "globstar"; prev.output = globstar(opts); prev.value += value; state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: "star", value, output: star }; if (opts.bash === true) { token.output = ".*?"; if (prev.type === "bos" || prev.type === "slash") { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { if (prev.type === "dot") { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== "*") { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", "]")); state.output = utils.escapeLast(state.output, "["); decrement("brackets"); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", ")")); state.output = utils.escapeLast(state.output, "("); decrement("parens"); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", "}")); state.output = utils.escapeLast(state.output, "{"); decrement("braces"); } if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) { push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` }); } if (state.backtrack === true) { state.output = ""; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; parse3.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils.isWindows(options); const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? "" : "?:"; const state = { negated: false, prefix: "" }; let star = opts.bash === true ? ".*?" : STAR; if (opts.capture) { star = `(${star})`; } const globstar = (opts2) => { if (opts2.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = (str) => { switch (str) { case "*": return `${nodot}${ONE_CHAR}${star}`; case ".*": return `${DOT_LITERAL}${ONE_CHAR}${star}`; case "*.*": return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case "*/*": return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case "**": return nodot + globstar(opts); case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source2 = create(match[1]); if (!source2) return; return source2 + DOT_LITERAL + match[2]; } } }; const output = utils.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; module2.exports = parse3; } }); // node_modules/readdirp/node_modules/picomatch/lib/picomatch.js var require_picomatch = __commonJS({ "node_modules/readdirp/node_modules/picomatch/lib/picomatch.js"(exports2, module2) { "use strict"; var path = require("path"); var scan = require_scan(); var parse3 = require_parse2(); var utils = require_utils3(); var constants = require_constants6(); var isObject2 = (val) => val && typeof val === "object" && !Array.isArray(val); var picomatch = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map((input) => picomatch(input, options, returnState)); const arrayMatcher = (str) => { for (const isMatch of fns) { const state2 = isMatch(str); if (state2) return state2; } return false; }; return arrayMatcher; } const isState = isObject2(glob) && glob.tokens && glob.input; if (glob === "" || typeof glob !== "string" && !isState) { throw new TypeError("Expected pattern to be a non-empty string"); } const opts = options || {}; const posix = utils.isWindows(options); const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === "function") { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === "function") { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === "function") { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; picomatch.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== "string") { throw new TypeError("Expected input to be a string"); } if (input === "") { return { isMatch: false, output: "" }; } const opts = options || {}; const format = opts.format || (posix ? utils.toPosixSlashes : null); let match = input === glob; let output = match && format ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); return regex.test(path.basename(input)); }; picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); picomatch.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map((p) => picomatch.parse(p, options)); return parse3(pattern, { ...options, fastpaths: false }); }; picomatch.scan = (input, options) => scan(input, options); picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? "" : "^"; const append = opts.contains ? "" : "$"; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== "string") { throw new TypeError("Expected a non-empty string"); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) { parsed.output = parse3.fastpaths(input, options); } if (!parsed.output) { parsed = parse3(input, options); } return picomatch.compileRe(parsed, options, returnOutput, returnState); }; picomatch.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; picomatch.constants = constants; module2.exports = picomatch; } }); // node_modules/readdirp/node_modules/picomatch/index.js var require_picomatch2 = __commonJS({ "node_modules/readdirp/node_modules/picomatch/index.js"(exports2, module2) { "use strict"; module2.exports = require_picomatch(); } }); // node_modules/readdirp/index.js var require_readdirp = __commonJS({ "node_modules/readdirp/index.js"(exports2, module2) { "use strict"; var fs = require("fs"); var { Readable: Readable2 } = require("stream"); var sysPath = require("path"); var { promisify } = require("util"); var picomatch = require_picomatch2(); var readdir = promisify(fs.readdir); var stat = promisify(fs.stat); var lstat = promisify(fs.lstat); var realpath = promisify(fs.realpath); var BANG = "!"; var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR"; var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]); var FILE_TYPE = "files"; var DIR_TYPE = "directories"; var FILE_DIR_TYPE = "files_directories"; var EVERYTHING_TYPE = "all"; var ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; var isNormalFlowError = (error48) => NORMAL_FLOW_ERRORS.has(error48.code); var [maj, min] = process.versions.node.split(".").slice(0, 2).map((n) => Number.parseInt(n, 10)); var wantBigintFsStats = process.platform === "win32" && (maj > 10 || maj === 10 && min >= 5); var normalizeFilter = (filter) => { if (filter === void 0) return; if (typeof filter === "function") return filter; if (typeof filter === "string") { const glob = picomatch(filter.trim()); return (entry) => glob(entry.basename); } if (Array.isArray(filter)) { const positive = []; const negative = []; for (const item of filter) { const trimmed = item.trim(); if (trimmed.charAt(0) === BANG) { negative.push(picomatch(trimmed.slice(1))); } else { positive.push(picomatch(trimmed)); } } if (negative.length > 0) { if (positive.length > 0) { return (entry) => positive.some((f) => f(entry.basename)) && !negative.some((f) => f(entry.basename)); } return (entry) => !negative.some((f) => f(entry.basename)); } return (entry) => positive.some((f) => f(entry.basename)); } }; var ReaddirpStream = class _ReaddirpStream extends Readable2 { static get defaultOptions() { return { root: ".", /* eslint-disable no-unused-vars */ fileFilter: (path) => true, directoryFilter: (path) => true, /* eslint-enable no-unused-vars */ type: FILE_TYPE, lstat: false, depth: 2147483648, alwaysStat: false }; } constructor(options = {}) { super({ objectMode: true, autoDestroy: true, highWaterMark: options.highWaterMark || 4096 }); const opts = { ..._ReaddirpStream.defaultOptions, ...options }; const { root, type } = opts; this._fileFilter = normalizeFilter(opts.fileFilter); this._directoryFilter = normalizeFilter(opts.directoryFilter); const statMethod = opts.lstat ? lstat : stat; if (wantBigintFsStats) { this._stat = (path) => statMethod(path, { bigint: true }); } else { this._stat = statMethod; } this._maxDepth = opts.depth; this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); this._wantsEverything = type === EVERYTHING_TYPE; this._root = sysPath.resolve(root); this._isDirent = "Dirent" in fs && !opts.alwaysStat; this._statsProp = this._isDirent ? "dirent" : "stats"; this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent }; this.parents = [this._exploreDir(root, 1)]; this.reading = false; this.parent = void 0; } async _read(batch) { if (this.reading) return; this.reading = true; try { while (!this.destroyed && batch > 0) { const { path, depth, files = [] } = this.parent || {}; if (files.length > 0) { const slice = files.splice(0, batch).map((dirent) => this._formatEntry(dirent, path)); for (const entry of await Promise.all(slice)) { if (this.destroyed) return; const entryType = await this._getEntryType(entry); if (entryType === "directory" && this._directoryFilter(entry)) { if (depth <= this._maxDepth) { this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); } if (this._wantsDir) { this.push(entry); batch--; } } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) { if (this._wantsFile) { this.push(entry); batch--; } } } } else { const parent = this.parents.pop(); if (!parent) { this.push(null); break; } this.parent = await parent; if (this.destroyed) return; } } } catch (error48) { this.destroy(error48); } finally { this.reading = false; } } async _exploreDir(path, depth) { let files; try { files = await readdir(path, this._rdOptions); } catch (error48) { this._onError(error48); } return { files, depth, path }; } async _formatEntry(dirent, path) { let entry; try { const basename = this._isDirent ? dirent.name : dirent; const fullPath = sysPath.resolve(sysPath.join(path, basename)); entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename }; entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); } catch (err) { this._onError(err); } return entry; } _onError(err) { if (isNormalFlowError(err) && !this.destroyed) { this.emit("warn", err); } else { this.destroy(err); } } async _getEntryType(entry) { const stats = entry && entry[this._statsProp]; if (!stats) { return; } if (stats.isFile()) { return "file"; } if (stats.isDirectory()) { return "directory"; } if (stats && stats.isSymbolicLink()) { const full = entry.fullPath; try { const entryRealPath = await realpath(full); const entryRealPathStats = await lstat(entryRealPath); if (entryRealPathStats.isFile()) { return "file"; } if (entryRealPathStats.isDirectory()) { const len = entryRealPath.length; if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) { const recursiveError = new Error( `Circular symlink detected: "${full}" points to "${entryRealPath}"` ); recursiveError.code = RECURSIVE_ERROR_CODE; return this._onError(recursiveError); } return "directory"; } } catch (error48) { this._onError(error48); } } } _includeAsFile(entry) { const stats = entry && entry[this._statsProp]; return stats && this._wantsEverything && !stats.isDirectory(); } }; var readdirp = (root, options = {}) => { let type = options.entryType || options.type; if (type === "both") type = FILE_DIR_TYPE; if (type) options.type = type; if (!root) { throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)"); } else if (typeof root !== "string") { throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)"); } else if (type && !ALL_TYPES.includes(type)) { throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`); } options.root = root; return new ReaddirpStream(options); }; var readdirpPromise = (root, options = {}) => { return new Promise((resolve, reject) => { const files = []; readdirp(root, options).on("data", (entry) => files.push(entry)).on("end", () => resolve(files)).on("error", (error48) => reject(error48)); }); }; readdirp.promise = readdirpPromise; readdirp.ReaddirpStream = ReaddirpStream; readdirp.default = readdirp; module2.exports = readdirp; } }); // node_modules/anymatch/node_modules/picomatch/lib/constants.js var require_constants7 = __commonJS({ "node_modules/anymatch/node_modules/picomatch/lib/constants.js"(exports2, module2) { "use strict"; var path = require("path"); var WIN_SLASH = "\\\\/"; var WIN_NO_SLASH = `[^${WIN_SLASH}]`; var DEFAULT_MAX_EXTGLOB_RECURSION = 0; var DOT_LITERAL = "\\."; var PLUS_LITERAL = "\\+"; var QMARK_LITERAL = "\\?"; var SLASH_LITERAL = "\\/"; var ONE_CHAR = "(?=.)"; var QMARK = "[^/]"; var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; var START_ANCHOR = `(?:^|${SLASH_LITERAL})`; var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; var NO_DOT = `(?!${DOT_LITERAL})`; var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; var STAR = `${QMARK}*?`; var POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR, START_ANCHOR }; var WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; var POSIX_REGEX_SOURCE = { __proto__: null, alnum: "a-zA-Z0-9", alpha: "a-zA-Z", ascii: "\\x00-\\x7F", blank: " \\t", cntrl: "\\x00-\\x1F\\x7F", digit: "0-9", graph: "\\x21-\\x7E", lower: "a-z", print: "\\x20-\\x7E ", punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", space: " \\t\\r\\n\\v\\f", upper: "A-Z", word: "A-Za-z0-9_", xdigit: "A-Fa-f0-9" }; module2.exports = { DEFAULT_MAX_EXTGLOB_RECURSION, MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { __proto__: null, "***": "*", "**/**": "**", "**/**/**": "**" }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` }, "?": { type: "qmark", open: "(?:", close: ")?" }, "+": { type: "plus", open: "(?:", close: ")+" }, "*": { type: "star", open: "(?:", close: ")*" }, "@": { type: "at", open: "(?:", close: ")" } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; } }); // node_modules/anymatch/node_modules/picomatch/lib/utils.js var require_utils4 = __commonJS({ "node_modules/anymatch/node_modules/picomatch/lib/utils.js"(exports2) { "use strict"; var path = require("path"); var win32 = process.platform === "win32"; var { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants7(); exports2.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); exports2.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); exports2.isRegexChar = (str) => str.length === 1 && exports2.hasRegexChars(str); exports2.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); exports2.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); exports2.removeBackslashes = (str) => { return str.replace(REGEX_REMOVE_BACKSLASH, (match) => { return match === "\\" ? "" : match; }); }; exports2.supportsLookbehinds = () => { const segs = process.version.slice(1).split(".").map(Number); if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { return true; } return false; }; exports2.isWindows = (options) => { if (options && typeof options.windows === "boolean") { return options.windows; } return win32 === true || path.sep === "\\"; }; exports2.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === "\\") return exports2.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports2.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith("./")) { output = output.slice(2); state.prefix = "./"; } return output; }; exports2.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? "" : "^"; const append = options.contains ? "" : "$"; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; } }); // node_modules/anymatch/node_modules/picomatch/lib/scan.js var require_scan2 = __commonJS({ "node_modules/anymatch/node_modules/picomatch/lib/scan.js"(exports2, module2) { "use strict"; var utils = require_utils4(); var { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ } = require_constants7(); var isPathSeparator = (code) => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; var depth = (token) => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; var scan = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: "", depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: "", depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT && index === start + 1) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ""; let glob = ""; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ""; glob = str; } else { base = str; } if (base && base !== "" && base !== "/" && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils.removeBackslashes(glob); if (base && backslashes === true) { base = utils.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== "") { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; module2.exports = scan; } }); // node_modules/anymatch/node_modules/picomatch/lib/parse.js var require_parse3 = __commonJS({ "node_modules/anymatch/node_modules/picomatch/lib/parse.js"(exports2, module2) { "use strict"; var constants = require_constants7(); var utils = require_utils4(); var { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants; var expandRange = (args, options) => { if (typeof options.expandRange === "function") { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join("-")}]`; try { new RegExp(value); } catch (ex) { return args.map((v) => utils.escapeRegex(v)).join(".."); } return value; }; var syntaxError2 = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; var splitTopLevel = (input) => { const parts = []; let bracket = 0; let paren = 0; let quote = 0; let value = ""; let escaped = false; for (const ch of input) { if (escaped === true) { value += ch; escaped = false; continue; } if (ch === "\\") { value += ch; escaped = true; continue; } if (ch === '"') { quote = quote === 1 ? 0 : 1; value += ch; continue; } if (quote === 0) { if (ch === "[") { bracket++; } else if (ch === "]" && bracket > 0) { bracket--; } else if (bracket === 0) { if (ch === "(") { paren++; } else if (ch === ")" && paren > 0) { paren--; } else if (ch === "|" && paren === 0) { parts.push(value); value = ""; continue; } } } value += ch; } parts.push(value); return parts; }; var isPlainBranch = (branch) => { let escaped = false; for (const ch of branch) { if (escaped === true) { escaped = false; continue; } if (ch === "\\") { escaped = true; continue; } if (/[?*+@!()[\]{}]/.test(ch)) { return false; } } return true; }; var normalizeSimpleBranch = (branch) => { let value = branch.trim(); let changed = true; while (changed === true) { changed = false; if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { value = value.slice(2, -1); changed = true; } } if (!isPlainBranch(value)) { return; } return value.replace(/\\(.)/g, "$1"); }; var hasRepeatedCharPrefixOverlap = (branches) => { const values = branches.map(normalizeSimpleBranch).filter(Boolean); for (let i = 0; i < values.length; i++) { for (let j = i + 1; j < values.length; j++) { const a = values[i]; const b = values[j]; const char = a[0]; if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { continue; } if (a === b || a.startsWith(b) || b.startsWith(a)) { return true; } } } return false; }; var parseRepeatedExtglob = (pattern, requireEnd = true) => { if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") { return; } let bracket = 0; let paren = 0; let quote = 0; let escaped = false; for (let i = 1; i < pattern.length; i++) { const ch = pattern[i]; if (escaped === true) { escaped = false; continue; } if (ch === "\\") { escaped = true; continue; } if (ch === '"') { quote = quote === 1 ? 0 : 1; continue; } if (quote === 1) { continue; } if (ch === "[") { bracket++; continue; } if (ch === "]" && bracket > 0) { bracket--; continue; } if (bracket > 0) { continue; } if (ch === "(") { paren++; continue; } if (ch === ")") { paren--; if (paren === 0) { if (requireEnd === true && i !== pattern.length - 1) { return; } return { type: pattern[0], body: pattern.slice(2, i), end: i }; } } } }; var getStarExtglobSequenceOutput = (pattern) => { let index = 0; const chars = []; while (index < pattern.length) { const match = parseRepeatedExtglob(pattern.slice(index), false); if (!match || match.type !== "*") { return; } const branches = splitTopLevel(match.body).map((branch2) => branch2.trim()); if (branches.length !== 1) { return; } const branch = normalizeSimpleBranch(branches[0]); if (!branch || branch.length !== 1) { return; } chars.push(branch); index += match.end + 1; } if (chars.length < 1) { return; } const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`; return `${source}*`; }; var repeatedExtglobRecursion = (pattern) => { let depth = 0; let value = pattern.trim(); let match = parseRepeatedExtglob(value); while (match) { depth++; value = match.body.trim(); match = parseRepeatedExtglob(value); } return depth; }; var analyzeRepeatedExtglob = (body, options) => { if (options.maxExtglobRecursion === false) { return { risky: false }; } const max = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants.DEFAULT_MAX_EXTGLOB_RECURSION; const branches = splitTopLevel(body).map((branch) => branch.trim()); if (branches.length > 1) { if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) { return { risky: true }; } } for (const branch of branches) { const safeOutput = getStarExtglobSequenceOutput(branch); if (safeOutput) { return { risky: true, safeOutput }; } if (repeatedExtglobRecursion(branch) > max) { return { risky: true }; } } return { risky: false }; }; var parse3 = (input, options) => { if (typeof input !== "string") { throw new TypeError("Expected a string"); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: "bos", value: "", output: opts.prepend || "" }; const tokens = [bos]; const capture = opts.capture ? "" : "?:"; const win32 = utils.isWindows(options); const PLATFORM_CHARS = constants.globChars(win32); const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = (opts2) => { return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? "" : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } if (typeof opts.noext === "boolean") { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: "", output: "", prefix: "", backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ""; const remaining = () => input.slice(state.index + 1); const consume = (value2 = "", num = 0) => { state.consumed += value2; state.index += num; }; const append = (token) => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = (type) => { state[type]++; stack.push(type); }; const decrement = (type) => { state[type]--; stack.pop(); }; const push = (tok) => { if (prev.type === "globstar") { const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = "star"; prev.value = "*"; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== "paren") { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === "text" && tok.type === "text") { prev.value += tok.value; prev.output = (prev.output || "") + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value2) => { const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" }; token.prev = prev; token.parens = state.parens; token.output = state.output; token.startIndex = state.index; token.tokensIndex = tokens.length; const output = (opts.capture ? "(" : "") + token.open; increment("parens"); push({ type, value: value2, output: state.output ? "" : ONE_CHAR }); push({ type: "paren", extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = (token) => { const literal2 = input.slice(token.startIndex, state.index + 1); const body = input.slice(token.startIndex + 2, state.index); const analysis = analyzeRepeatedExtglob(body, opts); if ((token.type === "plus" || token.type === "star") && analysis.risky) { const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0; const open2 = tokens[token.tokensIndex]; open2.type = "text"; open2.value = literal2; open2.output = safeOutput || utils.escapeRegex(literal2); for (let i = token.tokensIndex + 1; i < tokens.length; i++) { tokens[i].value = ""; tokens[i].output = ""; delete tokens[i].suffix; } state.output = token.output + open2.output; state.backtrack = true; push({ type: "paren", extglob: true, value, output: "" }); decrement("parens"); return; } let output = token.close + (opts.capture ? ")" : ""); let rest; if (token.type === "negate") { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes("/")) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { const expression = parse3(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === "bos") { state.negatedExtglob = true; } } push({ type: "paren", extglob: true, value, output }); decrement("parens"); }; if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc2, chars, first, rest, index) => { if (first === "\\") { backslashes = true; return m; } if (first === "?") { if (esc2) { return esc2 + first + (rest ? QMARK.repeat(rest.length) : ""); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ""); } return QMARK.repeat(chars.length); } if (first === ".") { return DOT_LITERAL.repeat(chars.length); } if (first === "*") { if (esc2) { return esc2 + first + (rest ? star : ""); } return star; } return esc2 ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ""); } else { output = output.replace(/\\+/g, (m) => { return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils.wrapOutput(output, state, options); return state; } while (!eos()) { value = advance(); if (value === "\0") { continue; } if (value === "\\") { const next = peek(); if (next === "/" && opts.bash !== true) { continue; } if (next === "." || next === ";") { continue; } if (!next) { value += "\\"; push({ type: "text", value }); continue; } const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += "\\"; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: "text", value }); continue; } } if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) { if (opts.posix !== false && value === ":") { const inner = prev.value.slice(1); if (inner.includes("[")) { prev.posix = true; if (inner.includes(":")) { const idx = prev.value.lastIndexOf("["); const pre = prev.value.slice(0, idx); const rest2 = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE[rest2]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") { value = `\\${value}`; } if (value === "]" && (prev.value === "[" || prev.value === "[^")) { value = `\\${value}`; } if (opts.posix === true && value === "!" && prev.value === "[") { value = "^"; } prev.value += value; append({ value }); continue; } if (state.quotes === 1 && value !== '"') { value = utils.escapeRegex(value); prev.value += value; append({ value }); continue; } if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: "text", value }); } continue; } if (value === "(") { increment("parens"); push({ type: "paren", value }); continue; } if (value === ")") { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError2("opening", "(")); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: "paren", value, output: state.parens ? ")" : "\\)" }); decrement("parens"); continue; } if (value === "[") { if (opts.nobracket === true || !remaining().includes("]")) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError2("closing", "]")); } value = `\\${value}`; } else { increment("brackets"); } push({ type: "bracket", value }); continue; } if (value === "]") { if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { push({ type: "text", value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError2("opening", "[")); } push({ type: "text", value, output: `\\${value}` }); continue; } decrement("brackets"); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) { value = `/${value}`; } prev.value += value; append({ value }); if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { continue; } const escaped = utils.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } if (value === "{" && opts.nobrace !== true) { increment("braces"); const open2 = { type: "brace", value, output: "(", outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open2); push(open2); continue; } if (value === "}") { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: "text", value, output: value }); continue; } let output = ")"; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === "brace") { break; } if (arr[i].type !== "dots") { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = "\\{"; value = output = "\\}"; state.output = out; for (const t of toks) { state.output += t.output || t.value; } } push({ type: "brace", value, output }); decrement("braces"); braces.pop(); continue; } if (value === "|") { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: "text", value }); continue; } if (value === ",") { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === "braces") { brace.comma = true; output = "|"; } push({ type: "comma", value, output }); continue; } if (value === "/") { if (prev.type === "dot" && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ""; state.output = ""; tokens.pop(); prev = bos; continue; } push({ type: "slash", value, output: SLASH_LITERAL }); continue; } if (value === ".") { if (state.braces > 0 && prev.type === "dot") { if (prev.value === ".") prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = "dots"; prev.output += value; prev.value += value; brace.dots = true; continue; } if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { push({ type: "text", value, output: DOT_LITERAL }); continue; } push({ type: "dot", value, output: DOT_LITERAL }); continue; } if (value === "?") { const isGroup = prev && prev.value === "("; if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { extglobOpen("qmark", value); continue; } if (prev && prev.type === "paren") { const next = peek(); let output = value; if (next === "<" && !utils.supportsLookbehinds()) { throw new Error("Node.js v10 or higher is required for regex lookbehinds"); } if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) { output = `\\${value}`; } push({ type: "text", value, output }); continue; } if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { push({ type: "qmark", value, output: QMARK_NO_DOT }); continue; } push({ type: "qmark", value, output: QMARK }); continue; } if (value === "!") { if (opts.noextglob !== true && peek() === "(") { if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { extglobOpen("negate", value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } if (value === "+") { if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { extglobOpen("plus", value); continue; } if (prev && prev.value === "(" || opts.regex === false) { push({ type: "plus", value, output: PLUS_LITERAL }); continue; } if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { push({ type: "plus", value }); continue; } push({ type: "plus", value: PLUS_LITERAL }); continue; } if (value === "@") { if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { push({ type: "at", extglob: true, value, output: "" }); continue; } push({ type: "text", value }); continue; } if (value !== "*") { if (value === "$" || value === "^") { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: "text", value }); continue; } if (prev && (prev.type === "globstar" || prev.star === true)) { prev.type = "star"; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen("star", value); continue; } if (prev.type === "star") { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === "slash" || prior.type === "bos"; const afterStar = before && (before.type === "star" || before.type === "globstar"); if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { push({ type: "star", value, output: "" }); continue; } const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) { push({ type: "star", value, output: "" }); continue; } while (rest.slice(0, 3) === "/**") { const after = input[state.index + 4]; if (after && after !== "/") { break; } rest = rest.slice(3); consume("/**", 3); } if (prior.type === "bos" && eos()) { prev.type = "globstar"; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = "globstar"; prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { const end = rest[1] !== void 0 ? "|$" : ""; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = "globstar"; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: "slash", value: "/", output: "" }); continue; } if (prior.type === "bos" && rest[0] === "/") { prev.type = "globstar"; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: "slash", value: "/", output: "" }); continue; } state.output = state.output.slice(0, -prev.output.length); prev.type = "globstar"; prev.output = globstar(opts); prev.value += value; state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: "star", value, output: star }; if (opts.bash === true) { token.output = ".*?"; if (prev.type === "bos" || prev.type === "slash") { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { if (prev.type === "dot") { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== "*") { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", "]")); state.output = utils.escapeLast(state.output, "["); decrement("brackets"); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", ")")); state.output = utils.escapeLast(state.output, "("); decrement("parens"); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError2("closing", "}")); state.output = utils.escapeLast(state.output, "{"); decrement("braces"); } if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) { push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` }); } if (state.backtrack === true) { state.output = ""; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; parse3.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils.isWindows(options); const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? "" : "?:"; const state = { negated: false, prefix: "" }; let star = opts.bash === true ? ".*?" : STAR; if (opts.capture) { star = `(${star})`; } const globstar = (opts2) => { if (opts2.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = (str) => { switch (str) { case "*": return `${nodot}${ONE_CHAR}${star}`; case ".*": return `${DOT_LITERAL}${ONE_CHAR}${star}`; case "*.*": return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case "*/*": return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case "**": return nodot + globstar(opts); case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source2 = create(match[1]); if (!source2) return; return source2 + DOT_LITERAL + match[2]; } } }; const output = utils.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; module2.exports = parse3; } }); // node_modules/anymatch/node_modules/picomatch/lib/picomatch.js var require_picomatch3 = __commonJS({ "node_modules/anymatch/node_modules/picomatch/lib/picomatch.js"(exports2, module2) { "use strict"; var path = require("path"); var scan = require_scan2(); var parse3 = require_parse3(); var utils = require_utils4(); var constants = require_constants7(); var isObject2 = (val) => val && typeof val === "object" && !Array.isArray(val); var picomatch = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map((input) => picomatch(input, options, returnState)); const arrayMatcher = (str) => { for (const isMatch of fns) { const state2 = isMatch(str); if (state2) return state2; } return false; }; return arrayMatcher; } const isState = isObject2(glob) && glob.tokens && glob.input; if (glob === "" || typeof glob !== "string" && !isState) { throw new TypeError("Expected pattern to be a non-empty string"); } const opts = options || {}; const posix = utils.isWindows(options); const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === "function") { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === "function") { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === "function") { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; picomatch.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== "string") { throw new TypeError("Expected input to be a string"); } if (input === "") { return { isMatch: false, output: "" }; } const opts = options || {}; const format = opts.format || (posix ? utils.toPosixSlashes : null); let match = input === glob; let output = match && format ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); return regex.test(path.basename(input)); }; picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); picomatch.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map((p) => picomatch.parse(p, options)); return parse3(pattern, { ...options, fastpaths: false }); }; picomatch.scan = (input, options) => scan(input, options); picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? "" : "^"; const append = opts.contains ? "" : "$"; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== "string") { throw new TypeError("Expected a non-empty string"); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) { parsed.output = parse3.fastpaths(input, options); } if (!parsed.output) { parsed = parse3(input, options); } return picomatch.compileRe(parsed, options, returnOutput, returnState); }; picomatch.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; picomatch.constants = constants; module2.exports = picomatch; } }); // node_modules/anymatch/node_modules/picomatch/index.js var require_picomatch4 = __commonJS({ "node_modules/anymatch/node_modules/picomatch/index.js"(exports2, module2) { "use strict"; module2.exports = require_picomatch3(); } }); // node_modules/normalize-path/index.js var require_normalize_path = __commonJS({ "node_modules/normalize-path/index.js"(exports2, module2) { module2.exports = function(path, stripTrailing) { if (typeof path !== "string") { throw new TypeError("expected path to be a string"); } if (path === "\\" || path === "/") return "/"; var len = path.length; if (len <= 1) return path; var prefix = ""; if (len > 4 && path[3] === "\\") { var ch = path[2]; if ((ch === "?" || ch === ".") && path.slice(0, 2) === "\\\\") { path = path.slice(2); prefix = "//"; } } var segs = path.split(/[/\\]+/); if (stripTrailing !== false && segs[segs.length - 1] === "") { segs.pop(); } return prefix + segs.join("/"); }; } }); // node_modules/anymatch/index.js var require_anymatch = __commonJS({ "node_modules/anymatch/index.js"(exports2, module2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var picomatch = require_picomatch4(); var normalizePath = require_normalize_path(); var BANG = "!"; var DEFAULT_OPTIONS = { returnIndex: false }; var arrify = (item) => Array.isArray(item) ? item : [item]; var createPattern = (matcher, options) => { if (typeof matcher === "function") { return matcher; } if (typeof matcher === "string") { const glob = picomatch(matcher, options); return (string4) => matcher === string4 || glob(string4); } if (matcher instanceof RegExp) { return (string4) => matcher.test(string4); } return (string4) => false; }; var matchPatterns = (patterns, negPatterns, args, returnIndex) => { const isList = Array.isArray(args); const _path = isList ? args[0] : args; if (!isList && typeof _path !== "string") { throw new TypeError("anymatch: second argument must be a string: got " + Object.prototype.toString.call(_path)); } const path = normalizePath(_path, false); for (let index = 0; index < negPatterns.length; index++) { const nglob = negPatterns[index]; if (nglob(path)) { return returnIndex ? -1 : false; } } const applied = isList && [path].concat(args.slice(1)); for (let index = 0; index < patterns.length; index++) { const pattern = patterns[index]; if (isList ? pattern(...applied) : pattern(path)) { return returnIndex ? index : true; } } return returnIndex ? -1 : false; }; var anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => { if (matchers == null) { throw new TypeError("anymatch: specify first argument"); } const opts = typeof options === "boolean" ? { returnIndex: options } : options; const returnIndex = opts.returnIndex || false; const mtchers = arrify(matchers); const negatedGlobs = mtchers.filter((item) => typeof item === "string" && item.charAt(0) === BANG).map((item) => item.slice(1)).map((item) => picomatch(item, opts)); const patterns = mtchers.filter((item) => typeof item !== "string" || typeof item === "string" && item.charAt(0) !== BANG).map((matcher) => createPattern(matcher, opts)); if (testString == null) { return (testString2, ri = false) => { const returnIndex2 = typeof ri === "boolean" ? ri : false; return matchPatterns(patterns, negatedGlobs, testString2, returnIndex2); }; } return matchPatterns(patterns, negatedGlobs, testString, returnIndex); }; anymatch.default = anymatch; module2.exports = anymatch; } }); // node_modules/is-extglob/index.js var require_is_extglob = __commonJS({ "node_modules/is-extglob/index.js"(exports2, module2) { module2.exports = function isExtglob(str) { if (typeof str !== "string" || str === "") { return false; } var match; while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; } }); // node_modules/is-glob/index.js var require_is_glob = __commonJS({ "node_modules/is-glob/index.js"(exports2, module2) { var isExtglob = require_is_extglob(); var chars = { "{": "}", "(": ")", "[": "]" }; var strictCheck = function(str) { if (str[0] === "!") { return true; } var index = 0; var pipeIndex = -2; var closeSquareIndex = -2; var closeCurlyIndex = -2; var closeParenIndex = -2; var backSlashIndex = -2; while (index < str.length) { if (str[index] === "*") { return true; } if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) { return true; } if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") { if (closeSquareIndex < index) { closeSquareIndex = str.indexOf("]", index); } if (closeSquareIndex > index) { if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } backSlashIndex = str.indexOf("\\", index); if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } } } if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") { closeCurlyIndex = str.indexOf("}", index); if (closeCurlyIndex > index) { backSlashIndex = str.indexOf("\\", index); if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { return true; } } } if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") { closeParenIndex = str.indexOf(")", index); if (closeParenIndex > index) { backSlashIndex = str.indexOf("\\", index); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") { if (pipeIndex < index) { pipeIndex = str.indexOf("|", index); } if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") { closeParenIndex = str.indexOf(")", pipeIndex); if (closeParenIndex > pipeIndex) { backSlashIndex = str.indexOf("\\", pipeIndex); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } } if (str[index] === "\\") { var open2 = str[index + 1]; index += 2; var close = chars[open2]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === "!") { return true; } } else { index++; } } return false; }; var relaxedCheck = function(str) { if (str[0] === "!") { return true; } var index = 0; while (index < str.length) { if (/[*?{}()[\]]/.test(str[index])) { return true; } if (str[index] === "\\") { var open2 = str[index + 1]; index += 2; var close = chars[open2]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === "!") { return true; } } else { index++; } } return false; }; module2.exports = function isGlob(str, options) { if (typeof str !== "string" || str === "") { return false; } if (isExtglob(str)) { return true; } var check2 = strictCheck; if (options && options.strict === false) { check2 = relaxedCheck; } return check2(str); }; } }); // node_modules/glob-parent/index.js var require_glob_parent = __commonJS({ "node_modules/glob-parent/index.js"(exports2, module2) { "use strict"; var isGlob = require_is_glob(); var pathPosixDirname = require("path").posix.dirname; var isWin32 = require("os").platform() === "win32"; var slash = "/"; var backslash = /\\/g; var enclosure = /[\{\[].*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; module2.exports = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } if (enclosure.test(str)) { str += slash; } str += "a"; do { str = pathPosixDirname(str); } while (isGlob(str) || globby.test(str)); return str.replace(escaped, "$1"); }; } }); // node_modules/braces/lib/utils.js var require_utils5 = __commonJS({ "node_modules/braces/lib/utils.js"(exports2) { "use strict"; exports2.isInteger = (num) => { if (typeof num === "number") { return Number.isInteger(num); } if (typeof num === "string" && num.trim() !== "") { return Number.isInteger(Number(num)); } return false; }; exports2.find = (node, type) => node.nodes.find((node2) => node2.type === type); exports2.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports2.isInteger(min) || !exports2.isInteger(max)) return false; return (Number(max) - Number(min)) / Number(step) >= limit; }; exports2.escapeNode = (block, n = 0, type) => { const node = block.nodes[n]; if (!node) return; if (type && node.type === type || node.type === "open" || node.type === "close") { if (node.escaped !== true) { node.value = "\\" + node.value; node.escaped = true; } } }; exports2.encloseBrace = (node) => { if (node.type !== "brace") return false; if (node.commas >> 0 + node.ranges >> 0 === 0) { node.invalid = true; return true; } return false; }; exports2.isInvalidBrace = (block) => { if (block.type !== "brace") return false; if (block.invalid === true || block.dollar) return true; if (block.commas >> 0 + block.ranges >> 0 === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; exports2.isOpenOrClose = (node) => { if (node.type === "open" || node.type === "close") { return true; } return node.open === true || node.close === true; }; exports2.reduce = (nodes) => nodes.reduce((acc, node) => { if (node.type === "text") acc.push(node.value); if (node.type === "range") node.type = "text"; return acc; }, []); exports2.flatten = (...args) => { const result = []; const flat = (arr) => { for (let i = 0; i < arr.length; i++) { const ele = arr[i]; if (Array.isArray(ele)) { flat(ele); continue; } if (ele !== void 0) { result.push(ele); } } return result; }; flat(args); return result; }; } }); // node_modules/braces/lib/stringify.js var require_stringify3 = __commonJS({ "node_modules/braces/lib/stringify.js"(exports2, module2) { "use strict"; var utils = require_utils5(); module2.exports = (ast, options = {}) => { const stringify = (node, parent = {}) => { const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ""; if (node.value) { if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { return "\\" + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (const child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; } }); // node_modules/is-number/index.js var require_is_number = __commonJS({ "node_modules/is-number/index.js"(exports2, module2) { "use strict"; module2.exports = function(num) { if (typeof num === "number") { return num - num === 0; } if (typeof num === "string" && num.trim() !== "") { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; } }); // node_modules/to-regex-range/index.js var require_to_regex_range = __commonJS({ "node_modules/to-regex-range/index.js"(exports2, module2) { "use strict"; var isNumber = require_is_number(); var toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError("toRegexRange: expected the first argument to be a number"); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError("toRegexRange: expected the second argument to be a number."); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === "boolean") { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey2 = min + ":" + max + "=" + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey2)) { return toRegexRange.cache[cacheKey2].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + "|" + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives, opts); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && positives.length + negatives.length > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey2] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, "-", false, options) || []; let onlyPositive = filterPatterns(pos, neg, "", false, options) || []; let intersected = filterPatterns(neg, pos, "-?", true, options) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join("|"); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = /* @__PURE__ */ new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ""; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== "0" || stopDigit !== "9") { pattern += toCharacterClass(startDigit, stopDigit, options); } else { count++; } } if (count) { pattern += options.shorthand === true ? "\\d" : "[0-9]"; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max2 = ranges[i]; let obj = rangeToPattern(String(start), String(max2), options); let zeros = ""; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max2 + 1; continue; } if (tok.isPadded) { zeros = padZeros(max2, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max2 + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection2, options) { let result = []; for (let ele of arr) { let { string: string4 } = ele; if (!intersection2 && !contains(comparison, "string", string4)) { result.push(prefix + string4); } if (intersection2 && contains(comparison, "string", string4)) { result.push(prefix + string4); } } return result; } function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some((ele) => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + "9".repeat(len)); } function countZeros(integer2, zeros) { return integer2 - integer2 % Math.pow(10, zeros); } function toQuantifier(digits) { let [start = 0, stop = ""] = digits; if (stop || start > 1) { return `{${start + (stop ? "," + stop : "")}}`; } return ""; } function toCharacterClass(a, b, options) { return `[${a}${b - a === 1 ? "" : "-"}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff2 = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff2) { case 0: return ""; case 1: return relax ? "0?" : "0"; case 2: return relax ? "0{0,2}" : "00"; default: { return relax ? `0{0,${diff2}}` : `0{${diff2}}`; } } } toRegexRange.cache = {}; toRegexRange.clearCache = () => toRegexRange.cache = {}; module2.exports = toRegexRange; } }); // node_modules/fill-range/index.js var require_fill_range = __commonJS({ "node_modules/fill-range/index.js"(exports2, module2) { "use strict"; var util2 = require("util"); var toRegexRange = require_to_regex_range(); var isObject2 = (val) => val !== null && typeof val === "object" && !Array.isArray(val); var transform2 = (toNumber) => { return (value) => toNumber === true ? Number(value) : String(value); }; var isValidValue = (value) => { return typeof value === "number" || typeof value === "string" && value !== ""; }; var isNumber = (num) => Number.isInteger(+num); var zeros = (input) => { let value = `${input}`; let index = -1; if (value[0] === "-") value = value.slice(1); if (value === "0") return false; while (value[++index] === "0") ; return index > 0; }; var stringify = (start, end, options) => { if (typeof start === "string" || typeof end === "string") { return true; } return options.stringify === true; }; var pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === "-" ? "-" : ""; if (dash) input = input.slice(1); input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0"); } if (toNumber === false) { return String(input); } return input; }; var toMaxLen = (input, maxLength) => { let negative = input[0] === "-" ? "-" : ""; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = "0" + input; return negative ? "-" + input : input; }; var toSequence = (parts, options, maxLen) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? "" : "?:"; let positives = ""; let negatives = ""; let result; if (parts.positives.length) { positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|"); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; var toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; var toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? "" : "?:"; return wrap ? `(${prefix}${start.join("|")})` : start.join("|"); } return toRegexRange(start, end, options); }; var rangeError = (...args) => { return new RangeError("Invalid range arguments: " + util2.inspect(...args)); }; var invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; var invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; var fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify(start, end, options) === false; let format = options.transform || transform2(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, { wrap: false, ...options }); } return range; }; var fillLetters = (start, end, step = 1, options = {}) => { if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) { return invalidRange(start, end, options); } let format = options.transform || ((val) => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; var fill = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === "function") { return fill(start, end, 1, { transform: step }); } if (isObject2(step)) { return fill(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber(step)) { if (step != null && !isObject2(step)) return invalidStep(step, opts); return fill(start, end, 1, step); } if (isNumber(start) && isNumber(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; module2.exports = fill; } }); // node_modules/braces/lib/compile.js var require_compile = __commonJS({ "node_modules/braces/lib/compile.js"(exports2, module2) { "use strict"; var fill = require_fill_range(); var utils = require_utils5(); var compile = (ast, options = {}) => { const walk = (node, parent = {}) => { const invalidBlock = utils.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; const invalid = invalidBlock === true || invalidNode === true; const prefix = options.escapeInvalid === true ? "\\" : ""; let output = ""; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { console.log("node.isClose", prefix, node.value); return prefix + node.value; } if (node.type === "open") { return invalid ? prefix + node.value : "("; } if (node.type === "close") { return invalid ? prefix + node.value : ")"; } if (node.type === "comma") { return node.prev.type === "comma" ? "" : invalid ? node.value : "|"; } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { const args = utils.reduce(node.nodes); const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (const child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; module2.exports = compile; } }); // node_modules/braces/lib/expand.js var require_expand = __commonJS({ "node_modules/braces/lib/expand.js"(exports2, module2) { "use strict"; var fill = require_fill_range(); var stringify = require_stringify3(); var utils = require_utils5(); var append = (queue = "", stash = "", enclose = false) => { const result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash; } for (const item of queue) { if (Array.isArray(item)) { for (const value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === "string") ele = `{${ele}}`; result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); } } } return utils.flatten(result); }; var expand = (ast, options = {}) => { const rangeLimit = options.rangeLimit === void 0 ? 1e3 : options.rangeLimit; const walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== "brace" && p.type !== "root" && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append(q.pop(), stringify(node, options))); return; } if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) { q.push(append(q.pop(), ["{}"])); return; } if (node.nodes && node.ranges > 0) { const args = utils.reduce(node.nodes); if (utils.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit."); } let range = fill(...args, options); if (range.length === 0) { range = stringify(node, options); } q.push(append(q.pop(), range)); node.nodes = []; return; } const enclose = utils.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== "brace" && block.type !== "root" && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { const child = node.nodes[i]; if (child.type === "comma" && node.type === "brace") { if (i === 1) queue.push(""); queue.push(""); continue; } if (child.type === "close") { q.push(append(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== "open") { queue.push(append(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils.flatten(walk(ast)); }; module2.exports = expand; } }); // node_modules/braces/lib/constants.js var require_constants8 = __commonJS({ "node_modules/braces/lib/constants.js"(exports2, module2) { "use strict"; module2.exports = { MAX_LENGTH: 1e4, // Digits CHAR_0: "0", /* 0 */ CHAR_9: "9", /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: "A", /* A */ CHAR_LOWERCASE_A: "a", /* a */ CHAR_UPPERCASE_Z: "Z", /* Z */ CHAR_LOWERCASE_Z: "z", /* z */ CHAR_LEFT_PARENTHESES: "(", /* ( */ CHAR_RIGHT_PARENTHESES: ")", /* ) */ CHAR_ASTERISK: "*", /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: "&", /* & */ CHAR_AT: "@", /* @ */ CHAR_BACKSLASH: "\\", /* \ */ CHAR_BACKTICK: "`", /* ` */ CHAR_CARRIAGE_RETURN: "\r", /* \r */ CHAR_CIRCUMFLEX_ACCENT: "^", /* ^ */ CHAR_COLON: ":", /* : */ CHAR_COMMA: ",", /* , */ CHAR_DOLLAR: "$", /* . */ CHAR_DOT: ".", /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: "=", /* = */ CHAR_EXCLAMATION_MARK: "!", /* ! */ CHAR_FORM_FEED: "\f", /* \f */ CHAR_FORWARD_SLASH: "/", /* / */ CHAR_HASH: "#", /* # */ CHAR_HYPHEN_MINUS: "-", /* - */ CHAR_LEFT_ANGLE_BRACKET: "<", /* < */ CHAR_LEFT_CURLY_BRACE: "{", /* { */ CHAR_LEFT_SQUARE_BRACKET: "[", /* [ */ CHAR_LINE_FEED: "\n", /* \n */ CHAR_NO_BREAK_SPACE: "\xA0", /* \u00A0 */ CHAR_PERCENT: "%", /* % */ CHAR_PLUS: "+", /* + */ CHAR_QUESTION_MARK: "?", /* ? */ CHAR_RIGHT_ANGLE_BRACKET: ">", /* > */ CHAR_RIGHT_CURLY_BRACE: "}", /* } */ CHAR_RIGHT_SQUARE_BRACKET: "]", /* ] */ CHAR_SEMICOLON: ";", /* ; */ CHAR_SINGLE_QUOTE: "'", /* ' */ CHAR_SPACE: " ", /* */ CHAR_TAB: " ", /* \t */ CHAR_UNDERSCORE: "_", /* _ */ CHAR_VERTICAL_LINE: "|", /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: "\uFEFF" /* \uFEFF */ }; } }); // node_modules/braces/lib/parse.js var require_parse4 = __commonJS({ "node_modules/braces/lib/parse.js"(exports2, module2) { "use strict"; var stringify = require_stringify3(); var { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = require_constants8(); var parse3 = (input, options = {}) => { if (typeof input !== "string") { throw new TypeError("Expected a string"); } const opts = options || {}; const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } const ast = { type: "root", input, nodes: [] }; const stack = [ast]; let block = ast; let prev = ast; let brackets = 0; const length = input.length; let index = 0; let depth = 0; let value; const advance = () => input[index++]; const push = (node) => { if (node.type === "text" && prev.type === "dot") { prev.type = "text"; } if (prev && prev.type === "text" && node.type === "text") { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: "bos" }); while (index < length) { block = stack[stack.length - 1]; value = advance(); if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } if (value === CHAR_BACKSLASH) { push({ type: "text", value: (options.keepEscaping ? value : "") + advance() }); continue; } if (value === CHAR_RIGHT_SQUARE_BRACKET) { push({ type: "text", value: "\\" + value }); continue; } if (value === CHAR_LEFT_SQUARE_BRACKET) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { brackets--; if (brackets === 0) { break; } } } push({ type: "text", value }); continue; } if (value === CHAR_LEFT_PARENTHESES) { block = push({ type: "paren", nodes: [] }); stack.push(block); push({ type: "text", value }); continue; } if (value === CHAR_RIGHT_PARENTHESES) { if (block.type !== "paren") { push({ type: "text", value }); continue; } block = stack.pop(); push({ type: "text", value }); block = stack[stack.length - 1]; continue; } if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { const open2 = value; let next; if (options.keepQuotes !== true) { value = ""; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open2) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: "text", value }); continue; } if (value === CHAR_LEFT_CURLY_BRACE) { depth++; const dollar = prev.value && prev.value.slice(-1) === "$" || block.dollar === true; const brace = { type: "brace", open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: "open", value }); continue; } if (value === CHAR_RIGHT_CURLY_BRACE) { if (block.type !== "brace") { push({ type: "text", value }); continue; } const type = "close"; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } if (value === CHAR_COMMA && depth > 0) { if (block.ranges > 0) { block.ranges = 0; const open2 = block.nodes.shift(); block.nodes = [open2, { type: "text", value: stringify(block) }]; } push({ type: "comma", value }); block.commas++; continue; } if (value === CHAR_DOT && depth > 0 && block.commas === 0) { const siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: "text", value }); continue; } if (prev.type === "dot") { block.range = []; prev.value += value; prev.type = "range"; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = "text"; continue; } block.ranges++; block.args = []; continue; } if (prev.type === "range") { siblings.pop(); const before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: "dot", value }); continue; } push({ type: "text", value }); } do { block = stack.pop(); if (block.type !== "root") { block.nodes.forEach((node) => { if (!node.nodes) { if (node.type === "open") node.isOpen = true; if (node.type === "close") node.isClose = true; if (!node.nodes) node.type = "text"; node.invalid = true; } }); const parent = stack[stack.length - 1]; const index2 = parent.nodes.indexOf(block); parent.nodes.splice(index2, 1, ...block.nodes); } } while (stack.length > 0); push({ type: "eos" }); return ast; }; module2.exports = parse3; } }); // node_modules/braces/index.js var require_braces = __commonJS({ "node_modules/braces/index.js"(exports2, module2) { "use strict"; var stringify = require_stringify3(); var compile = require_compile(); var expand = require_expand(); var parse3 = require_parse4(); var braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (const pattern of input) { const result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; braces.parse = (input, options = {}) => parse3(input, options); braces.stringify = (input, options = {}) => { if (typeof input === "string") { return stringify(braces.parse(input, options), options); } return stringify(input, options); }; braces.compile = (input, options = {}) => { if (typeof input === "string") { input = braces.parse(input, options); } return compile(input, options); }; braces.expand = (input, options = {}) => { if (typeof input === "string") { input = braces.parse(input, options); } let result = expand(input, options); if (options.noempty === true) { result = result.filter(Boolean); } if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; braces.create = (input, options = {}) => { if (input === "" || input.length < 3) { return [input]; } return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; module2.exports = braces; } }); // node_modules/binary-extensions/binary-extensions.json var require_binary_extensions = __commonJS({ "node_modules/binary-extensions/binary-extensions.json"(exports2, module2) { module2.exports = [ "3dm", "3ds", "3g2", "3gp", "7z", "a", "aac", "adp", "afdesign", "afphoto", "afpub", "ai", "aif", "aiff", "alz", "ape", "apk", "appimage", "ar", "arj", "asf", "au", "avi", "bak", "baml", "bh", "bin", "bk", "bmp", "btif", "bz2", "bzip2", "cab", "caf", "cgm", "class", "cmx", "cpio", "cr2", "cur", "dat", "dcm", "deb", "dex", "djvu", "dll", "dmg", "dng", "doc", "docm", "docx", "dot", "dotm", "dra", "DS_Store", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", "flatpak", "fli", "flv", "fpx", "fst", "fvt", "g3", "gh", "gif", "graffle", "gz", "gzip", "h261", "h263", "h264", "icns", "ico", "ief", "img", "ipa", "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "key", "ktx", "lha", "lib", "lvp", "lz", "lzh", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", "mdi", "mht", "mid", "midi", "mj2", "mka", "mkv", "mmr", "mng", "mobi", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", "nef", "npx", "numbers", "nupkg", "o", "odp", "ods", "odt", "oga", "ogg", "ogv", "otf", "ott", "pages", "pbm", "pcx", "pdb", "pdf", "pea", "pgm", "pic", "png", "pnm", "pot", "potm", "potx", "ppa", "ppam", "ppm", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "resources", "rgb", "rip", "rlc", "rmf", "rmvb", "rpm", "rtf", "rz", "s3m", "s7z", "scpt", "sgi", "shar", "snap", "sil", "sketch", "slk", "smv", "snk", "so", "stl", "suo", "sub", "swf", "tar", "tbz", "tbz2", "tga", "tgz", "thmx", "tif", "tiff", "tlz", "ttc", "ttf", "txz", "udf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", "webm", "webp", "whl", "wim", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wrm", "wvx", "xbm", "xif", "xla", "xlam", "xls", "xlsb", "xlsm", "xlsx", "xlt", "xltm", "xltx", "xm", "xmind", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx" ]; } }); // node_modules/binary-extensions/index.js var require_binary_extensions2 = __commonJS({ "node_modules/binary-extensions/index.js"(exports2, module2) { module2.exports = require_binary_extensions(); } }); // node_modules/is-binary-path/index.js var require_is_binary_path = __commonJS({ "node_modules/is-binary-path/index.js"(exports2, module2) { "use strict"; var path = require("path"); var binaryExtensions = require_binary_extensions2(); var extensions = new Set(binaryExtensions); module2.exports = (filePath) => extensions.has(path.extname(filePath).slice(1).toLowerCase()); } }); // node_modules/chokidar/lib/constants.js var require_constants9 = __commonJS({ "node_modules/chokidar/lib/constants.js"(exports2) { "use strict"; var { sep } = require("path"); var { platform } = process; var os = require("os"); exports2.EV_ALL = "all"; exports2.EV_READY = "ready"; exports2.EV_ADD = "add"; exports2.EV_CHANGE = "change"; exports2.EV_ADD_DIR = "addDir"; exports2.EV_UNLINK = "unlink"; exports2.EV_UNLINK_DIR = "unlinkDir"; exports2.EV_RAW = "raw"; exports2.EV_ERROR = "error"; exports2.STR_DATA = "data"; exports2.STR_END = "end"; exports2.STR_CLOSE = "close"; exports2.FSEVENT_CREATED = "created"; exports2.FSEVENT_MODIFIED = "modified"; exports2.FSEVENT_DELETED = "deleted"; exports2.FSEVENT_MOVED = "moved"; exports2.FSEVENT_CLONED = "cloned"; exports2.FSEVENT_UNKNOWN = "unknown"; exports2.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1; exports2.FSEVENT_TYPE_FILE = "file"; exports2.FSEVENT_TYPE_DIRECTORY = "directory"; exports2.FSEVENT_TYPE_SYMLINK = "symlink"; exports2.KEY_LISTENERS = "listeners"; exports2.KEY_ERR = "errHandlers"; exports2.KEY_RAW = "rawEmitters"; exports2.HANDLER_KEYS = [exports2.KEY_LISTENERS, exports2.KEY_ERR, exports2.KEY_RAW]; exports2.DOT_SLASH = `.${sep}`; exports2.BACK_SLASH_RE = /\\/g; exports2.DOUBLE_SLASH_RE = /\/\//; exports2.SLASH_OR_BACK_SLASH_RE = /[/\\]/; exports2.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; exports2.REPLACER_RE = /^\.[/\\]/; exports2.SLASH = "/"; exports2.SLASH_SLASH = "//"; exports2.BRACE_START = "{"; exports2.BANG = "!"; exports2.ONE_DOT = "."; exports2.TWO_DOTS = ".."; exports2.STAR = "*"; exports2.GLOBSTAR = "**"; exports2.ROOT_GLOBSTAR = "/**/*"; exports2.SLASH_GLOBSTAR = "/**"; exports2.DIR_SUFFIX = "Dir"; exports2.ANYMATCH_OPTS = { dot: true }; exports2.STRING_TYPE = "string"; exports2.FUNCTION_TYPE = "function"; exports2.EMPTY_STR = ""; exports2.EMPTY_FN = () => { }; exports2.IDENTITY_FN = (val) => val; exports2.isWindows = platform === "win32"; exports2.isMacos = platform === "darwin"; exports2.isLinux = platform === "linux"; exports2.isIBMi = os.type() === "OS400"; } }); // node_modules/chokidar/lib/nodefs-handler.js var require_nodefs_handler = __commonJS({ "node_modules/chokidar/lib/nodefs-handler.js"(exports2, module2) { "use strict"; var fs = require("fs"); var sysPath = require("path"); var { promisify } = require("util"); var isBinaryPath = require_is_binary_path(); var { isWindows, isLinux, EMPTY_FN, EMPTY_STR, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, EV_CHANGE, EV_ADD, EV_ADD_DIR, EV_ERROR, STR_DATA, STR_END, BRACE_START, STAR } = require_constants9(); var THROTTLE_MODE_WATCH = "watch"; var open2 = promisify(fs.open); var stat = promisify(fs.stat); var lstat = promisify(fs.lstat); var close = promisify(fs.close); var fsrealpath = promisify(fs.realpath); var statMethods = { lstat, stat }; var foreach = (val, fn) => { if (val instanceof Set) { val.forEach(fn); } else { fn(val); } }; var addAndConvert = (main, prop, item) => { let container = main[prop]; if (!(container instanceof Set)) { main[prop] = container = /* @__PURE__ */ new Set([container]); } container.add(item); }; var clearItem = (cont) => (key) => { const set2 = cont[key]; if (set2 instanceof Set) { set2.clear(); } else { delete cont[key]; } }; var delFromSet = (main, prop, item) => { const container = main[prop]; if (container instanceof Set) { container.delete(item); } else if (container === item) { delete main[prop]; } }; var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; var FsWatchInstances = /* @__PURE__ */ new Map(); function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { const handleEvent = (rawEvent, evPath) => { listener(path); emitRaw(rawEvent, evPath, { watchedPath: path }); if (evPath && path !== evPath) { fsWatchBroadcast( sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath) ); } }; try { return fs.watch(path, options, handleEvent); } catch (error48) { errHandler(error48); } } var fsWatchBroadcast = (fullPath, type, val1, val2, val3) => { const cont = FsWatchInstances.get(fullPath); if (!cont) return; foreach(cont[type], (listener) => { listener(val1, val2, val3); }); }; var setFsWatchListener = (path, fullPath, options, handlers) => { const { listener, errHandler, rawEmitter } = handlers; let cont = FsWatchInstances.get(fullPath); let watcher; if (!options.persistent) { watcher = createFsWatchInstance( path, options, listener, errHandler, rawEmitter ); return watcher.close.bind(watcher); } if (cont) { addAndConvert(cont, KEY_LISTENERS, listener); addAndConvert(cont, KEY_ERR, errHandler); addAndConvert(cont, KEY_RAW, rawEmitter); } else { watcher = createFsWatchInstance( path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here fsWatchBroadcast.bind(null, fullPath, KEY_RAW) ); if (!watcher) return; watcher.on(EV_ERROR, async (error48) => { const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); cont.watcherUnusable = true; if (isWindows && error48.code === "EPERM") { try { const fd = await open2(path, "r"); await close(fd); broadcastErr(error48); } catch (err) { } } else { broadcastErr(error48); } }); cont = { listeners: listener, errHandlers: errHandler, rawEmitters: rawEmitter, watcher }; FsWatchInstances.set(fullPath, cont); } return () => { delFromSet(cont, KEY_LISTENERS, listener); delFromSet(cont, KEY_ERR, errHandler); delFromSet(cont, KEY_RAW, rawEmitter); if (isEmptySet(cont.listeners)) { cont.watcher.close(); FsWatchInstances.delete(fullPath); HANDLER_KEYS.forEach(clearItem(cont)); cont.watcher = void 0; Object.freeze(cont); } }; }; var FsWatchFileInstances = /* @__PURE__ */ new Map(); var setFsWatchFileListener = (path, fullPath, options, handlers) => { const { listener, rawEmitter } = handlers; let cont = FsWatchFileInstances.get(fullPath); let listeners = /* @__PURE__ */ new Set(); let rawEmitters = /* @__PURE__ */ new Set(); const copts = cont && cont.options; if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { listeners = cont.listeners; rawEmitters = cont.rawEmitters; fs.unwatchFile(fullPath); cont = void 0; } if (cont) { addAndConvert(cont, KEY_LISTENERS, listener); addAndConvert(cont, KEY_RAW, rawEmitter); } else { cont = { listeners: listener, rawEmitters: rawEmitter, options, watcher: fs.watchFile(fullPath, options, (curr, prev) => { foreach(cont.rawEmitters, (rawEmitter2) => { rawEmitter2(EV_CHANGE, fullPath, { curr, prev }); }); const currmtime = curr.mtimeMs; if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { foreach(cont.listeners, (listener2) => listener2(path, curr)); } }) }; FsWatchFileInstances.set(fullPath, cont); } return () => { delFromSet(cont, KEY_LISTENERS, listener); delFromSet(cont, KEY_RAW, rawEmitter); if (isEmptySet(cont.listeners)) { FsWatchFileInstances.delete(fullPath); fs.unwatchFile(fullPath); cont.options = cont.watcher = void 0; Object.freeze(cont); } }; }; var NodeFsHandler = class { /** * @param {import("../index").FSWatcher} fsW */ constructor(fsW) { this.fsw = fsW; this._boundHandleError = (error48) => fsW._handleError(error48); } /** * Watch file for changes with fs_watchFile or fs_watch. * @param {String} path to file or dir * @param {Function} listener on fs change * @returns {Function} closer for the watcher instance */ _watchWithNodeFs(path, listener) { const opts = this.fsw.options; const directory = sysPath.dirname(path); const basename = sysPath.basename(path); const parent = this.fsw._getWatchedDir(directory); parent.add(basename); const absolutePath = sysPath.resolve(path); const options = { persistent: opts.persistent }; if (!listener) listener = EMPTY_FN; let closer; if (opts.usePolling) { options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval; closer = setFsWatchFileListener(path, absolutePath, options, { listener, rawEmitter: this.fsw._emitRaw }); } else { closer = setFsWatchListener(path, absolutePath, options, { listener, errHandler: this._boundHandleError, rawEmitter: this.fsw._emitRaw }); } return closer; } /** * Watch a file and emit add event if warranted. * @param {Path} file Path * @param {fs.Stats} stats result of fs_stat * @param {Boolean} initialAdd was the file added at watch instantiation? * @returns {Function} closer for the watcher instance */ _handleFile(file2, stats, initialAdd) { if (this.fsw.closed) { return; } const dirname = sysPath.dirname(file2); const basename = sysPath.basename(file2); const parent = this.fsw._getWatchedDir(dirname); let prevStats = stats; if (parent.has(basename)) return; const listener = async (path, newStats) => { if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5)) return; if (!newStats || newStats.mtimeMs === 0) { try { const newStats2 = await stat(file2); if (this.fsw.closed) return; const at = newStats2.atimeMs; const mt = newStats2.mtimeMs; if (!at || at <= mt || mt !== prevStats.mtimeMs) { this.fsw._emit(EV_CHANGE, file2, newStats2); } if (isLinux && prevStats.ino !== newStats2.ino) { this.fsw._closeFile(path); prevStats = newStats2; this.fsw._addPathCloser(path, this._watchWithNodeFs(file2, listener)); } else { prevStats = newStats2; } } catch (error48) { this.fsw._remove(dirname, basename); } } else if (parent.has(basename)) { const at = newStats.atimeMs; const mt = newStats.mtimeMs; if (!at || at <= mt || mt !== prevStats.mtimeMs) { this.fsw._emit(EV_CHANGE, file2, newStats); } prevStats = newStats; } }; const closer = this._watchWithNodeFs(file2, listener); if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) { if (!this.fsw._throttle(EV_ADD, file2, 0)) return; this.fsw._emit(EV_ADD, file2, stats); } return closer; } /** * Handle symlinks encountered while reading a dir. * @param {Object} entry returned by readdirp * @param {String} directory path of dir being read * @param {String} path of this item * @param {String} item basename of this item * @returns {Promise} true if no more processing is needed for this entry. */ async _handleSymlink(entry, directory, path, item) { if (this.fsw.closed) { return; } const full = entry.fullPath; const dir = this.fsw._getWatchedDir(directory); if (!this.fsw.options.followSymlinks) { this.fsw._incrReadyCount(); let linkPath; try { linkPath = await fsrealpath(path); } catch (e) { this.fsw._emitReady(); return true; } if (this.fsw.closed) return; if (dir.has(item)) { if (this.fsw._symlinkPaths.get(full) !== linkPath) { this.fsw._symlinkPaths.set(full, linkPath); this.fsw._emit(EV_CHANGE, path, entry.stats); } } else { dir.add(item); this.fsw._symlinkPaths.set(full, linkPath); this.fsw._emit(EV_ADD, path, entry.stats); } this.fsw._emitReady(); return true; } if (this.fsw._symlinkPaths.has(full)) { return true; } this.fsw._symlinkPaths.set(full, true); } _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { directory = sysPath.join(directory, EMPTY_STR); if (!wh.hasGlob) { throttler = this.fsw._throttle("readdir", directory, 1e3); if (!throttler) return; } const previous = this.fsw._getWatchedDir(wh.path); const current = /* @__PURE__ */ new Set(); let stream = this.fsw._readdirp(directory, { fileFilter: (entry) => wh.filterPath(entry), directoryFilter: (entry) => wh.filterDir(entry), depth: 0 }).on(STR_DATA, async (entry) => { if (this.fsw.closed) { stream = void 0; return; } const item = entry.path; let path = sysPath.join(directory, item); current.add(item); if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) { return; } if (this.fsw.closed) { stream = void 0; return; } if (item === target || !target && !previous.has(item)) { this.fsw._incrReadyCount(); path = sysPath.join(dir, sysPath.relative(dir, path)); this._addToNodeFs(path, initialAdd, wh, depth + 1); } }).on(EV_ERROR, this._boundHandleError); return new Promise( (resolve) => stream.once(STR_END, () => { if (this.fsw.closed) { stream = void 0; return; } const wasThrottled = throttler ? throttler.clear() : false; resolve(); previous.getChildren().filter((item) => { return item !== directory && !current.has(item) && // in case of intersecting globs; // a path may have been filtered out of this readdir, but // shouldn't be removed because it matches a different glob (!wh.hasGlob || wh.filterPath({ fullPath: sysPath.resolve(directory, item) })); }).forEach((item) => { this.fsw._remove(directory, item); }); stream = void 0; if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler); }) ); } /** * Read directory to add / remove files from `@watched` list and re-read it on change. * @param {String} dir fs path * @param {fs.Stats} stats * @param {Boolean} initialAdd * @param {Number} depth relative to user-supplied path * @param {String} target child path targeted for watch * @param {Object} wh Common watch helpers for this path * @param {String} realpath * @returns {Promise} closer for the watcher instance. */ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); const tracked = parentDir.has(sysPath.basename(dir)); if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats); } parentDir.add(sysPath.basename(dir)); this.fsw._getWatchedDir(dir); let throttler; let closer; const oDepth = this.fsw.options.depth; if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { if (!target) { await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); if (this.fsw.closed) return; } closer = this._watchWithNodeFs(dir, (dirPath, stats2) => { if (stats2 && stats2.mtimeMs === 0) return; this._handleRead(dirPath, false, wh, target, dir, depth, throttler); }); } return closer; } /** * Handle added file, directory, or glob pattern. * Delegates call to _handleFile / _handleDir after checks. * @param {String} path to file or ir * @param {Boolean} initialAdd was the file added at watch instantiation? * @param {Object} priorWh depth relative to user-supplied path * @param {Number} depth Child path actually targeted for watch * @param {String=} target Child path actually targeted for watch * @returns {Promise} */ async _addToNodeFs(path, initialAdd, priorWh, depth, target) { const ready = this.fsw._emitReady; if (this.fsw._isIgnored(path) || this.fsw.closed) { ready(); return false; } const wh = this.fsw._getWatchHelpers(path, depth); if (!wh.hasGlob && priorWh) { wh.hasGlob = priorWh.hasGlob; wh.globFilter = priorWh.globFilter; wh.filterPath = (entry) => priorWh.filterPath(entry); wh.filterDir = (entry) => priorWh.filterDir(entry); } try { const stats = await statMethods[wh.statMethod](wh.watchPath); if (this.fsw.closed) return; if (this.fsw._isIgnored(wh.watchPath, stats)) { ready(); return false; } const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START); let closer; if (stats.isDirectory()) { const absPath = sysPath.resolve(path); const targetPath = follow ? await fsrealpath(path) : path; if (this.fsw.closed) return; closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); if (this.fsw.closed) return; if (absPath !== targetPath && targetPath !== void 0) { this.fsw._symlinkPaths.set(absPath, targetPath); } } else if (stats.isSymbolicLink()) { const targetPath = follow ? await fsrealpath(path) : path; if (this.fsw.closed) return; const parent = sysPath.dirname(wh.watchPath); this.fsw._getWatchedDir(parent).add(wh.watchPath); this.fsw._emit(EV_ADD, wh.watchPath, stats); closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); if (this.fsw.closed) return; if (targetPath !== void 0) { this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath); } } else { closer = this._handleFile(wh.watchPath, stats, initialAdd); } ready(); this.fsw._addPathCloser(path, closer); return false; } catch (error48) { if (this.fsw._handleError(error48)) { ready(); return path; } } } }; module2.exports = NodeFsHandler; } }); // node_modules/chokidar/lib/fsevents-handler.js var require_fsevents_handler = __commonJS({ "node_modules/chokidar/lib/fsevents-handler.js"(exports2, module2) { "use strict"; var fs = require("fs"); var sysPath = require("path"); var { promisify } = require("util"); var fsevents; try { fsevents = require("fsevents"); } catch (error48) { if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error48); } if (fsevents) { const mtch = process.version.match(/v(\d+)\.(\d+)/); if (mtch && mtch[1] && mtch[2]) { const maj = Number.parseInt(mtch[1], 10); const min = Number.parseInt(mtch[2], 10); if (maj === 8 && min < 16) { fsevents = void 0; } } } var { EV_ADD, EV_CHANGE, EV_ADD_DIR, EV_UNLINK, EV_ERROR, STR_DATA, STR_END, FSEVENT_CREATED, FSEVENT_MODIFIED, FSEVENT_DELETED, FSEVENT_MOVED, // FSEVENT_CLONED, FSEVENT_UNKNOWN, FSEVENT_FLAG_MUST_SCAN_SUBDIRS, FSEVENT_TYPE_FILE, FSEVENT_TYPE_DIRECTORY, FSEVENT_TYPE_SYMLINK, ROOT_GLOBSTAR, DIR_SUFFIX, DOT_SLASH, FUNCTION_TYPE, EMPTY_FN, IDENTITY_FN } = require_constants9(); var Depth = (value) => isNaN(value) ? {} : { depth: value }; var stat = promisify(fs.stat); var lstat = promisify(fs.lstat); var realpath = promisify(fs.realpath); var statMethods = { stat, lstat }; var FSEventsWatchers = /* @__PURE__ */ new Map(); var consolidateThreshhold = 10; var wrongEventFlags = /* @__PURE__ */ new Set([ 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912 ]); var createFSEventsInstance = (path, callback) => { const stop = fsevents.watch(path, callback); return { stop }; }; function setFSEventsListener(path, realPath, listener, rawEmitter) { let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath; const parentPath = sysPath.dirname(watchPath); let cont = FSEventsWatchers.get(watchPath); if (couldConsolidate(parentPath)) { watchPath = parentPath; } const resolvedPath = sysPath.resolve(path); const hasSymlink = resolvedPath !== realPath; const filteredListener = (fullPath, flags, info) => { if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath); if (fullPath === resolvedPath || !fullPath.indexOf(resolvedPath + sysPath.sep)) listener(fullPath, flags, info); }; let watchedParent = false; for (const watchedPath of FSEventsWatchers.keys()) { if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) { watchPath = watchedPath; cont = FSEventsWatchers.get(watchPath); watchedParent = true; break; } } if (cont || watchedParent) { cont.listeners.add(filteredListener); } else { cont = { listeners: /* @__PURE__ */ new Set([filteredListener]), rawEmitter, watcher: createFSEventsInstance(watchPath, (fullPath, flags) => { if (!cont.listeners.size) return; if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return; const info = fsevents.getInfo(fullPath, flags); cont.listeners.forEach((list) => { list(fullPath, flags, info); }); cont.rawEmitter(info.event, fullPath, info); }) }; FSEventsWatchers.set(watchPath, cont); } return () => { const lst = cont.listeners; lst.delete(filteredListener); if (!lst.size) { FSEventsWatchers.delete(watchPath); if (cont.watcher) return cont.watcher.stop().then(() => { cont.rawEmitter = cont.watcher = void 0; Object.freeze(cont); }); } }; } var couldConsolidate = (path) => { let count = 0; for (const watchPath of FSEventsWatchers.keys()) { if (watchPath.indexOf(path) === 0) { count++; if (count >= consolidateThreshhold) { return true; } } } return false; }; var canUse = () => fsevents && FSEventsWatchers.size < 128; var calcDepth = (path, root) => { let i = 0; while (!path.indexOf(root) && (path = sysPath.dirname(path)) !== root) i++; return i; }; var sameTypes = (info, stats) => info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || info.type === FSEVENT_TYPE_FILE && stats.isFile(); var FsEventsHandler = class { /** * @param {import('../index').FSWatcher} fsw */ constructor(fsw) { this.fsw = fsw; } checkIgnored(path, stats) { const ipaths = this.fsw._ignoredPaths; if (this.fsw._isIgnored(path, stats)) { ipaths.add(path); if (stats && stats.isDirectory()) { ipaths.add(path + ROOT_GLOBSTAR); } return true; } ipaths.delete(path); ipaths.delete(path + ROOT_GLOBSTAR); } addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) { const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD; this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts); } async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) { try { const stats = await stat(path); if (this.fsw.closed) return; if (sameTypes(info, stats)) { this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); } else { this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); } } catch (error48) { if (error48.code === "EACCES") { this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); } else { this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); } } } handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) { if (this.fsw.closed || this.checkIgnored(path)) return; if (event === EV_UNLINK) { const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY; if (isDirectory || watchedDir.has(item)) { this.fsw._remove(parent, item, isDirectory); } } else { if (event === EV_ADD) { if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path); if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) { const curDepth = opts.depth === void 0 ? void 0 : calcDepth(fullPath, realPath) + 1; return this._addToFsEvents(path, false, true, curDepth); } this.fsw._getWatchedDir(parent).add(item); } const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event; this.fsw._emit(eventName, path); if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true); } } /** * Handle symlinks encountered during directory scan * @param {String} watchPath - file/dir path to be watched with fsevents * @param {String} realPath - real path (in case of symlinks) * @param {Function} transform - path transformer * @param {Function} globFilter - path filter in case a glob pattern was provided * @returns {Function} closer for the watcher instance */ _watchWithFsEvents(watchPath, realPath, transform2, globFilter) { if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return; const opts = this.fsw.options; const watchCallback = async (fullPath, flags, info) => { if (this.fsw.closed) return; if (opts.depth !== void 0 && calcDepth(fullPath, realPath) > opts.depth) return; const path = transform2(sysPath.join( watchPath, sysPath.relative(watchPath, fullPath) )); if (globFilter && !globFilter(path)) return; const parent = sysPath.dirname(path); const item = sysPath.basename(path); const watchedDir = this.fsw._getWatchedDir( info.type === FSEVENT_TYPE_DIRECTORY ? path : parent ); if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) { if (typeof opts.ignored === FUNCTION_TYPE) { let stats; try { stats = await stat(path); } catch (error48) { } if (this.fsw.closed) return; if (this.checkIgnored(path, stats)) return; if (sameTypes(info, stats)) { this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); } else { this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts); } } else { this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); } } else { switch (info.event) { case FSEVENT_CREATED: case FSEVENT_MODIFIED: return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts); case FSEVENT_DELETED: case FSEVENT_MOVED: return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts); } } }; const closer = setFSEventsListener( watchPath, realPath, watchCallback, this.fsw._emitRaw ); this.fsw._emitReady(); return closer; } /** * Handle symlinks encountered during directory scan * @param {String} linkPath path to symlink * @param {String} fullPath absolute path to the symlink * @param {Function} transform pre-existing path transformer * @param {Number} curDepth level of subdirectories traversed to where symlink is * @returns {Promise} */ async _handleFsEventsSymlink(linkPath, fullPath, transform2, curDepth) { if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return; this.fsw._symlinkPaths.set(fullPath, true); this.fsw._incrReadyCount(); try { const linkTarget = await realpath(linkPath); if (this.fsw.closed) return; if (this.fsw._isIgnored(linkTarget)) { return this.fsw._emitReady(); } this.fsw._incrReadyCount(); this._addToFsEvents(linkTarget || linkPath, (path) => { let aliasedPath = linkPath; if (linkTarget && linkTarget !== DOT_SLASH) { aliasedPath = path.replace(linkTarget, linkPath); } else if (path !== DOT_SLASH) { aliasedPath = sysPath.join(linkPath, path); } return transform2(aliasedPath); }, false, curDepth); } catch (error48) { if (this.fsw._handleError(error48)) { return this.fsw._emitReady(); } } } /** * * @param {Path} newPath * @param {fs.Stats} stats */ emitAdd(newPath, stats, processPath, opts, forceAdd) { const pp = processPath(newPath); const isDir = stats.isDirectory(); const dirObj = this.fsw._getWatchedDir(sysPath.dirname(pp)); const base = sysPath.basename(pp); if (isDir) this.fsw._getWatchedDir(pp); if (dirObj.has(base)) return; dirObj.add(base); if (!opts.ignoreInitial || forceAdd === true) { this.fsw._emit(isDir ? EV_ADD_DIR : EV_ADD, pp, stats); } } initWatch(realPath, path, wh, processPath) { if (this.fsw.closed) return; const closer = this._watchWithFsEvents( wh.watchPath, sysPath.resolve(realPath || wh.watchPath), processPath, wh.globFilter ); this.fsw._addPathCloser(path, closer); } /** * Handle added path with fsevents * @param {String} path file/dir path or glob pattern * @param {Function|Boolean=} transform converts working path to what the user expects * @param {Boolean=} forceAdd ensure add is emitted * @param {Number=} priorDepth Level of subdirectories already traversed. * @returns {Promise} */ async _addToFsEvents(path, transform2, forceAdd, priorDepth) { if (this.fsw.closed) { return; } const opts = this.fsw.options; const processPath = typeof transform2 === FUNCTION_TYPE ? transform2 : IDENTITY_FN; const wh = this.fsw._getWatchHelpers(path); try { const stats = await statMethods[wh.statMethod](wh.watchPath); if (this.fsw.closed) return; if (this.fsw._isIgnored(wh.watchPath, stats)) { throw null; } if (stats.isDirectory()) { if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd); if (priorDepth && priorDepth > opts.depth) return; this.fsw._readdirp(wh.watchPath, { fileFilter: (entry) => wh.filterPath(entry), directoryFilter: (entry) => wh.filterDir(entry), ...Depth(opts.depth - (priorDepth || 0)) }).on(STR_DATA, (entry) => { if (this.fsw.closed) { return; } if (entry.stats.isDirectory() && !wh.filterPath(entry)) return; const joinedPath = sysPath.join(wh.watchPath, entry.path); const { fullPath } = entry; if (wh.followSymlinks && entry.stats.isSymbolicLink()) { const curDepth = opts.depth === void 0 ? void 0 : calcDepth(joinedPath, sysPath.resolve(wh.watchPath)) + 1; this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth); } else { this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd); } }).on(EV_ERROR, EMPTY_FN).on(STR_END, () => { this.fsw._emitReady(); }); } else { this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd); this.fsw._emitReady(); } } catch (error48) { if (!error48 || this.fsw._handleError(error48)) { this.fsw._emitReady(); this.fsw._emitReady(); } } if (opts.persistent && forceAdd !== true) { if (typeof transform2 === FUNCTION_TYPE) { this.initWatch(void 0, path, wh, processPath); } else { let realPath; try { realPath = await realpath(wh.watchPath); } catch (e) { } this.initWatch(realPath, path, wh, processPath); } } } }; module2.exports = FsEventsHandler; module2.exports.canUse = canUse; } }); // node_modules/chokidar/index.js var require_chokidar = __commonJS({ "node_modules/chokidar/index.js"(exports2) { "use strict"; var { EventEmitter } = require("events"); var fs = require("fs"); var sysPath = require("path"); var { promisify } = require("util"); var readdirp = require_readdirp(); var anymatch = require_anymatch().default; var globParent = require_glob_parent(); var isGlob = require_is_glob(); var braces = require_braces(); var normalizePath = require_normalize_path(); var NodeFsHandler = require_nodefs_handler(); var FsEventsHandler = require_fsevents_handler(); var { EV_ALL, EV_READY, EV_ADD, EV_CHANGE, EV_UNLINK, EV_ADD_DIR, EV_UNLINK_DIR, EV_RAW, EV_ERROR, STR_CLOSE, STR_END, BACK_SLASH_RE, DOUBLE_SLASH_RE, SLASH_OR_BACK_SLASH_RE, DOT_RE, REPLACER_RE, SLASH, SLASH_SLASH, BRACE_START, BANG, ONE_DOT, TWO_DOTS, GLOBSTAR, SLASH_GLOBSTAR, ANYMATCH_OPTS, STRING_TYPE, FUNCTION_TYPE, EMPTY_STR, EMPTY_FN, isWindows, isMacos, isIBMi } = require_constants9(); var stat = promisify(fs.stat); var readdir = promisify(fs.readdir); var arrify = (value = []) => Array.isArray(value) ? value : [value]; var flatten = (list, result = []) => { list.forEach((item) => { if (Array.isArray(item)) { flatten(item, result); } else { result.push(item); } }); return result; }; var unifyPaths = (paths_) => { const paths = flatten(arrify(paths_)); if (!paths.every((p) => typeof p === STRING_TYPE)) { throw new TypeError(`Non-string provided as watch path: ${paths}`); } return paths.map(normalizePathToUnix); }; var toUnix = (string4) => { let str = string4.replace(BACK_SLASH_RE, SLASH); let prepend = false; if (str.startsWith(SLASH_SLASH)) { prepend = true; } while (str.match(DOUBLE_SLASH_RE)) { str = str.replace(DOUBLE_SLASH_RE, SLASH); } if (prepend) { str = SLASH + str; } return str; }; var normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path))); var normalizeIgnored = (cwd = EMPTY_STR) => (path) => { if (typeof path !== STRING_TYPE) return path; return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path)); }; var getAbsolutePath = (path, cwd) => { if (sysPath.isAbsolute(path)) { return path; } if (path.startsWith(BANG)) { return BANG + sysPath.join(cwd, path.slice(1)); } return sysPath.join(cwd, path); }; var undef = (opts, key) => opts[key] === void 0; var DirEntry = class { /** * @param {Path} dir * @param {Function} removeWatcher */ constructor(dir, removeWatcher) { this.path = dir; this._removeWatcher = removeWatcher; this.items = /* @__PURE__ */ new Set(); } add(item) { const { items } = this; if (!items) return; if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item); } async remove(item) { const { items } = this; if (!items) return; items.delete(item); if (items.size > 0) return; const dir = this.path; try { await readdir(dir); } catch (err) { if (this._removeWatcher) { this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); } } } has(item) { const { items } = this; if (!items) return; return items.has(item); } /** * @returns {Array} */ getChildren() { const { items } = this; if (!items) return; return [...items.values()]; } dispose() { this.items.clear(); delete this.path; delete this._removeWatcher; delete this.items; Object.freeze(this); } }; var STAT_METHOD_F = "stat"; var STAT_METHOD_L = "lstat"; var WatchHelper = class { constructor(path, watchPath, follow, fsw) { this.fsw = fsw; this.path = path = path.replace(REPLACER_RE, EMPTY_STR); this.watchPath = watchPath; this.fullWatchPath = sysPath.resolve(watchPath); this.hasGlob = watchPath !== path; if (path === EMPTY_STR) this.hasGlob = false; this.globSymlink = this.hasGlob && follow ? void 0 : false; this.globFilter = this.hasGlob ? anymatch(path, void 0, ANYMATCH_OPTS) : false; this.dirParts = this.getDirParts(path); this.dirParts.forEach((parts) => { if (parts.length > 1) parts.pop(); }); this.followSymlinks = follow; this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; } checkGlobSymlink(entry) { if (this.globSymlink === void 0) { this.globSymlink = entry.fullParentDir === this.fullWatchPath ? false : { realPath: entry.fullParentDir, linkPath: this.fullWatchPath }; } if (this.globSymlink) { return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath); } return entry.fullPath; } entryPath(entry) { return sysPath.join( this.watchPath, sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)) ); } filterPath(entry) { const { stats } = entry; if (stats && stats.isSymbolicLink()) return this.filterDir(entry); const resolvedPath = this.entryPath(entry); const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? this.globFilter(resolvedPath) : true; return matchesGlob && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats); } getDirParts(path) { if (!this.hasGlob) return []; const parts = []; const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path]; expandedPath.forEach((path2) => { parts.push(sysPath.relative(this.watchPath, path2).split(SLASH_OR_BACK_SLASH_RE)); }); return parts; } filterDir(entry) { if (this.hasGlob) { const entryParts = this.getDirParts(this.checkGlobSymlink(entry)); let globstar = false; this.unmatchedGlob = !this.dirParts.some((parts) => { return parts.every((part, i) => { if (part === GLOBSTAR) globstar = true; return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS); }); }); } return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats); } }; var FSWatcher = class extends EventEmitter { // Not indenting methods for history sake; for now. constructor(_opts) { super(); const opts = {}; if (_opts) Object.assign(opts, _opts); this._watched = /* @__PURE__ */ new Map(); this._closers = /* @__PURE__ */ new Map(); this._ignoredPaths = /* @__PURE__ */ new Set(); this._throttled = /* @__PURE__ */ new Map(); this._symlinkPaths = /* @__PURE__ */ new Map(); this._streams = /* @__PURE__ */ new Set(); this.closed = false; if (undef(opts, "persistent")) opts.persistent = true; if (undef(opts, "ignoreInitial")) opts.ignoreInitial = false; if (undef(opts, "ignorePermissionErrors")) opts.ignorePermissionErrors = false; if (undef(opts, "interval")) opts.interval = 100; if (undef(opts, "binaryInterval")) opts.binaryInterval = 300; if (undef(opts, "disableGlobbing")) opts.disableGlobbing = false; opts.enableBinaryInterval = opts.binaryInterval !== opts.interval; if (undef(opts, "useFsEvents")) opts.useFsEvents = !opts.usePolling; const canUseFsEvents = FsEventsHandler.canUse(); if (!canUseFsEvents) opts.useFsEvents = false; if (undef(opts, "usePolling") && !opts.useFsEvents) { opts.usePolling = isMacos; } if (isIBMi) { opts.usePolling = true; } const envPoll = process.env.CHOKIDAR_USEPOLLING; if (envPoll !== void 0) { const envLower = envPoll.toLowerCase(); if (envLower === "false" || envLower === "0") { opts.usePolling = false; } else if (envLower === "true" || envLower === "1") { opts.usePolling = true; } else { opts.usePolling = !!envLower; } } const envInterval = process.env.CHOKIDAR_INTERVAL; if (envInterval) { opts.interval = Number.parseInt(envInterval, 10); } if (undef(opts, "atomic")) opts.atomic = !opts.usePolling && !opts.useFsEvents; if (opts.atomic) this._pendingUnlinks = /* @__PURE__ */ new Map(); if (undef(opts, "followSymlinks")) opts.followSymlinks = true; if (undef(opts, "awaitWriteFinish")) opts.awaitWriteFinish = false; if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {}; const awf = opts.awaitWriteFinish; if (awf) { if (!awf.stabilityThreshold) awf.stabilityThreshold = 2e3; if (!awf.pollInterval) awf.pollInterval = 100; this._pendingWrites = /* @__PURE__ */ new Map(); } if (opts.ignored) opts.ignored = arrify(opts.ignored); let readyCalls = 0; this._emitReady = () => { readyCalls++; if (readyCalls >= this._readyCount) { this._emitReady = EMPTY_FN; this._readyEmitted = true; process.nextTick(() => this.emit(EV_READY)); } }; this._emitRaw = (...args) => this.emit(EV_RAW, ...args); this._readyEmitted = false; this.options = opts; if (opts.useFsEvents) { this._fsEventsHandler = new FsEventsHandler(this); } else { this._nodeFsHandler = new NodeFsHandler(this); } Object.freeze(opts); } // Public methods /** * Adds paths to be watched on an existing FSWatcher instance * @param {Path|Array} paths_ * @param {String=} _origAdd private; for handling non-existent paths to be watched * @param {Boolean=} _internal private; indicates a non-user add * @returns {FSWatcher} for chaining */ add(paths_, _origAdd, _internal) { const { cwd, disableGlobbing } = this.options; this.closed = false; let paths = unifyPaths(paths_); if (cwd) { paths = paths.map((path) => { const absPath = getAbsolutePath(path, cwd); if (disableGlobbing || !isGlob(path)) { return absPath; } return normalizePath(absPath); }); } paths = paths.filter((path) => { if (path.startsWith(BANG)) { this._ignoredPaths.add(path.slice(1)); return false; } this._ignoredPaths.delete(path); this._ignoredPaths.delete(path + SLASH_GLOBSTAR); this._userIgnored = void 0; return true; }); if (this.options.useFsEvents && this._fsEventsHandler) { if (!this._readyCount) this._readyCount = paths.length; if (this.options.persistent) this._readyCount += paths.length; paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path)); } else { if (!this._readyCount) this._readyCount = 0; this._readyCount += paths.length; Promise.all( paths.map(async (path) => { const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd); if (res) this._emitReady(); return res; }) ).then((results) => { if (this.closed) return; results.filter((item) => item).forEach((item) => { this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); }); }); } return this; } /** * Close watchers or start ignoring events from specified paths. * @param {Path|Array} paths_ - string or array of strings, file/directory paths and/or globs * @returns {FSWatcher} for chaining */ unwatch(paths_) { if (this.closed) return this; const paths = unifyPaths(paths_); const { cwd } = this.options; paths.forEach((path) => { if (!sysPath.isAbsolute(path) && !this._closers.has(path)) { if (cwd) path = sysPath.join(cwd, path); path = sysPath.resolve(path); } this._closePath(path); this._ignoredPaths.add(path); if (this._watched.has(path)) { this._ignoredPaths.add(path + SLASH_GLOBSTAR); } this._userIgnored = void 0; }); return this; } /** * Close watchers and remove all listeners from watched paths. * @returns {Promise}. */ close() { if (this.closed) return this._closePromise; this.closed = true; this.removeAllListeners(); const closers = []; this._closers.forEach((closerList) => closerList.forEach((closer) => { const promise2 = closer(); if (promise2 instanceof Promise) closers.push(promise2); })); this._streams.forEach((stream) => stream.destroy()); this._userIgnored = void 0; this._readyCount = 0; this._readyEmitted = false; this._watched.forEach((dirent) => dirent.dispose()); ["closers", "watched", "streams", "symlinkPaths", "throttled"].forEach((key) => { this[`_${key}`].clear(); }); this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve(); return this._closePromise; } /** * Expose list of watched paths * @returns {Object} for chaining */ getWatched() { const watchList = {}; this._watched.forEach((entry, dir) => { const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir; watchList[key || ONE_DOT] = entry.getChildren().sort(); }); return watchList; } emitWithAll(event, args) { this.emit(...args); if (event !== EV_ERROR) this.emit(EV_ALL, ...args); } // Common helpers // -------------- /** * Normalize and emit events. * Calling _emit DOES NOT MEAN emit() would be called! * @param {EventName} event Type of event * @param {Path} path File or directory path * @param {*=} val1 arguments to be passed with event * @param {*=} val2 * @param {*=} val3 * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag */ async _emit(event, path, val1, val2, val3) { if (this.closed) return; const opts = this.options; if (isWindows) path = sysPath.normalize(path); if (opts.cwd) path = sysPath.relative(opts.cwd, path); const args = [event, path]; if (val3 !== void 0) args.push(val1, val2, val3); else if (val2 !== void 0) args.push(val1, val2); else if (val1 !== void 0) args.push(val1); const awf = opts.awaitWriteFinish; let pw; if (awf && (pw = this._pendingWrites.get(path))) { pw.lastChange = /* @__PURE__ */ new Date(); return this; } if (opts.atomic) { if (event === EV_UNLINK) { this._pendingUnlinks.set(path, args); setTimeout(() => { this._pendingUnlinks.forEach((entry, path2) => { this.emit(...entry); this.emit(EV_ALL, ...entry); this._pendingUnlinks.delete(path2); }); }, typeof opts.atomic === "number" ? opts.atomic : 100); return this; } if (event === EV_ADD && this._pendingUnlinks.has(path)) { event = args[0] = EV_CHANGE; this._pendingUnlinks.delete(path); } } if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) { const awfEmit = (err, stats) => { if (err) { event = args[0] = EV_ERROR; args[1] = err; this.emitWithAll(event, args); } else if (stats) { if (args.length > 2) { args[2] = stats; } else { args.push(stats); } this.emitWithAll(event, args); } }; this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); return this; } if (event === EV_CHANGE) { const isThrottled = !this._throttle(EV_CHANGE, path, 50); if (isThrottled) return this; } if (opts.alwaysStat && val1 === void 0 && (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)) { const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path; let stats; try { stats = await stat(fullPath); } catch (err) { } if (!stats || this.closed) return; args.push(stats); } this.emitWithAll(event, args); return this; } /** * Common handler for errors * @param {Error} error * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag */ _handleError(error48) { const code = error48 && error48.code; if (error48 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) { this.emit(EV_ERROR, error48); } return error48 || this.closed; } /** * Helper utility for throttling * @param {ThrottleType} actionType type being throttled * @param {Path} path being acted upon * @param {Number} timeout duration of time to suppress duplicate actions * @returns {Object|false} tracking object or false if action should be suppressed */ _throttle(actionType, path, timeout) { if (!this._throttled.has(actionType)) { this._throttled.set(actionType, /* @__PURE__ */ new Map()); } const action = this._throttled.get(actionType); const actionPath = action.get(path); if (actionPath) { actionPath.count++; return false; } let timeoutObject; const clear = () => { const item = action.get(path); const count = item ? item.count : 0; action.delete(path); clearTimeout(timeoutObject); if (item) clearTimeout(item.timeoutObject); return count; }; timeoutObject = setTimeout(clear, timeout); const thr = { timeoutObject, clear, count: 0 }; action.set(path, thr); return thr; } _incrReadyCount() { return this._readyCount++; } /** * Awaits write operation to finish. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. * @param {Path} path being acted upon * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished * @param {EventName} event * @param {Function} awfEmit Callback to be called when ready for event to be emitted. */ _awaitWriteFinish(path, threshold, event, awfEmit) { let timeoutHandler; let fullPath = path; if (this.options.cwd && !sysPath.isAbsolute(path)) { fullPath = sysPath.join(this.options.cwd, path); } const now = /* @__PURE__ */ new Date(); const awaitWriteFinish = (prevStat) => { fs.stat(fullPath, (err, curStat) => { if (err || !this._pendingWrites.has(path)) { if (err && err.code !== "ENOENT") awfEmit(err); return; } const now2 = Number(/* @__PURE__ */ new Date()); if (prevStat && curStat.size !== prevStat.size) { this._pendingWrites.get(path).lastChange = now2; } const pw = this._pendingWrites.get(path); const df = now2 - pw.lastChange; if (df >= threshold) { this._pendingWrites.delete(path); awfEmit(void 0, curStat); } else { timeoutHandler = setTimeout( awaitWriteFinish, this.options.awaitWriteFinish.pollInterval, curStat ); } }); }; if (!this._pendingWrites.has(path)) { this._pendingWrites.set(path, { lastChange: now, cancelWait: () => { this._pendingWrites.delete(path); clearTimeout(timeoutHandler); return event; } }); timeoutHandler = setTimeout( awaitWriteFinish, this.options.awaitWriteFinish.pollInterval ); } } _getGlobIgnored() { return [...this._ignoredPaths.values()]; } /** * Determines whether user has asked to ignore this path. * @param {Path} path filepath or dir * @param {fs.Stats=} stats result of fs.stat * @returns {Boolean} */ _isIgnored(path, stats) { if (this.options.atomic && DOT_RE.test(path)) return true; if (!this._userIgnored) { const { cwd } = this.options; const ign = this.options.ignored; const ignored = ign && ign.map(normalizeIgnored(cwd)); const paths = arrify(ignored).filter((path2) => typeof path2 === STRING_TYPE && !isGlob(path2)).map((path2) => path2 + SLASH_GLOBSTAR); const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths); this._userIgnored = anymatch(list, void 0, ANYMATCH_OPTS); } return this._userIgnored([path, stats]); } _isntIgnored(path, stat2) { return !this._isIgnored(path, stat2); } /** * Provides a set of common helpers and properties relating to symlink and glob handling. * @param {Path} path file, directory, or glob pattern being watched * @param {Number=} depth at any depth > 0, this isn't a glob * @returns {WatchHelper} object containing helpers for this path */ _getWatchHelpers(path, depth) { const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path); const follow = this.options.followSymlinks; return new WatchHelper(path, watchPath, follow, this); } // Directory helpers // ----------------- /** * Provides directory tracking objects * @param {String} directory path of the directory * @returns {DirEntry} the directory's tracking object */ _getWatchedDir(directory) { if (!this._boundRemove) this._boundRemove = this._remove.bind(this); const dir = sysPath.resolve(directory); if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove)); return this._watched.get(dir); } // File helpers // ------------ /** * Check for read permissions. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405 * @param {fs.Stats} stats - object, result of fs_stat * @returns {Boolean} indicates whether the file can be read */ _hasReadPermissions(stats) { if (this.options.ignorePermissionErrors) return true; const md = stats && Number.parseInt(stats.mode, 10); const st = md & 511; const it = Number.parseInt(st.toString(8)[0], 10); return Boolean(4 & it); } /** * Handles emitting unlink events for * files and directories, and via recursion, for * files and directories within directories that are unlinked * @param {String} directory within which the following item is located * @param {String} item base path of item/directory * @returns {void} */ _remove(directory, item, isDirectory) { const path = sysPath.join(directory, item); const fullPath = sysPath.resolve(path); isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath); if (!this._throttle("remove", path, 100)) return; if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) { this.add(directory, item, true); } const wp = this._getWatchedDir(path); const nestedDirectoryChildren = wp.getChildren(); nestedDirectoryChildren.forEach((nested) => this._remove(path, nested)); const parent = this._getWatchedDir(directory); const wasTracked = parent.has(item); parent.remove(item); if (this._symlinkPaths.has(fullPath)) { this._symlinkPaths.delete(fullPath); } let relPath = path; if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path); if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { const event = this._pendingWrites.get(relPath).cancelWait(); if (event === EV_ADD) return; } this._watched.delete(path); this._watched.delete(fullPath); const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK; if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path); if (!this.options.useFsEvents) { this._closePath(path); } } /** * Closes all watchers for a path * @param {Path} path */ _closePath(path) { this._closeFile(path); const dir = sysPath.dirname(path); this._getWatchedDir(dir).remove(sysPath.basename(path)); } /** * Closes only file-specific watchers * @param {Path} path */ _closeFile(path) { const closers = this._closers.get(path); if (!closers) return; closers.forEach((closer) => closer()); this._closers.delete(path); } /** * * @param {Path} path * @param {Function} closer */ _addPathCloser(path, closer) { if (!closer) return; let list = this._closers.get(path); if (!list) { list = []; this._closers.set(path, list); } list.push(closer); } _readdirp(root, opts) { if (this.closed) return; const options = { type: EV_ALL, alwaysStat: true, lstat: true, ...opts }; let stream = readdirp(root, options); this._streams.add(stream); stream.once(STR_CLOSE, () => { stream = void 0; }); stream.once(STR_END, () => { if (stream) { this._streams.delete(stream); stream = void 0; } }); return stream; } }; exports2.FSWatcher = FSWatcher; var watch = (paths, options) => { const watcher = new FSWatcher(options); watcher.add(paths); return watcher; }; exports2.watch = watch; } }); // node_modules/buffer-crc32/index.js var require_buffer_crc32 = __commonJS({ "node_modules/buffer-crc32/index.js"(exports2, module2) { var Buffer2 = require("buffer").Buffer; var CRC_TABLE = [ 0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117 ]; if (typeof Int32Array !== "undefined") { CRC_TABLE = new Int32Array(CRC_TABLE); } function ensureBuffer(input) { if (Buffer2.isBuffer(input)) { return input; } var hasNewBufferAPI = typeof Buffer2.alloc === "function" && typeof Buffer2.from === "function"; if (typeof input === "number") { return hasNewBufferAPI ? Buffer2.alloc(input) : new Buffer2(input); } else if (typeof input === "string") { return hasNewBufferAPI ? Buffer2.from(input) : new Buffer2(input); } else { throw new Error("input must be buffer, number, or string, received " + typeof input); } } function bufferizeInt(num) { var tmp = ensureBuffer(4); tmp.writeInt32BE(num, 0); return tmp; } function _crc32(buf, previous) { buf = ensureBuffer(buf); if (Buffer2.isBuffer(previous)) { previous = previous.readUInt32BE(0); } var crc = ~~previous ^ -1; for (var n = 0; n < buf.length; n++) { crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8; } return crc ^ -1; } function crc32() { return bufferizeInt(_crc32.apply(null, arguments)); } crc32.signed = function() { return _crc32.apply(null, arguments); }; crc32.unsigned = function() { return _crc32.apply(null, arguments) >>> 0; }; module2.exports = crc32; } }); // node_modules/yazl/index.js var require_yazl = __commonJS({ "node_modules/yazl/index.js"(exports2) { var fs = require("fs"); var Transform = require("stream").Transform; var PassThrough2 = require("stream").PassThrough; var zlib = require("zlib"); var util2 = require("util"); var EventEmitter = require("events").EventEmitter; var crc32 = require_buffer_crc32(); exports2.ZipFile = ZipFile; exports2.dateToDosDateTime = dateToDosDateTime; util2.inherits(ZipFile, EventEmitter); function ZipFile() { this.outputStream = new PassThrough2(); this.entries = []; this.outputStreamCursor = 0; this.ended = false; this.allDone = false; this.forceZip64Eocd = false; } ZipFile.prototype.addFile = function(realPath, metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, false); if (options == null) options = {}; var entry = new Entry(metadataPath, false, options); self.entries.push(entry); fs.stat(realPath, function(err, stats) { if (err) return self.emit("error", err); if (!stats.isFile()) return self.emit("error", new Error("not a file: " + realPath)); entry.uncompressedSize = stats.size; if (options.mtime == null) entry.setLastModDate(stats.mtime); if (options.mode == null) entry.setFileAttributesMode(stats.mode); entry.setFileDataPumpFunction(function() { var readStream = fs.createReadStream(realPath); entry.state = Entry.FILE_DATA_IN_PROGRESS; readStream.on("error", function(err2) { self.emit("error", err2); }); pumpFileDataReadStream(self, entry, readStream); }); pumpEntries(self); }); }; ZipFile.prototype.addReadStream = function(readStream, metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, false); if (options == null) options = {}; var entry = new Entry(metadataPath, false, options); self.entries.push(entry); entry.setFileDataPumpFunction(function() { entry.state = Entry.FILE_DATA_IN_PROGRESS; pumpFileDataReadStream(self, entry, readStream); }); pumpEntries(self); }; ZipFile.prototype.addBuffer = function(buffer, metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, false); if (buffer.length > 1073741823) throw new Error("buffer too large: " + buffer.length + " > 1073741823"); if (options == null) options = {}; if (options.size != null) throw new Error("options.size not allowed"); var entry = new Entry(metadataPath, false, options); entry.uncompressedSize = buffer.length; entry.crc32 = crc32.unsigned(buffer); entry.crcAndFileSizeKnown = true; self.entries.push(entry); if (!entry.compress) { setCompressedBuffer(buffer); } else { zlib.deflateRaw(buffer, function(err, compressedBuffer) { setCompressedBuffer(compressedBuffer); }); } function setCompressedBuffer(compressedBuffer) { entry.compressedSize = compressedBuffer.length; entry.setFileDataPumpFunction(function() { writeToOutputStream(self, compressedBuffer); writeToOutputStream(self, entry.getDataDescriptor()); entry.state = Entry.FILE_DATA_DONE; setImmediate(function() { pumpEntries(self); }); }); pumpEntries(self); } }; ZipFile.prototype.addEmptyDirectory = function(metadataPath, options) { var self = this; metadataPath = validateMetadataPath(metadataPath, true); if (options == null) options = {}; if (options.size != null) throw new Error("options.size not allowed"); if (options.compress != null) throw new Error("options.compress not allowed"); var entry = new Entry(metadataPath, true, options); self.entries.push(entry); entry.setFileDataPumpFunction(function() { writeToOutputStream(self, entry.getDataDescriptor()); entry.state = Entry.FILE_DATA_DONE; pumpEntries(self); }); pumpEntries(self); }; var eocdrSignatureBuffer = bufferFrom([80, 75, 5, 6]); ZipFile.prototype.end = function(options, finalSizeCallback) { if (typeof options === "function") { finalSizeCallback = options; options = null; } if (options == null) options = {}; if (this.ended) return; this.ended = true; this.finalSizeCallback = finalSizeCallback; this.forceZip64Eocd = !!options.forceZip64Format; if (options.comment) { if (typeof options.comment === "string") { this.comment = encodeCp437(options.comment); } else { this.comment = options.comment; } if (this.comment.length > 65535) throw new Error("comment is too large"); if (bufferIncludes(this.comment, eocdrSignatureBuffer)) throw new Error("comment contains end of central directory record signature"); } else { this.comment = EMPTY_BUFFER; } pumpEntries(this); }; function writeToOutputStream(self, buffer) { self.outputStream.write(buffer); self.outputStreamCursor += buffer.length; } function pumpFileDataReadStream(self, entry, readStream) { var crc32Watcher = new Crc32Watcher(); var uncompressedSizeCounter = new ByteCounter(); var compressor = entry.compress ? new zlib.DeflateRaw() : new PassThrough2(); var compressedSizeCounter = new ByteCounter(); readStream.pipe(crc32Watcher).pipe(uncompressedSizeCounter).pipe(compressor).pipe(compressedSizeCounter).pipe(self.outputStream, { end: false }); compressedSizeCounter.on("end", function() { entry.crc32 = crc32Watcher.crc32; if (entry.uncompressedSize == null) { entry.uncompressedSize = uncompressedSizeCounter.byteCount; } else { if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self.emit("error", new Error("file data stream has unexpected number of bytes")); } entry.compressedSize = compressedSizeCounter.byteCount; self.outputStreamCursor += entry.compressedSize; writeToOutputStream(self, entry.getDataDescriptor()); entry.state = Entry.FILE_DATA_DONE; pumpEntries(self); }); } function pumpEntries(self) { if (self.allDone) return; if (self.ended && self.finalSizeCallback != null) { var finalSize = calculateFinalSize(self); if (finalSize != null) { self.finalSizeCallback(finalSize); self.finalSizeCallback = null; } } var entry = getFirstNotDoneEntry(); function getFirstNotDoneEntry() { for (var i = 0; i < self.entries.length; i++) { var entry2 = self.entries[i]; if (entry2.state < Entry.FILE_DATA_DONE) return entry2; } return null; } if (entry != null) { if (entry.state < Entry.READY_TO_PUMP_FILE_DATA) return; if (entry.state === Entry.FILE_DATA_IN_PROGRESS) return; entry.relativeOffsetOfLocalHeader = self.outputStreamCursor; var localFileHeader = entry.getLocalFileHeader(); writeToOutputStream(self, localFileHeader); entry.doFileDataPump(); } else { if (self.ended) { self.offsetOfStartOfCentralDirectory = self.outputStreamCursor; self.entries.forEach(function(entry2) { var centralDirectoryRecord = entry2.getCentralDirectoryRecord(); writeToOutputStream(self, centralDirectoryRecord); }); writeToOutputStream(self, getEndOfCentralDirectoryRecord(self)); self.outputStream.end(); self.allDone = true; } } } function calculateFinalSize(self) { var pretendOutputCursor = 0; var centralDirectorySize = 0; for (var i = 0; i < self.entries.length; i++) { var entry = self.entries[i]; if (entry.compress) return -1; if (entry.state >= Entry.READY_TO_PUMP_FILE_DATA) { if (entry.uncompressedSize == null) return -1; } else { if (entry.uncompressedSize == null) return null; } entry.relativeOffsetOfLocalHeader = pretendOutputCursor; var useZip64Format = entry.useZip64Format(); pretendOutputCursor += LOCAL_FILE_HEADER_FIXED_SIZE + entry.utf8FileName.length; pretendOutputCursor += entry.uncompressedSize; if (!entry.crcAndFileSizeKnown) { if (useZip64Format) { pretendOutputCursor += ZIP64_DATA_DESCRIPTOR_SIZE; } else { pretendOutputCursor += DATA_DESCRIPTOR_SIZE; } } centralDirectorySize += CENTRAL_DIRECTORY_RECORD_FIXED_SIZE + entry.utf8FileName.length + entry.fileComment.length; if (useZip64Format) { centralDirectorySize += ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE; } } var endOfCentralDirectorySize = 0; if (self.forceZip64Eocd || self.entries.length >= 65535 || centralDirectorySize >= 65535 || pretendOutputCursor >= 4294967295) { endOfCentralDirectorySize += ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE; } endOfCentralDirectorySize += END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length; return pretendOutputCursor + centralDirectorySize + endOfCentralDirectorySize; } var ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 56; var ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE = 20; var END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 22; function getEndOfCentralDirectoryRecord(self, actuallyJustTellMeHowLongItWouldBe) { var needZip64Format = false; var normalEntriesLength = self.entries.length; if (self.forceZip64Eocd || self.entries.length >= 65535) { normalEntriesLength = 65535; needZip64Format = true; } var sizeOfCentralDirectory = self.outputStreamCursor - self.offsetOfStartOfCentralDirectory; var normalSizeOfCentralDirectory = sizeOfCentralDirectory; if (self.forceZip64Eocd || sizeOfCentralDirectory >= 4294967295) { normalSizeOfCentralDirectory = 4294967295; needZip64Format = true; } var normalOffsetOfStartOfCentralDirectory = self.offsetOfStartOfCentralDirectory; if (self.forceZip64Eocd || self.offsetOfStartOfCentralDirectory >= 4294967295) { normalOffsetOfStartOfCentralDirectory = 4294967295; needZip64Format = true; } if (actuallyJustTellMeHowLongItWouldBe) { if (needZip64Format) { return ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE + END_OF_CENTRAL_DIRECTORY_RECORD_SIZE; } else { return END_OF_CENTRAL_DIRECTORY_RECORD_SIZE; } } var eocdrBuffer = bufferAlloc(END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length); eocdrBuffer.writeUInt32LE(101010256, 0); eocdrBuffer.writeUInt16LE(0, 4); eocdrBuffer.writeUInt16LE(0, 6); eocdrBuffer.writeUInt16LE(normalEntriesLength, 8); eocdrBuffer.writeUInt16LE(normalEntriesLength, 10); eocdrBuffer.writeUInt32LE(normalSizeOfCentralDirectory, 12); eocdrBuffer.writeUInt32LE(normalOffsetOfStartOfCentralDirectory, 16); eocdrBuffer.writeUInt16LE(self.comment.length, 20); self.comment.copy(eocdrBuffer, 22); if (!needZip64Format) return eocdrBuffer; var zip64EocdrBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE); zip64EocdrBuffer.writeUInt32LE(101075792, 0); writeUInt64LE(zip64EocdrBuffer, ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE - 12, 4); zip64EocdrBuffer.writeUInt16LE(VERSION_MADE_BY, 12); zip64EocdrBuffer.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_ZIP64, 14); zip64EocdrBuffer.writeUInt32LE(0, 16); zip64EocdrBuffer.writeUInt32LE(0, 20); writeUInt64LE(zip64EocdrBuffer, self.entries.length, 24); writeUInt64LE(zip64EocdrBuffer, self.entries.length, 32); writeUInt64LE(zip64EocdrBuffer, sizeOfCentralDirectory, 40); writeUInt64LE(zip64EocdrBuffer, self.offsetOfStartOfCentralDirectory, 48); var zip64EocdlBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE); zip64EocdlBuffer.writeUInt32LE(117853008, 0); zip64EocdlBuffer.writeUInt32LE(0, 4); writeUInt64LE(zip64EocdlBuffer, self.outputStreamCursor, 8); zip64EocdlBuffer.writeUInt32LE(1, 16); return Buffer.concat([ zip64EocdrBuffer, zip64EocdlBuffer, eocdrBuffer ]); } function validateMetadataPath(metadataPath, isDirectory) { if (metadataPath === "") throw new Error("empty metadataPath"); metadataPath = metadataPath.replace(/\\/g, "/"); if (/^[a-zA-Z]:/.test(metadataPath) || /^\//.test(metadataPath)) throw new Error("absolute path: " + metadataPath); if (metadataPath.split("/").indexOf("..") !== -1) throw new Error("invalid relative path: " + metadataPath); var looksLikeDirectory = /\/$/.test(metadataPath); if (isDirectory) { if (!looksLikeDirectory) metadataPath += "/"; } else { if (looksLikeDirectory) throw new Error("file path cannot end with '/': " + metadataPath); } return metadataPath; } var EMPTY_BUFFER = bufferAlloc(0); function Entry(metadataPath, isDirectory, options) { this.utf8FileName = bufferFrom(metadataPath); if (this.utf8FileName.length > 65535) throw new Error("utf8 file name too long. " + utf8FileName.length + " > 65535"); this.isDirectory = isDirectory; this.state = Entry.WAITING_FOR_METADATA; this.setLastModDate(options.mtime != null ? options.mtime : /* @__PURE__ */ new Date()); if (options.mode != null) { this.setFileAttributesMode(options.mode); } else { this.setFileAttributesMode(isDirectory ? 16893 : 33204); } if (isDirectory) { this.crcAndFileSizeKnown = true; this.crc32 = 0; this.uncompressedSize = 0; this.compressedSize = 0; } else { this.crcAndFileSizeKnown = false; this.crc32 = null; this.uncompressedSize = null; this.compressedSize = null; if (options.size != null) this.uncompressedSize = options.size; } if (isDirectory) { this.compress = false; } else { this.compress = true; if (options.compress != null) this.compress = !!options.compress; } this.forceZip64Format = !!options.forceZip64Format; if (options.fileComment) { if (typeof options.fileComment === "string") { this.fileComment = bufferFrom(options.fileComment, "utf-8"); } else { this.fileComment = options.fileComment; } if (this.fileComment.length > 65535) throw new Error("fileComment is too large"); } else { this.fileComment = EMPTY_BUFFER; } } Entry.WAITING_FOR_METADATA = 0; Entry.READY_TO_PUMP_FILE_DATA = 1; Entry.FILE_DATA_IN_PROGRESS = 2; Entry.FILE_DATA_DONE = 3; Entry.prototype.setLastModDate = function(date5) { var dosDateTime = dateToDosDateTime(date5); this.lastModFileTime = dosDateTime.time; this.lastModFileDate = dosDateTime.date; }; Entry.prototype.setFileAttributesMode = function(mode) { if ((mode & 65535) !== mode) throw new Error("invalid mode. expected: 0 <= " + mode + " <= 65535"); this.externalFileAttributes = mode << 16 >>> 0; }; Entry.prototype.setFileDataPumpFunction = function(doFileDataPump) { this.doFileDataPump = doFileDataPump; this.state = Entry.READY_TO_PUMP_FILE_DATA; }; Entry.prototype.useZip64Format = function() { return this.forceZip64Format || this.uncompressedSize != null && this.uncompressedSize > 4294967294 || this.compressedSize != null && this.compressedSize > 4294967294 || this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 4294967294; }; var LOCAL_FILE_HEADER_FIXED_SIZE = 30; var VERSION_NEEDED_TO_EXTRACT_UTF8 = 20; var VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45; var VERSION_MADE_BY = 3 << 8 | 63; var FILE_NAME_IS_UTF8 = 1 << 11; var UNKNOWN_CRC32_AND_FILE_SIZES = 1 << 3; Entry.prototype.getLocalFileHeader = function() { var crc322 = 0; var compressedSize = 0; var uncompressedSize = 0; if (this.crcAndFileSizeKnown) { crc322 = this.crc32; compressedSize = this.compressedSize; uncompressedSize = this.uncompressedSize; } var fixedSizeStuff = bufferAlloc(LOCAL_FILE_HEADER_FIXED_SIZE); var generalPurposeBitFlag = FILE_NAME_IS_UTF8; if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; fixedSizeStuff.writeUInt32LE(67324752, 0); fixedSizeStuff.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_UTF8, 4); fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 6); fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 8); fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 10); fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 12); fixedSizeStuff.writeUInt32LE(crc322, 14); fixedSizeStuff.writeUInt32LE(compressedSize, 18); fixedSizeStuff.writeUInt32LE(uncompressedSize, 22); fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 26); fixedSizeStuff.writeUInt16LE(0, 28); return Buffer.concat([ fixedSizeStuff, // file name (variable size) this.utf8FileName // extra field (variable size) // no extra fields ]); }; var DATA_DESCRIPTOR_SIZE = 16; var ZIP64_DATA_DESCRIPTOR_SIZE = 24; Entry.prototype.getDataDescriptor = function() { if (this.crcAndFileSizeKnown) { return EMPTY_BUFFER; } if (!this.useZip64Format()) { var buffer = bufferAlloc(DATA_DESCRIPTOR_SIZE); buffer.writeUInt32LE(134695760, 0); buffer.writeUInt32LE(this.crc32, 4); buffer.writeUInt32LE(this.compressedSize, 8); buffer.writeUInt32LE(this.uncompressedSize, 12); return buffer; } else { var buffer = bufferAlloc(ZIP64_DATA_DESCRIPTOR_SIZE); buffer.writeUInt32LE(134695760, 0); buffer.writeUInt32LE(this.crc32, 4); writeUInt64LE(buffer, this.compressedSize, 8); writeUInt64LE(buffer, this.uncompressedSize, 16); return buffer; } }; var CENTRAL_DIRECTORY_RECORD_FIXED_SIZE = 46; var ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE = 28; Entry.prototype.getCentralDirectoryRecord = function() { var fixedSizeStuff = bufferAlloc(CENTRAL_DIRECTORY_RECORD_FIXED_SIZE); var generalPurposeBitFlag = FILE_NAME_IS_UTF8; if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; var normalCompressedSize = this.compressedSize; var normalUncompressedSize = this.uncompressedSize; var normalRelativeOffsetOfLocalHeader = this.relativeOffsetOfLocalHeader; var versionNeededToExtract; var zeiefBuffer; if (this.useZip64Format()) { normalCompressedSize = 4294967295; normalUncompressedSize = 4294967295; normalRelativeOffsetOfLocalHeader = 4294967295; versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_ZIP64; zeiefBuffer = bufferAlloc(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE); zeiefBuffer.writeUInt16LE(1, 0); zeiefBuffer.writeUInt16LE(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE - 4, 2); writeUInt64LE(zeiefBuffer, this.uncompressedSize, 4); writeUInt64LE(zeiefBuffer, this.compressedSize, 12); writeUInt64LE(zeiefBuffer, this.relativeOffsetOfLocalHeader, 20); } else { versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_UTF8; zeiefBuffer = EMPTY_BUFFER; } fixedSizeStuff.writeUInt32LE(33639248, 0); fixedSizeStuff.writeUInt16LE(VERSION_MADE_BY, 4); fixedSizeStuff.writeUInt16LE(versionNeededToExtract, 6); fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 8); fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 10); fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 12); fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 14); fixedSizeStuff.writeUInt32LE(this.crc32, 16); fixedSizeStuff.writeUInt32LE(normalCompressedSize, 20); fixedSizeStuff.writeUInt32LE(normalUncompressedSize, 24); fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 28); fixedSizeStuff.writeUInt16LE(zeiefBuffer.length, 30); fixedSizeStuff.writeUInt16LE(this.fileComment.length, 32); fixedSizeStuff.writeUInt16LE(0, 34); fixedSizeStuff.writeUInt16LE(0, 36); fixedSizeStuff.writeUInt32LE(this.externalFileAttributes, 38); fixedSizeStuff.writeUInt32LE(normalRelativeOffsetOfLocalHeader, 42); return Buffer.concat([ fixedSizeStuff, // file name (variable size) this.utf8FileName, // extra field (variable size) zeiefBuffer, // file comment (variable size) this.fileComment ]); }; Entry.prototype.getCompressionMethod = function() { var NO_COMPRESSION = 0; var DEFLATE_COMPRESSION = 8; return this.compress ? DEFLATE_COMPRESSION : NO_COMPRESSION; }; function dateToDosDateTime(jsDate) { var date5 = 0; date5 |= jsDate.getDate() & 31; date5 |= (jsDate.getMonth() + 1 & 15) << 5; date5 |= (jsDate.getFullYear() - 1980 & 127) << 9; var time3 = 0; time3 |= Math.floor(jsDate.getSeconds() / 2); time3 |= (jsDate.getMinutes() & 63) << 5; time3 |= (jsDate.getHours() & 31) << 11; return { date: date5, time: time3 }; } function writeUInt64LE(buffer, n, offset) { var high = Math.floor(n / 4294967296); var low = n % 4294967296; buffer.writeUInt32LE(low, offset); buffer.writeUInt32LE(high, offset + 4); } util2.inherits(ByteCounter, Transform); function ByteCounter(options) { Transform.call(this, options); this.byteCount = 0; } ByteCounter.prototype._transform = function(chunk, encoding, cb) { this.byteCount += chunk.length; cb(null, chunk); }; util2.inherits(Crc32Watcher, Transform); function Crc32Watcher(options) { Transform.call(this, options); this.crc32 = 0; } Crc32Watcher.prototype._transform = function(chunk, encoding, cb) { this.crc32 = crc32.unsigned(chunk, this.crc32); cb(null, chunk); }; var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"; if (cp437.length !== 256) throw new Error("assertion failure"); var reverseCp437 = null; function encodeCp437(string4) { if (/^[\x20-\x7e]*$/.test(string4)) { return bufferFrom(string4, "utf-8"); } if (reverseCp437 == null) { reverseCp437 = {}; for (var i = 0; i < cp437.length; i++) { reverseCp437[cp437[i]] = i; } } var result = bufferAlloc(string4.length); for (var i = 0; i < string4.length; i++) { var b = reverseCp437[string4[i]]; if (b == null) throw new Error("character not encodable in CP437: " + JSON.stringify(string4[i])); result[i] = b; } return result; } function bufferAlloc(size) { bufferAlloc = modern; try { return bufferAlloc(size); } catch (e) { bufferAlloc = legacy; return bufferAlloc(size); } function modern(size2) { return Buffer.allocUnsafe(size2); } function legacy(size2) { return new Buffer(size2); } } function bufferFrom(something, encoding) { bufferFrom = modern; try { return bufferFrom(something, encoding); } catch (e) { bufferFrom = legacy; return bufferFrom(something, encoding); } function modern(something2, encoding2) { return Buffer.from(something2, encoding2); } function legacy(something2, encoding2) { return new Buffer(something2, encoding2); } } function bufferIncludes(buffer, content) { bufferIncludes = modern; try { return bufferIncludes(buffer, content); } catch (e) { bufferIncludes = legacy; return bufferIncludes(buffer, content); } function modern(buffer2, content2) { return buffer2.includes(content2); } function legacy(buffer2, content2) { for (var i = 0; i <= buffer2.length - content2.length; i++) { for (var j = 0; ; j++) { if (j === content2.length) return true; if (buffer2[i + j] !== content2[j]) break; } } return false; } } } }); // node_modules/graceful-fs/polyfills.js var require_polyfills = __commonJS({ "node_modules/graceful-fs/polyfills.js"(exports2, module2) { var constants = require("constants"); var origCwd = process.cwd; var cwd = null; var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform; process.cwd = function() { if (!cwd) cwd = origCwd.call(process); return cwd; }; try { process.cwd(); } catch (er) { } if (typeof process.chdir === "function") { chdir = process.chdir; process.chdir = function(d) { cwd = null; chdir.call(process, d); }; if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir); } var chdir; module2.exports = patch; function patch(fs) { if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { patchLchmod(fs); } if (!fs.lutimes) { patchLutimes(fs); } fs.chown = chownFix(fs.chown); fs.fchown = chownFix(fs.fchown); fs.lchown = chownFix(fs.lchown); fs.chmod = chmodFix(fs.chmod); fs.fchmod = chmodFix(fs.fchmod); fs.lchmod = chmodFix(fs.lchmod); fs.chownSync = chownFixSync(fs.chownSync); fs.fchownSync = chownFixSync(fs.fchownSync); fs.lchownSync = chownFixSync(fs.lchownSync); fs.chmodSync = chmodFixSync(fs.chmodSync); fs.fchmodSync = chmodFixSync(fs.fchmodSync); fs.lchmodSync = chmodFixSync(fs.lchmodSync); fs.stat = statFix(fs.stat); fs.fstat = statFix(fs.fstat); fs.lstat = statFix(fs.lstat); fs.statSync = statFixSync(fs.statSync); fs.fstatSync = statFixSync(fs.fstatSync); fs.lstatSync = statFixSync(fs.lstatSync); if (fs.chmod && !fs.lchmod) { fs.lchmod = function(path, mode, cb) { if (cb) process.nextTick(cb); }; fs.lchmodSync = function() { }; } if (fs.chown && !fs.lchown) { fs.lchown = function(path, uid, gid, cb) { if (cb) process.nextTick(cb); }; fs.lchownSync = function() { }; } if (platform === "win32") { fs.rename = typeof fs.rename !== "function" ? fs.rename : (function(fs$rename) { function rename(from, to, cb) { var start = Date.now(); var backoff = 0; fs$rename(from, to, function CB(er) { if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 6e4) { setTimeout(function() { fs.stat(to, function(stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else cb(er); }); }, backoff); if (backoff < 100) backoff += 10; return; } if (cb) cb(er); }); } if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename); return rename; })(fs.rename); } fs.read = typeof fs.read !== "function" ? fs.read : (function(fs$read) { function read(fd, buffer, offset, length, position, callback_) { var callback; if (callback_ && typeof callback_ === "function") { var eagCounter = 0; callback = function(er, _, __) { if (er && er.code === "EAGAIN" && eagCounter < 10) { eagCounter++; return fs$read.call(fs, fd, buffer, offset, length, position, callback); } callback_.apply(this, arguments); }; } return fs$read.call(fs, fd, buffer, offset, length, position, callback); } if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read); return read; })(fs.read); fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : /* @__PURE__ */ (function(fs$readSync) { return function(fd, buffer, offset, length, position) { var eagCounter = 0; while (true) { try { return fs$readSync.call(fs, fd, buffer, offset, length, position); } catch (er) { if (er.code === "EAGAIN" && eagCounter < 10) { eagCounter++; continue; } throw er; } } }; })(fs.readSync); function patchLchmod(fs2) { fs2.lchmod = function(path, mode, callback) { fs2.open( path, constants.O_WRONLY | constants.O_SYMLINK, mode, function(err, fd) { if (err) { if (callback) callback(err); return; } fs2.fchmod(fd, mode, function(err2) { fs2.close(fd, function(err22) { if (callback) callback(err2 || err22); }); }); } ); }; fs2.lchmodSync = function(path, mode) { var fd = fs2.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode); var threw = true; var ret; try { ret = fs2.fchmodSync(fd, mode); threw = false; } finally { if (threw) { try { fs2.closeSync(fd); } catch (er) { } } else { fs2.closeSync(fd); } } return ret; }; } function patchLutimes(fs2) { if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) { fs2.lutimes = function(path, at, mt, cb) { fs2.open(path, constants.O_SYMLINK, function(er, fd) { if (er) { if (cb) cb(er); return; } fs2.futimes(fd, at, mt, function(er2) { fs2.close(fd, function(er22) { if (cb) cb(er2 || er22); }); }); }); }; fs2.lutimesSync = function(path, at, mt) { var fd = fs2.openSync(path, constants.O_SYMLINK); var ret; var threw = true; try { ret = fs2.futimesSync(fd, at, mt); threw = false; } finally { if (threw) { try { fs2.closeSync(fd); } catch (er) { } } else { fs2.closeSync(fd); } } return ret; }; } else if (fs2.futimes) { fs2.lutimes = function(_a2, _b, _c, cb) { if (cb) process.nextTick(cb); }; fs2.lutimesSync = function() { }; } } function chmodFix(orig) { if (!orig) return orig; return function(target, mode, cb) { return orig.call(fs, target, mode, function(er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }); }; } function chmodFixSync(orig) { if (!orig) return orig; return function(target, mode) { try { return orig.call(fs, target, mode); } catch (er) { if (!chownErOk(er)) throw er; } }; } function chownFix(orig) { if (!orig) return orig; return function(target, uid, gid, cb) { return orig.call(fs, target, uid, gid, function(er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }); }; } function chownFixSync(orig) { if (!orig) return orig; return function(target, uid, gid) { try { return orig.call(fs, target, uid, gid); } catch (er) { if (!chownErOk(er)) throw er; } }; } function statFix(orig) { if (!orig) return orig; return function(target, options, cb) { if (typeof options === "function") { cb = options; options = null; } function callback(er, stats) { if (stats) { if (stats.uid < 0) stats.uid += 4294967296; if (stats.gid < 0) stats.gid += 4294967296; } if (cb) cb.apply(this, arguments); } return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback); }; } function statFixSync(orig) { if (!orig) return orig; return function(target, options) { var stats = options ? orig.call(fs, target, options) : orig.call(fs, target); if (stats) { if (stats.uid < 0) stats.uid += 4294967296; if (stats.gid < 0) stats.gid += 4294967296; } return stats; }; } function chownErOk(er) { if (!er) return true; if (er.code === "ENOSYS") return true; var nonroot = !process.getuid || process.getuid() !== 0; if (nonroot) { if (er.code === "EINVAL" || er.code === "EPERM") return true; } return false; } } } }); // node_modules/graceful-fs/legacy-streams.js var require_legacy_streams = __commonJS({ "node_modules/graceful-fs/legacy-streams.js"(exports2, module2) { var Stream = require("stream").Stream; module2.exports = legacy; function legacy(fs) { return { ReadStream, WriteStream }; function ReadStream(path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); Stream.call(this); var self = this; this.path = path; this.fd = null; this.readable = true; this.paused = false; this.flags = "r"; this.mode = 438; this.bufferSize = 64 * 1024; options = options || {}; var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.encoding) this.setEncoding(this.encoding); if (this.start !== void 0) { if ("number" !== typeof this.start) { throw TypeError("start must be a Number"); } if (this.end === void 0) { this.end = Infinity; } else if ("number" !== typeof this.end) { throw TypeError("end must be a Number"); } if (this.start > this.end) { throw new Error("start must be <= end"); } this.pos = this.start; } if (this.fd !== null) { process.nextTick(function() { self._read(); }); return; } fs.open(this.path, this.flags, this.mode, function(err, fd) { if (err) { self.emit("error", err); self.readable = false; return; } self.fd = fd; self.emit("open", fd); self._read(); }); } function WriteStream(path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); Stream.call(this); this.path = path; this.fd = null; this.writable = true; this.flags = "w"; this.encoding = "binary"; this.mode = 438; this.bytesWritten = 0; options = options || {}; var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.start !== void 0) { if ("number" !== typeof this.start) { throw TypeError("start must be a Number"); } if (this.start < 0) { throw new Error("start must be >= zero"); } this.pos = this.start; } this.busy = false; this._queue = []; if (this.fd === null) { this._open = fs.open; this._queue.push([this._open, this.path, this.flags, this.mode, void 0]); this.flush(); } } } } }); // node_modules/graceful-fs/clone.js var require_clone = __commonJS({ "node_modules/graceful-fs/clone.js"(exports2, module2) { "use strict"; module2.exports = clone2; var getPrototypeOf = Object.getPrototypeOf || function(obj) { return obj.__proto__; }; function clone2(obj) { if (obj === null || typeof obj !== "object") return obj; if (obj instanceof Object) var copy = { __proto__: getPrototypeOf(obj) }; else var copy = /* @__PURE__ */ Object.create(null); Object.getOwnPropertyNames(obj).forEach(function(key) { Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)); }); return copy; } } }); // node_modules/graceful-fs/graceful-fs.js var require_graceful_fs = __commonJS({ "node_modules/graceful-fs/graceful-fs.js"(exports2, module2) { var fs = require("fs"); var polyfills = require_polyfills(); var legacy = require_legacy_streams(); var clone2 = require_clone(); var util2 = require("util"); var gracefulQueue; var previousSymbol; if (typeof Symbol === "function" && typeof Symbol.for === "function") { gracefulQueue = Symbol.for("graceful-fs.queue"); previousSymbol = Symbol.for("graceful-fs.previous"); } else { gracefulQueue = "___graceful-fs.queue"; previousSymbol = "___graceful-fs.previous"; } function noop2() { } function publishQueue(context, queue2) { Object.defineProperty(context, gracefulQueue, { get: function() { return queue2; } }); } var debug2 = noop2; if (util2.debuglog) debug2 = util2.debuglog("gfs4"); else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) debug2 = function() { var m = util2.format.apply(util2, arguments); m = "GFS4: " + m.split(/\n/).join("\nGFS4: "); console.error(m); }; if (!fs[gracefulQueue]) { queue = global[gracefulQueue] || []; publishQueue(fs, queue); fs.close = (function(fs$close) { function close(fd, cb) { return fs$close.call(fs, fd, function(err) { if (!err) { resetQueue(); } if (typeof cb === "function") cb.apply(this, arguments); }); } Object.defineProperty(close, previousSymbol, { value: fs$close }); return close; })(fs.close); fs.closeSync = (function(fs$closeSync) { function closeSync(fd) { fs$closeSync.apply(fs, arguments); resetQueue(); } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }); return closeSync; })(fs.closeSync); if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) { process.on("exit", function() { debug2(fs[gracefulQueue]); require("assert").equal(fs[gracefulQueue].length, 0); }); } } var queue; if (!global[gracefulQueue]) { publishQueue(global, fs[gracefulQueue]); } module2.exports = patch(clone2(fs)); if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { module2.exports = patch(fs); fs.__patched = true; } function patch(fs2) { polyfills(fs2); fs2.gracefulify = patch; fs2.createReadStream = createReadStream; fs2.createWriteStream = createWriteStream; var fs$readFile = fs2.readFile; fs2.readFile = readFile; function readFile(path, options, cb) { if (typeof options === "function") cb = options, options = null; return go$readFile(path, options, cb); function go$readFile(path2, options2, cb2, startTime) { return fs$readFile(path2, options2, function(err) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); } }); } } var fs$writeFile = fs2.writeFile; fs2.writeFile = writeFile; function writeFile(path, data, options, cb) { if (typeof options === "function") cb = options, options = null; return go$writeFile(path, data, options, cb); function go$writeFile(path2, data2, options2, cb2, startTime) { return fs$writeFile(path2, data2, options2, function(err) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); } }); } } var fs$appendFile = fs2.appendFile; if (fs$appendFile) fs2.appendFile = appendFile; function appendFile(path, data, options, cb) { if (typeof options === "function") cb = options, options = null; return go$appendFile(path, data, options, cb); function go$appendFile(path2, data2, options2, cb2, startTime) { return fs$appendFile(path2, data2, options2, function(err) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); } }); } } var fs$copyFile = fs2.copyFile; if (fs$copyFile) fs2.copyFile = copyFile; function copyFile(src, dest, flags, cb) { if (typeof flags === "function") { cb = flags; flags = 0; } return go$copyFile(src, dest, flags, cb); function go$copyFile(src2, dest2, flags2, cb2, startTime) { return fs$copyFile(src2, dest2, flags2, function(err) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); } }); } } var fs$readdir = fs2.readdir; fs2.readdir = readdir; var noReaddirOptionVersions = /^v[0-5]\./; function readdir(path, options, cb) { if (typeof options === "function") cb = options, options = null; var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path2, options2, cb2, startTime) { return fs$readdir(path2, fs$readdirCallback( path2, options2, cb2, startTime )); } : function go$readdir2(path2, options2, cb2, startTime) { return fs$readdir(path2, options2, fs$readdirCallback( path2, options2, cb2, startTime )); }; return go$readdir(path, options, cb); function fs$readdirCallback(path2, options2, cb2, startTime) { return function(err, files) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([ go$readdir, [path2, options2, cb2], err, startTime || Date.now(), Date.now() ]); else { if (files && files.sort) files.sort(); if (typeof cb2 === "function") cb2.call(this, err, files); } }; } } if (process.version.substr(0, 4) === "v0.8") { var legStreams = legacy(fs2); ReadStream = legStreams.ReadStream; WriteStream = legStreams.WriteStream; } var fs$ReadStream = fs2.ReadStream; if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype); ReadStream.prototype.open = ReadStream$open; } var fs$WriteStream = fs2.WriteStream; if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype); WriteStream.prototype.open = WriteStream$open; } Object.defineProperty(fs2, "ReadStream", { get: function() { return ReadStream; }, set: function(val) { ReadStream = val; }, enumerable: true, configurable: true }); Object.defineProperty(fs2, "WriteStream", { get: function() { return WriteStream; }, set: function(val) { WriteStream = val; }, enumerable: true, configurable: true }); var FileReadStream = ReadStream; Object.defineProperty(fs2, "FileReadStream", { get: function() { return FileReadStream; }, set: function(val) { FileReadStream = val; }, enumerable: true, configurable: true }); var FileWriteStream = WriteStream; Object.defineProperty(fs2, "FileWriteStream", { get: function() { return FileWriteStream; }, set: function(val) { FileWriteStream = val; }, enumerable: true, configurable: true }); function ReadStream(path, options) { if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this; else return ReadStream.apply(Object.create(ReadStream.prototype), arguments); } function ReadStream$open() { var that = this; open2(that.path, that.flags, that.mode, function(err, fd) { if (err) { if (that.autoClose) that.destroy(); that.emit("error", err); } else { that.fd = fd; that.emit("open", fd); that.read(); } }); } function WriteStream(path, options) { if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this; else return WriteStream.apply(Object.create(WriteStream.prototype), arguments); } function WriteStream$open() { var that = this; open2(that.path, that.flags, that.mode, function(err, fd) { if (err) { that.destroy(); that.emit("error", err); } else { that.fd = fd; that.emit("open", fd); } }); } function createReadStream(path, options) { return new fs2.ReadStream(path, options); } function createWriteStream(path, options) { return new fs2.WriteStream(path, options); } var fs$open = fs2.open; fs2.open = open2; function open2(path, flags, mode, cb) { if (typeof mode === "function") cb = mode, mode = null; return go$open(path, flags, mode, cb); function go$open(path2, flags2, mode2, cb2, startTime) { return fs$open(path2, flags2, mode2, function(err, fd) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); } }); } } return fs2; } function enqueue(elem) { debug2("ENQUEUE", elem[0].name, elem[1]); fs[gracefulQueue].push(elem); retry2(); } var retryTimer; function resetQueue() { var now = Date.now(); for (var i = 0; i < fs[gracefulQueue].length; ++i) { if (fs[gracefulQueue][i].length > 2) { fs[gracefulQueue][i][3] = now; fs[gracefulQueue][i][4] = now; } } retry2(); } function retry2() { clearTimeout(retryTimer); retryTimer = void 0; if (fs[gracefulQueue].length === 0) return; var elem = fs[gracefulQueue].shift(); var fn = elem[0]; var args = elem[1]; var err = elem[2]; var startTime = elem[3]; var lastTime = elem[4]; if (startTime === void 0) { debug2("RETRY", fn.name, args); fn.apply(null, args); } else if (Date.now() - startTime >= 6e4) { debug2("TIMEOUT", fn.name, args); var cb = args.pop(); if (typeof cb === "function") cb.call(null, err); } else { var sinceAttempt = Date.now() - lastTime; var sinceStart = Math.max(lastTime - startTime, 1); var desiredDelay = Math.min(sinceStart * 1.2, 100); if (sinceAttempt >= desiredDelay) { debug2("RETRY", fn.name, args); fn.apply(null, args.concat([startTime])); } else { fs[gracefulQueue].push(elem); } } if (retryTimer === void 0) { retryTimer = setTimeout(retry2, 0); } } } }); // node_modules/retry/lib/retry_operation.js var require_retry_operation = __commonJS({ "node_modules/retry/lib/retry_operation.js"(exports2, module2) { function RetryOperation(timeouts, options) { if (typeof options === "boolean") { options = { forever: options }; } this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); this._timeouts = timeouts; this._options = options || {}; this._maxRetryTime = options && options.maxRetryTime || Infinity; this._fn = null; this._errors = []; this._attempts = 1; this._operationTimeout = null; this._operationTimeoutCb = null; this._timeout = null; this._operationStart = null; if (this._options.forever) { this._cachedTimeouts = this._timeouts.slice(0); } } module2.exports = RetryOperation; RetryOperation.prototype.reset = function() { this._attempts = 1; this._timeouts = this._originalTimeouts; }; RetryOperation.prototype.stop = function() { if (this._timeout) { clearTimeout(this._timeout); } this._timeouts = []; this._cachedTimeouts = null; }; RetryOperation.prototype.retry = function(err) { if (this._timeout) { clearTimeout(this._timeout); } if (!err) { return false; } var currentTime = (/* @__PURE__ */ new Date()).getTime(); if (err && currentTime - this._operationStart >= this._maxRetryTime) { this._errors.unshift(new Error("RetryOperation timeout occurred")); return false; } this._errors.push(err); var timeout = this._timeouts.shift(); if (timeout === void 0) { if (this._cachedTimeouts) { this._errors.splice(this._errors.length - 1, this._errors.length); this._timeouts = this._cachedTimeouts.slice(0); timeout = this._timeouts.shift(); } else { return false; } } var self = this; var timer = setTimeout(function() { self._attempts++; if (self._operationTimeoutCb) { self._timeout = setTimeout(function() { self._operationTimeoutCb(self._attempts); }, self._operationTimeout); if (self._options.unref) { self._timeout.unref(); } } self._fn(self._attempts); }, timeout); if (this._options.unref) { timer.unref(); } return true; }; RetryOperation.prototype.attempt = function(fn, timeoutOps) { this._fn = fn; if (timeoutOps) { if (timeoutOps.timeout) { this._operationTimeout = timeoutOps.timeout; } if (timeoutOps.cb) { this._operationTimeoutCb = timeoutOps.cb; } } var self = this; if (this._operationTimeoutCb) { this._timeout = setTimeout(function() { self._operationTimeoutCb(); }, self._operationTimeout); } this._operationStart = (/* @__PURE__ */ new Date()).getTime(); this._fn(this._attempts); }; RetryOperation.prototype.try = function(fn) { console.log("Using RetryOperation.try() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = function(fn) { console.log("Using RetryOperation.start() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = RetryOperation.prototype.try; RetryOperation.prototype.errors = function() { return this._errors; }; RetryOperation.prototype.attempts = function() { return this._attempts; }; RetryOperation.prototype.mainError = function() { if (this._errors.length === 0) { return null; } var counts = {}; var mainError = null; var mainErrorCount = 0; for (var i = 0; i < this._errors.length; i++) { var error48 = this._errors[i]; var message = error48.message; var count = (counts[message] || 0) + 1; counts[message] = count; if (count >= mainErrorCount) { mainError = error48; mainErrorCount = count; } } return mainError; }; } }); // node_modules/retry/lib/retry.js var require_retry = __commonJS({ "node_modules/retry/lib/retry.js"(exports2) { var RetryOperation = require_retry_operation(); exports2.operation = function(options) { var timeouts = exports2.timeouts(options); return new RetryOperation(timeouts, { forever: options && options.forever, unref: options && options.unref, maxRetryTime: options && options.maxRetryTime }); }; exports2.timeouts = function(options) { if (options instanceof Array) { return [].concat(options); } var opts = { retries: 10, factor: 2, minTimeout: 1 * 1e3, maxTimeout: Infinity, randomize: false }; for (var key in options) { opts[key] = options[key]; } if (opts.minTimeout > opts.maxTimeout) { throw new Error("minTimeout is greater than maxTimeout"); } var timeouts = []; for (var i = 0; i < opts.retries; i++) { timeouts.push(this.createTimeout(i, opts)); } if (options && options.forever && !timeouts.length) { timeouts.push(this.createTimeout(i, opts)); } timeouts.sort(function(a, b) { return a - b; }); return timeouts; }; exports2.createTimeout = function(attempt, opts) { var random2 = opts.randomize ? Math.random() + 1 : 1; var timeout = Math.round(random2 * opts.minTimeout * Math.pow(opts.factor, attempt)); timeout = Math.min(timeout, opts.maxTimeout); return timeout; }; exports2.wrap = function(obj, options, methods) { if (options instanceof Array) { methods = options; options = null; } if (!methods) { methods = []; for (var key in obj) { if (typeof obj[key] === "function") { methods.push(key); } } } for (var i = 0; i < methods.length; i++) { var method = methods[i]; var original = obj[method]; obj[method] = function retryWrapper(original2) { var op = exports2.operation(options); var args = Array.prototype.slice.call(arguments, 1); var callback = args.pop(); args.push(function(err) { if (op.retry(err)) { return; } if (err) { arguments[0] = op.mainError(); } callback.apply(this, arguments); }); op.attempt(function() { original2.apply(obj, args); }); }.bind(obj, original); obj[method].options = options; } }; } }); // node_modules/retry/index.js var require_retry2 = __commonJS({ "node_modules/retry/index.js"(exports2, module2) { module2.exports = require_retry(); } }); // node_modules/signal-exit/signals.js var require_signals = __commonJS({ "node_modules/signal-exit/signals.js"(exports2, module2) { module2.exports = [ "SIGABRT", "SIGALRM", "SIGHUP", "SIGINT", "SIGTERM" ]; if (process.platform !== "win32") { module2.exports.push( "SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT" // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ); } if (process.platform === "linux") { module2.exports.push( "SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED" ); } } }); // node_modules/signal-exit/index.js var require_signal_exit = __commonJS({ "node_modules/signal-exit/index.js"(exports2, module2) { var process5 = global.process; var processOk = function(process6) { return process6 && typeof process6 === "object" && typeof process6.removeListener === "function" && typeof process6.emit === "function" && typeof process6.reallyExit === "function" && typeof process6.listeners === "function" && typeof process6.kill === "function" && typeof process6.pid === "number" && typeof process6.on === "function"; }; if (!processOk(process5)) { module2.exports = function() { return function() { }; }; } else { assert2 = require("assert"); signals = require_signals(); isWin2 = /^win/i.test(process5.platform); EE = require("events"); if (typeof EE !== "function") { EE = EE.EventEmitter; } if (process5.__signal_exit_emitter__) { emitter = process5.__signal_exit_emitter__; } else { emitter = process5.__signal_exit_emitter__ = new EE(); emitter.count = 0; emitter.emitted = {}; } if (!emitter.infinite) { emitter.setMaxListeners(Infinity); emitter.infinite = true; } module2.exports = function(cb, opts) { if (!processOk(global.process)) { return function() { }; } assert2.equal(typeof cb, "function", "a callback must be provided for exit handler"); if (loaded === false) { load(); } var ev = "exit"; if (opts && opts.alwaysLast) { ev = "afterexit"; } var remove = function() { emitter.removeListener(ev, cb); if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) { unload(); } }; emitter.on(ev, cb); return remove; }; unload = function unload2() { if (!loaded || !processOk(global.process)) { return; } loaded = false; signals.forEach(function(sig) { try { process5.removeListener(sig, sigListeners[sig]); } catch (er) { } }); process5.emit = originalProcessEmit; process5.reallyExit = originalProcessReallyExit; emitter.count -= 1; }; module2.exports.unload = unload; emit = function emit2(event, code, signal) { if (emitter.emitted[event]) { return; } emitter.emitted[event] = true; emitter.emit(event, code, signal); }; sigListeners = {}; signals.forEach(function(sig) { sigListeners[sig] = function listener() { if (!processOk(global.process)) { return; } var listeners = process5.listeners(sig); if (listeners.length === emitter.count) { unload(); emit("exit", null, sig); emit("afterexit", null, sig); if (isWin2 && sig === "SIGHUP") { sig = "SIGINT"; } process5.kill(process5.pid, sig); } }; }); module2.exports.signals = function() { return signals; }; loaded = false; load = function load2() { if (loaded || !processOk(global.process)) { return; } loaded = true; emitter.count += 1; signals = signals.filter(function(sig) { try { process5.on(sig, sigListeners[sig]); return true; } catch (er) { return false; } }); process5.emit = processEmit; process5.reallyExit = processReallyExit; }; module2.exports.load = load; originalProcessReallyExit = process5.reallyExit; processReallyExit = function processReallyExit2(code) { if (!processOk(global.process)) { return; } process5.exitCode = code || /* istanbul ignore next */ 0; emit("exit", process5.exitCode, null); emit("afterexit", process5.exitCode, null); originalProcessReallyExit.call(process5, process5.exitCode); }; originalProcessEmit = process5.emit; processEmit = function processEmit2(ev, arg) { if (ev === "exit" && processOk(global.process)) { if (arg !== void 0) { process5.exitCode = arg; } var ret = originalProcessEmit.apply(this, arguments); emit("exit", process5.exitCode, null); emit("afterexit", process5.exitCode, null); return ret; } else { return originalProcessEmit.apply(this, arguments); } }; } var assert2; var signals; var isWin2; var EE; var emitter; var unload; var emit; var sigListeners; var loaded; var load; var originalProcessReallyExit; var processReallyExit; var originalProcessEmit; var processEmit; } }); // node_modules/wrappy/wrappy.js var require_wrappy = __commonJS({ "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 i = 0; i < args.length; i++) { args[i] = arguments[i]; } 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/once/once.js var require_once = __commonJS({ "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 f = function() { if (f.called) return f.value; f.called = true; return f.value = fn.apply(this, arguments); }; f.called = false; return f; } function onceStrict(fn) { var f = function() { if (f.called) throw new Error(f.onceError); f.called = true; return f.value = fn.apply(this, arguments); }; var name = fn.name || "Function wrapped with `once`"; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f; } } }); // node_modules/end-of-stream/index.js var require_end_of_stream = __commonJS({ "node_modules/end-of-stream/index.js"(exports2, module2) { var once = require_once(); var noop2 = function() { }; var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process); var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === "function"; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3; }; var eos = function(stream, opts, callback) { if (typeof opts === "function") return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop2); var ws2 = stream._writableState; var rs = stream._readableState; var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null); }; var onerror = function(err) { callback.call(stream, err); }; var onclose = function() { qnt(onclosenexttick); }; var onclosenexttick = function() { if (cancelled) return; if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error("premature close")); if (writable && !(ws2 && (ws2.ended && !ws2.destroyed))) return callback.call(stream, new Error("premature close")); }; var onrequest = function() { stream.req.on("finish", onfinish); }; if (isRequest(stream)) { stream.on("complete", onfinish); stream.on("abort", onclose); if (stream.req) onrequest(); else stream.on("request", onrequest); } else if (writable && !ws2) { stream.on("end", onlegacyfinish); stream.on("close", onlegacyfinish); } if (isChildProcess(stream)) stream.on("exit", onexit); stream.on("end", onend); stream.on("finish", onfinish); if (opts.error !== false) stream.on("error", onerror); stream.on("close", onclose); return function() { cancelled = true; stream.removeListener("complete", onfinish); stream.removeListener("abort", onclose); stream.removeListener("request", onrequest); if (stream.req) stream.req.removeListener("finish", onfinish); stream.removeListener("end", onlegacyfinish); stream.removeListener("close", onlegacyfinish); stream.removeListener("finish", onfinish); stream.removeListener("exit", onexit); stream.removeListener("end", onend); stream.removeListener("error", onerror); stream.removeListener("close", onclose); }; }; module2.exports = eos; } }); // node_modules/pump/index.js var require_pump = __commonJS({ "node_modules/pump/index.js"(exports2, module2) { var once = require_once(); var eos = require_end_of_stream(); var fs; try { fs = require("fs"); } catch (e) { } var noop2 = function() { }; var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version); var isFn = function(fn) { return typeof fn === "function"; }; var isFS = function(stream) { if (!ancient) return false; if (!fs) return false; return (stream instanceof (fs.ReadStream || noop2) || stream instanceof (fs.WriteStream || noop2)) && isFn(stream.close); }; var isRequest = function(stream) { return stream.setHeader && isFn(stream.abort); }; var destroyer = function(stream, reading, writing, callback) { callback = once(callback); var closed = false; stream.on("close", function() { closed = true; }); eos(stream, { readable: reading, writable: writing }, function(err) { if (err) return callback(err); closed = true; callback(); }); var destroyed = false; return function(err) { if (closed) return; if (destroyed) return; destroyed = true; if (isFS(stream)) return stream.close(noop2); if (isRequest(stream)) return stream.abort(); if (isFn(stream.destroy)) return stream.destroy(); callback(err || new Error("stream was destroyed")); }; }; var call = function(fn) { fn(); }; var pipe2 = function(from, to) { return from.pipe(to); }; var pump = function() { var streams = Array.prototype.slice.call(arguments); var callback = isFn(streams[streams.length - 1] || noop2) && streams.pop() || noop2; if (Array.isArray(streams[0])) streams = streams[0]; if (streams.length < 2) throw new Error("pump requires two streams per minimum"); var error48; var destroys = streams.map(function(stream, i) { var reading = i < streams.length - 1; var writing = i > 0; return destroyer(stream, reading, writing, function(err) { if (!error48) error48 = err; if (err) destroys.forEach(call); if (reading) return; destroys.forEach(call); callback(error48); }); }); return streams.reduce(pipe2); }; module2.exports = pump; } }); // node_modules/get-stream/buffer-stream.js var require_buffer_stream = __commonJS({ "node_modules/get-stream/buffer-stream.js"(exports2, module2) { "use strict"; var { PassThrough: PassThroughStream } = require("stream"); module2.exports = (options) => { options = { ...options }; const { array: array2 } = options; let { encoding } = options; const isBuffer = encoding === "buffer"; let objectMode = false; if (array2) { objectMode = !(encoding || isBuffer); } else { encoding = encoding || "utf8"; } if (isBuffer) { encoding = null; } const stream = new PassThroughStream({ objectMode }); if (encoding) { stream.setEncoding(encoding); } let length = 0; const chunks = []; stream.on("data", (chunk) => { chunks.push(chunk); if (objectMode) { length = chunks.length; } else { length += chunk.length; } }); stream.getBufferedValue = () => { if (array2) { return chunks; } return isBuffer ? Buffer.concat(chunks, length) : chunks.join(""); }; stream.getBufferedLength = () => length; return stream; }; } }); // node_modules/get-stream/index.js var require_get_stream = __commonJS({ "node_modules/get-stream/index.js"(exports2, module2) { "use strict"; var { constants: BufferConstants } = require("buffer"); var pump = require_pump(); var bufferStream = require_buffer_stream(); var MaxBufferError = class extends Error { constructor() { super("maxBuffer exceeded"); this.name = "MaxBufferError"; } }; async function getStream2(inputStream, options) { if (!inputStream) { return Promise.reject(new Error("Expected a stream")); } options = { maxBuffer: Infinity, ...options }; const { maxBuffer } = options; let stream; await new Promise((resolve, reject) => { const rejectPromise = (error48) => { if (error48 && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error48.bufferedData = stream.getBufferedValue(); } reject(error48); }; stream = pump(inputStream, bufferStream(options), (error48) => { if (error48) { rejectPromise(error48); return; } resolve(); }); stream.on("data", () => { if (stream.getBufferedLength() > maxBuffer) { rejectPromise(new MaxBufferError()); } }); }); return stream.getBufferedValue(); } module2.exports = getStream2; module2.exports.default = getStream2; module2.exports.buffer = (stream, options) => getStream2(stream, { ...options, encoding: "buffer" }); module2.exports.array = (stream, options) => getStream2(stream, { ...options, array: true }); module2.exports.MaxBufferError = MaxBufferError; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/code.js var require_code = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/code.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.regexpCode = exports2.getEsmExportName = exports2.getProperty = exports2.safeStringify = exports2.stringify = exports2.strConcat = exports2.addCodeArg = exports2.str = exports2._ = exports2.nil = exports2._Code = exports2.Name = exports2.IDENTIFIER = exports2._CodeOrName = void 0; var _CodeOrName = class { }; exports2._CodeOrName = _CodeOrName; exports2.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var Name = class extends _CodeOrName { constructor(s) { super(); if (!exports2.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } }; exports2.Name = Name; var _Code = class extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a2; return (_a2 = this._str) !== null && _a2 !== void 0 ? _a2 : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); } get names() { var _a2; return (_a2 = this._names) !== null && _a2 !== void 0 ? _a2 : this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}); } }; exports2._Code = _Code; exports2.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports2._ = _; var plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports2.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports2.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== void 0) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; } exports2.strConcat = strConcat; function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports2.stringify = stringify; function safeStringify(x) { return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } exports2.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports2.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; } exports2.getProperty = getProperty; function getEsmExportName(key) { if (typeof key == "string" && exports2.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports2.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports2.regexpCode = regexpCode; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/scope.js var require_scope = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/scope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ValueScope = exports2.ValueScopeName = exports2.Scope = exports2.varKinds = exports2.UsedValueState = void 0; var code_1 = require_code(); var ValueError = class extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } }; var UsedValueState; (function(UsedValueState2) { UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; })(UsedValueState || (exports2.UsedValueState = UsedValueState = {})); exports2.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var") }; var Scope = class { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a2, _b; if (((_b = (_a2 = this._parent) === null || _a2 === void 0 ? void 0 : _a2._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return this._names[prefix] = { prefix, index: 0 }; } }; exports2.Scope = Scope; var ValueScopeName = class extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; } }; exports2.ValueScopeName = ValueScopeName; var line = (0, code_1._)`\n`; var ValueScope = class extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a2; if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a2 = value.key) !== null && _a2 !== void 0 ? _a2 : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = /* @__PURE__ */ new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._)`${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const; code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { code = (0, code_1._)`${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } }; exports2.ValueScope = ValueScope; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/index.js var require_codegen = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.or = exports2.and = exports2.not = exports2.CodeGen = exports2.operators = exports2.varKinds = exports2.ValueScopeName = exports2.ValueScope = exports2.Scope = exports2.Name = exports2.regexpCode = exports2.stringify = exports2.getProperty = exports2.nil = exports2.strConcat = exports2.str = exports2._ = void 0; var code_1 = require_code(); var scope_1 = require_scope(); var code_2 = require_code(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return code_2._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return code_2.str; } }); Object.defineProperty(exports2, "strConcat", { enumerable: true, get: function() { return code_2.strConcat; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return code_2.nil; } }); Object.defineProperty(exports2, "getProperty", { enumerable: true, get: function() { return code_2.getProperty; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return code_2.stringify; } }); Object.defineProperty(exports2, "regexpCode", { enumerable: true, get: function() { return code_2.regexpCode; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return code_2.Name; } }); var scope_2 = require_scope(); Object.defineProperty(exports2, "Scope", { enumerable: true, get: function() { return scope_2.Scope; } }); Object.defineProperty(exports2, "ValueScope", { enumerable: true, get: function() { return scope_2.ValueScope; } }); Object.defineProperty(exports2, "ValueScopeName", { enumerable: true, get: function() { return scope_2.ValueScopeName; } }); Object.defineProperty(exports2, "varKinds", { enumerable: true, get: function() { return scope_2.varKinds; } }); exports2.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+") }; var Node = class { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } }; var Def = class extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; var Assign = class extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } }; var AssignOp = class extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } }; var Label = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } }; var Break = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } }; var Throw = class extends Node { constructor(error48) { super(); this.error = error48; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } }; var AnyCode = class extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : void 0; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } }; var ParentNode = class extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } }; var BlockNode = class extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } }; var Root = class extends ParentNode { }; var Else = class extends BlockNode { }; Else.kind = "else"; var If = class _If extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof _If ? e : e.nodes; if (this.nodes.length) return this; return new _If(not(cond), e instanceof _If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return void 0; return this; } optimizeNames(names, constants) { var _a2; this.else = (_a2 = this.else) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } }; If.kind = "if"; var For = class extends BlockNode { }; For.kind = "for"; var ForLoop = class extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } }; var ForRange = class extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } }; var ForIter = class extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } }; var Func = class extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } }; Func.kind = "func"; var Return = class extends ParentNode { render(opts) { return "return " + super.render(opts); } }; Return.kind = "return"; var Try = class extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a2, _b; super.optimizeNodes(); (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a2, _b; super.optimizeNames(names, constants); (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } }; var Catch = class extends BlockNode { constructor(error48) { super(); this.error = error48; } render(opts) { return `catch(${this.error})` + super.render(opts); } }; Catch.kind = "catch"; var Finally = class extends BlockNode { render(opts) { return "finally" + super.render(opts); } }; Finally.kind = "finally"; var CodeGen = class { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== void 0 && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports2.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { this.var(name, (0, code_1._)`${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error48 = this.name("e"); this._currNode = node.catch = new Catch(error48); catchCode(error48); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error48) { return this._leafNode(new Throw(error48)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || N2 && n instanceof N2) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } }; exports2.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === void 0 || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; } exports2.not = not; var andCode = mappend(exports2.operators.AND); function and(...args) { return args.reduce(andCode); } exports2.and = and; var orCode = mappend(exports2.operators.OR); function or(...args) { return args.reduce(orCode); } exports2.or = or; function mappend(op) { return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/util.js var require_util4 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkStrictMode = exports2.getErrorPath = exports2.Type = exports2.useFunc = exports2.setEvaluated = exports2.evaluatedPropsToName = exports2.mergeEvaluated = exports2.eachItem = exports2.unescapeJsonPointer = exports2.escapeJsonPointer = exports2.escapeFragment = exports2.unescapeFragment = exports2.schemaRefOrVal = exports2.schemaHasRulesButRef = exports2.schemaHasRules = exports2.checkUnknownRules = exports2.alwaysValidSchema = exports2.toHash = void 0; var codegen_1 = require_codegen(); var code_1 = require_code(); function toHash(arr) { const hash2 = {}; for (const item of arr) hash2[item] = true; return hash2; } exports2.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports2.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports2.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports2.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports2.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._)`${schema}`; } return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports2.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports2.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports2.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports2.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports2.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports2.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { return (gen, from, to, toName) => { const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports2.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._)`${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => from === true ? true : { ...from, ...to }, resultToName: evaluatedPropsToName }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => from === true ? true : Math.max(from, to), resultToName: (gen, items) => gen.var("items", items) }) }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._)`{}`); if (ps !== void 0) setEvaluated(gen, props, ps); return props; } exports2.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); } exports2.setEvaluated = setEvaluated; var snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) }); } exports2.useFunc = useFunc; var Type; (function(Type2) { Type2[Type2["Num"] = 0] = "Num"; Type2[Type2["Str"] = 1] = "Str"; })(Type || (exports2.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { if (dataProp instanceof codegen_1.Name) { const isNumber = dataPropType === Type.Num; return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports2.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports2.checkStrictMode = checkStrictMode; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/names.js var require_names = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/names.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart") }; exports2.default = names; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/errors.js var require_errors2 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/errors.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0; var codegen_1 = require_codegen(); var util_1 = require_util4(); var names_1 = require_names(); exports2.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; exports2.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; function reportError(cxt, error48 = exports2.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error48, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._)`[${errObj}]`); } } exports2.reportError = reportError; function reportExtraError(cxt, error48 = exports2.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error48, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports2.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports2.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { if (errsCount === void 0) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); gen.assign((0, codegen_1._)`${err}.data`, data); } }); } exports2.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._)`${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, errs); gen.return(false); } } var E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; function errorObjectCode(cxt, error48, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; return errorObject(cxt, error48, errorPaths); } function errorObject(cxt, error48, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; extraErrorProps(cxt, error48, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/boolSchema.js var require_boolSchema = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.boolOrEmptySchema = exports2.topBoolOrEmptySchema = void 0; var errors_1 = require_errors2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var boolError = { message: "boolean schema is false" }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, null); gen.return(true); } } exports2.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); falseSchemaError(it); } else { gen.var(valid, true); } } exports2.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it }; (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/rules.js var require_rules = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/rules.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getRules = exports2.isJSONType = void 0; var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; var jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports2.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {} }; } exports2.getRules = getRules; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/applicability.js var require_applicability = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/applicability.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.shouldUseRule = exports2.shouldUseGroup = exports2.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports2.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports2.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a2; return schema[rule.keyword] !== void 0 || ((_a2 = rule.definition.implements) === null || _a2 === void 0 ? void 0 : _a2.some((kwd) => schema[kwd] !== void 0)); } exports2.shouldUseRule = shouldUseRule; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/dataType.js var require_dataType = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/dataType.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.reportTypeError = exports2.checkDataTypes = exports2.checkDataType = exports2.coerceAndCheckDataType = exports2.getJSONTypes = exports2.getSchemaTypes = exports2.DataType = void 0; var rules_1 = require_rules(); var applicability_1 = require_applicability(); var errors_1 = require_errors2(); var codegen_1 = require_codegen(); var util_1 = require_util4(); var DataType; (function(DataType2) { DataType2[DataType2["Correct"] = 0] = "Correct"; DataType2[DataType2["Wrong"] = 1] = "Wrong"; })(DataType || (exports2.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== void 0) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports2.getSchemaTypes = getSchemaTypes; function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports2.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports2.coerceAndCheckDataType = coerceAndCheckDataType; var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._)`${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); return; case "number": gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "integer": gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "boolean": gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._)`${data} ${EQ} null`; case "array": cond = (0, codegen_1._)`Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } } exports2.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._)`typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports2.checkDataTypes = checkDataTypes; var typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports2.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it }; } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/defaults.js var require_defaults = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/defaults.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.assignDefaults = void 0; var codegen_1 = require_codegen(); var util_1 = require_util4(); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports2.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === void 0) return; const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._)`${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/code.js var require_code2 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/code.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0; var codegen_1 = require_codegen(); var util_1 = require_util4(); var names_1 = require_names(); var util_2 = require_util4(); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); cxt.error(); }); } exports2.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); } exports2.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports2.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); } exports2.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; } exports2.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports2.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports2.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports2.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } exports2.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData] ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; } exports2.callValidateCode = callValidateCode; var newRegExp = (0, codegen_1._)`new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` }); } exports2.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._)`${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports2.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true }, schValid); gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports2.validateUnion = validateUnion; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/keyword.js var require_keyword = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/keyword.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateKeywordUsage = exports2.validSchemaType = exports2.funcKeywordCode = exports2.macroKeywordCode = void 0; var codegen_1 = require_codegen(); var names_1 = require_names(); var code_1 = require_code2(); var errors_1 = require_errors2(); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true }, valid); cxt.pass(valid, () => cxt.error(true)); } exports2.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a2; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._)`${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !("compile" in def && !$data || def.schema === false); gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a3; gen.if((0, codegen_1.not)((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid), errors); } } exports2.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); } exports2.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports2.validateKeywordUsage = validateKeywordUsage; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/subschema.js var require_subschema = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/subschema.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.extendSubschemaMode = exports2.extendSubschemaData = exports2.getSubschema = void 0; var codegen_1 = require_codegen(); var util_1 = require_util4(); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== void 0 && schema !== void 0) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== void 0) { const sch = it.schema[keyword]; return schemaProp === void 0 ? { schema: sch, schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}` } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` }; } if (schema !== void 0) { if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath }; } throw new Error('either "keyword" or "schema" must be passed'); } exports2.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== void 0 && dataProp !== void 0) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== void 0) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== void 0) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); dataContextProps(nextData); if (propertyName !== void 0) subschema.propertyName = propertyName; } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = /* @__PURE__ */ new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports2.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== void 0) subschema.compositeRule = compositeRule; if (createErrors !== void 0) subschema.createErrors = createErrors; if (allErrors !== void 0) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; subschema.jtdMetadata = jtdMetadata; } exports2.extendSubschemaMode = extendSubschemaMode; } }); // node_modules/fast-deep-equal/index.js var require_fast_deep_equal = __commonJS({ "node_modules/fast-deep-equal/index.js"(exports2, module2) { "use strict"; module2.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == "object" && typeof b == "object") { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0; ) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0; ) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } return a !== a && b !== b; }; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse/index.js var require_json_schema_traverse = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse/index.js"(exports2, module2) { "use strict"; var traverse = module2.exports = function(schema, opts, cb) { if (typeof opts == "function") { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = typeof cb == "function" ? cb : cb.pre || function() { }; var post = cb.post || function() { }; _traverse(opts, pre, post, schema, "", schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == "object" && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == "object") { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, "~0").replace(/\//g, "~1"); } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/resolve.js var require_resolve = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/resolve.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0; var util_1 = require_util4(); var equal = require_fast_deep_equal(); var traverse = require_json_schema_traverse(); var SIMPLE_INLINED = /* @__PURE__ */ new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const" ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports2.inlineRef = inlineRef; var REF_KEYWORDS = /* @__PURE__ */ new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor" ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports2.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports2._getFullPath = _getFullPath; var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports2.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports2.resolveUrl = resolveUrl; var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = /* @__PURE__ */ new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === void 0) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports2.getSchemaRefs = getSchemaRefs; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/index.js var require_validate = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getData = exports2.KeywordCxt = exports2.validateFunctionCode = void 0; var boolSchema_1 = require_boolSchema(); var dataType_1 = require_dataType(); var applicability_1 = require_applicability(); var dataType_2 = require_dataType(); var defaults_1 = require_defaults(); var keyword_1 = require_keyword(); var subschema_1 = require_subschema(); var codegen_1 = require_codegen(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util4(); var errors_1 = require_errors2(); function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports2.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; } function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults } } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); } function includesType(ts, t) { return ts.includes(t) || t === "integer" && ts.includes("number"); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } var KeywordCxt = class { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), void 0, failAction); } fail(condition) { if (condition === void 0) { this.error(); if (!this.allErrors) this.gen.if(false); return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } }; exports2.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment2 of segments) { if (segment2) { data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment2))}`; expr = (0, codegen_1._)`${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports2.getData = getData; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/validation_error.js var require_validation_error = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/validation_error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var ValidationError = class extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } }; exports2.default = ValidationError; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/ref_error.js var require_ref_error = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/ref_error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var resolve_1 = require_resolve(); var MissingRefError = class extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; exports2.default = MissingRefError; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/index.js var require_compile2 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0; var codegen_1 = require_codegen(); var validation_error_1 = require_validation_error(); var names_1 = require_names(); var resolve_1 = require_resolve(); var util_1 = require_util4(); var validate_1 = require_validate(); var SchemaEnv = class { constructor(env) { var _a2; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a2 = env.baseId) !== null && _a2 !== void 0 ? _a2 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } }; exports2.SchemaEnv = SchemaEnv; function compileSchema(sch) { const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._)`""`, opts: this.opts, self: this }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate2 = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate2 }); validate2.errors = null; validate2.schema = sch.schema; validate2.schemaEnv = sch; if (sch.$async) validate2.$async = true; if (this.opts.code.source === true) { validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; if (validate2.source) validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } sch.validate = validate2; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); throw e; } finally { this._compilations.delete(sch); } } exports2.compileSchema = compileSchema; function resolveRef2(root, baseId, ref) { var _a2; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve.call(this, root, ref); if (_sch === void 0) { const schema = (_a2 = root.localRefs) === null || _a2 === void 0 ? void 0 : _a2[ref]; const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === void 0) return; return root.refs[ref] = inlineOrCompile.call(this, _sch); } exports2.resolveRef = resolveRef2; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports2.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } function resolve(root, ref) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } function resolveSchema(root, ref) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports2.resolveSchema = resolveSchema; var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions" ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a2; if (((_a2 = parsedRef.fragment) === null || _a2 === void 0 ? void 0 : _a2[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === void 0) return; schema = partSchema; const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return void 0; } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/data.json var require_data = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/data.json"(exports2, module2) { module2.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; } }); // node_modules/fast-uri/lib/utils.js var require_utils6 = __commonJS({ "node_modules/fast-uri/lib/utils.js"(exports2, module2) { "use strict"; var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); function stringArrayToHexStripped(input) { let acc = ""; let code = 0; let i = 0; for (i = 0; i < input.length; i++) { code = input[i].charCodeAt(0); if (code === 48) { continue; } if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } acc += input[i]; break; } for (i += 1; i < input.length; i++) { code = input[i].charCodeAt(0); if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { return ""; } acc += input[i]; } return acc; } var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); function consumeIsZone(buffer) { buffer.length = 0; return true; } function consumeHextets(buffer, address, output) { if (buffer.length) { const hex3 = stringArrayToHexStripped(buffer); if (hex3 !== "") { address.push(hex3); } else { output.error = true; return false; } buffer.length = 0; } return true; } function getIPV6(input) { let tokenCount = 0; const output = { error: false, address: "", zone: "" }; const address = []; const buffer = []; let endipv6Encountered = false; let endIpv6 = false; let consume = consumeHextets; for (let i = 0; i < input.length; i++) { const cursor = input[i]; if (cursor === "[" || cursor === "]") { continue; } if (cursor === ":") { if (endipv6Encountered === true) { endIpv6 = true; } if (!consume(buffer, address, output)) { break; } if (++tokenCount > 7) { output.error = true; break; } if (i > 0 && input[i - 1] === ":") { endipv6Encountered = true; } address.push(":"); continue; } else if (cursor === "%") { if (!consume(buffer, address, output)) { break; } consume = consumeIsZone; } else { buffer.push(cursor); continue; } } if (buffer.length) { if (consume === consumeIsZone) { output.zone = buffer.join(""); } else if (endIpv6) { address.push(buffer.join("")); } else { address.push(stringArrayToHexStripped(buffer)); } } output.address = address.join(""); return output; } function normalizeIPv6(host) { if (findToken(host, ":") < 2) { return { host, isIPV6: false }; } const ipv63 = getIPV6(host); if (!ipv63.error) { let newHost = ipv63.address; let escapedHost = ipv63.address; if (ipv63.zone) { newHost += "%" + ipv63.zone; escapedHost += "%25" + ipv63.zone; } return { host: newHost, isIPV6: true, escapedHost }; } else { return { host, isIPV6: false }; } } function findToken(str, token) { let ind = 0; for (let i = 0; i < str.length; i++) { if (str[i] === token) ind++; } return ind; } function removeDotSegments(path) { let input = path; const output = []; let nextSlash = -1; let len = 0; while (len = input.length) { if (len === 1) { if (input === ".") { break; } else if (input === "/") { output.push("/"); break; } else { output.push(input); break; } } else if (len === 2) { if (input[0] === ".") { if (input[1] === ".") { break; } else if (input[1] === "/") { input = input.slice(2); continue; } } else if (input[0] === "/") { if (input[1] === "." || input[1] === "/") { output.push("/"); break; } } } else if (len === 3) { if (input === "/..") { if (output.length !== 0) { output.pop(); } output.push("/"); break; } } if (input[0] === ".") { if (input[1] === ".") { if (input[2] === "/") { input = input.slice(3); continue; } } else if (input[1] === "/") { input = input.slice(2); continue; } } else if (input[0] === "/") { if (input[1] === ".") { if (input[2] === "/") { input = input.slice(2); continue; } else if (input[2] === ".") { if (input[3] === "/") { input = input.slice(3); if (output.length !== 0) { output.pop(); } continue; } } } } if ((nextSlash = input.indexOf("/", 1)) === -1) { output.push(input); break; } else { output.push(input.slice(0, nextSlash)); input = input.slice(nextSlash); } } return output.join(""); } function normalizeComponentEncoding(component, esc2) { const func = esc2 !== true ? escape : unescape; if (component.scheme !== void 0) { component.scheme = func(component.scheme); } if (component.userinfo !== void 0) { component.userinfo = func(component.userinfo); } if (component.host !== void 0) { component.host = func(component.host); } if (component.path !== void 0) { component.path = func(component.path); } if (component.query !== void 0) { component.query = func(component.query); } if (component.fragment !== void 0) { component.fragment = func(component.fragment); } return component; } function recomposeAuthority(component) { const uriTokens = []; if (component.userinfo !== void 0) { uriTokens.push(component.userinfo); uriTokens.push("@"); } if (component.host !== void 0) { let host = unescape(component.host); if (!isIPv4(host)) { const ipV6res = normalizeIPv6(host); if (ipV6res.isIPV6 === true) { host = `[${ipV6res.escapedHost}]`; } else { host = component.host; } } uriTokens.push(host); } if (typeof component.port === "number" || typeof component.port === "string") { uriTokens.push(":"); uriTokens.push(String(component.port)); } return uriTokens.length ? uriTokens.join("") : void 0; } module2.exports = { nonSimpleDomain, recomposeAuthority, normalizeComponentEncoding, removeDotSegments, isIPv4, isUUID, normalizeIPv6, stringArrayToHexStripped }; } }); // node_modules/fast-uri/lib/schemes.js var require_schemes = __commonJS({ "node_modules/fast-uri/lib/schemes.js"(exports2, module2) { "use strict"; var { isUUID } = require_utils6(); var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; var supportedSchemeNames = ( /** @type {const} */ [ "http", "https", "ws", "wss", "urn", "urn:uuid" ] ); function isValidSchemeName(name) { return supportedSchemeNames.indexOf( /** @type {*} */ name ) !== -1; } function wsIsSecure(wsComponent) { if (wsComponent.secure === true) { return true; } else if (wsComponent.secure === false) { return false; } else if (wsComponent.scheme) { return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); } else { return false; } } function httpParse(component) { if (!component.host) { component.error = component.error || "HTTP URIs must have a host."; } return component; } function httpSerialize(component) { const secure = String(component.scheme).toLowerCase() === "https"; if (component.port === (secure ? 443 : 80) || component.port === "") { component.port = void 0; } if (!component.path) { component.path = "/"; } return component; } function wsParse(wsComponent) { wsComponent.secure = wsIsSecure(wsComponent); wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); wsComponent.path = void 0; wsComponent.query = void 0; return wsComponent; } function wsSerialize(wsComponent) { if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { wsComponent.port = void 0; } if (typeof wsComponent.secure === "boolean") { wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; wsComponent.secure = void 0; } if (wsComponent.resourceName) { const [path, query] = wsComponent.resourceName.split("?"); wsComponent.path = path && path !== "/" ? path : void 0; wsComponent.query = query; wsComponent.resourceName = void 0; } wsComponent.fragment = void 0; return wsComponent; } function urnParse(urnComponent, options) { if (!urnComponent.path) { urnComponent.error = "URN can not be parsed"; return urnComponent; } const matches = urnComponent.path.match(URN_REG); if (matches) { const scheme = options.scheme || urnComponent.scheme || "urn"; urnComponent.nid = matches[1].toLowerCase(); urnComponent.nss = matches[2]; const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; const schemeHandler = getSchemeHandler(urnScheme); urnComponent.path = void 0; if (schemeHandler) { urnComponent = schemeHandler.parse(urnComponent, options); } } else { urnComponent.error = urnComponent.error || "URN can not be parsed."; } return urnComponent; } function urnSerialize(urnComponent, options) { if (urnComponent.nid === void 0) { throw new Error("URN without nid cannot be serialized"); } const scheme = options.scheme || urnComponent.scheme || "urn"; const nid = urnComponent.nid.toLowerCase(); const urnScheme = `${scheme}:${options.nid || nid}`; const schemeHandler = getSchemeHandler(urnScheme); if (schemeHandler) { urnComponent = schemeHandler.serialize(urnComponent, options); } const uriComponent = urnComponent; const nss = urnComponent.nss; uriComponent.path = `${nid || options.nid}:${nss}`; options.skipEscape = true; return uriComponent; } function urnuuidParse(urnComponent, options) { const uuidComponent = urnComponent; uuidComponent.uuid = uuidComponent.nss; uuidComponent.nss = void 0; if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { uuidComponent.error = uuidComponent.error || "UUID is not valid."; } return uuidComponent; } function urnuuidSerialize(uuidComponent) { const urnComponent = uuidComponent; urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); return urnComponent; } var http = ( /** @type {SchemeHandler} */ { scheme: "http", domainHost: true, parse: httpParse, serialize: httpSerialize } ); var https = ( /** @type {SchemeHandler} */ { scheme: "https", domainHost: http.domainHost, parse: httpParse, serialize: httpSerialize } ); var ws2 = ( /** @type {SchemeHandler} */ { scheme: "ws", domainHost: true, parse: wsParse, serialize: wsSerialize } ); var wss = ( /** @type {SchemeHandler} */ { scheme: "wss", domainHost: ws2.domainHost, parse: ws2.parse, serialize: ws2.serialize } ); var urn = ( /** @type {SchemeHandler} */ { scheme: "urn", parse: urnParse, serialize: urnSerialize, skipNormalize: true } ); var urnuuid = ( /** @type {SchemeHandler} */ { scheme: "urn:uuid", parse: urnuuidParse, serialize: urnuuidSerialize, skipNormalize: true } ); var SCHEMES = ( /** @type {Record} */ { http, https, ws: ws2, wss, urn, "urn:uuid": urnuuid } ); Object.setPrototypeOf(SCHEMES, null); function getSchemeHandler(scheme) { return scheme && (SCHEMES[ /** @type {SchemeName} */ scheme ] || SCHEMES[ /** @type {SchemeName} */ scheme.toLowerCase() ]) || void 0; } module2.exports = { wsIsSecure, SCHEMES, isValidSchemeName, getSchemeHandler }; } }); // node_modules/fast-uri/index.js var require_fast_uri = __commonJS({ "node_modules/fast-uri/index.js"(exports2, module2) { "use strict"; var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils6(); var { SCHEMES, getSchemeHandler } = require_schemes(); function normalize(uri, options) { if (typeof uri === "string") { uri = /** @type {T} */ serialize(parse3(uri, options), options); } else if (typeof uri === "object") { uri = /** @type {T} */ parse3(serialize(uri, options), options); } return uri; } function resolve(baseURI, relativeURI, options) { const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true); schemelessOptions.skipEscape = true; return serialize(resolved, schemelessOptions); } function resolveComponent(base, relative, options, skipNormalization) { const target = {}; if (!skipNormalization) { base = parse3(serialize(base, options), options); relative = parse3(serialize(relative, options), options); } options = options || {}; if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme; target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (!relative.path) { target.path = base.path; if (relative.query !== void 0) { target.query = relative.query; } else { target.query = base.query; } } else { if (relative.path[0] === "/") { target.path = removeDotSegments(relative.path); } else { if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { target.path = "/" + relative.path; } else if (!base.path) { target.path = relative.path; } else { target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; } target.path = removeDotSegments(target.path); } target.query = relative.query; } target.userinfo = base.userinfo; target.host = base.host; target.port = base.port; } target.scheme = base.scheme; } target.fragment = relative.fragment; return target; } function equal(uriA, uriB, options) { if (typeof uriA === "string") { uriA = unescape(uriA); uriA = serialize(normalizeComponentEncoding(parse3(uriA, options), true), { ...options, skipEscape: true }); } else if (typeof uriA === "object") { uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); } if (typeof uriB === "string") { uriB = unescape(uriB); uriB = serialize(normalizeComponentEncoding(parse3(uriB, options), true), { ...options, skipEscape: true }); } else if (typeof uriB === "object") { uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); } return uriA.toLowerCase() === uriB.toLowerCase(); } function serialize(cmpts, opts) { const component = { host: cmpts.host, scheme: cmpts.scheme, userinfo: cmpts.userinfo, port: cmpts.port, path: cmpts.path, query: cmpts.query, nid: cmpts.nid, nss: cmpts.nss, uuid: cmpts.uuid, fragment: cmpts.fragment, reference: cmpts.reference, resourceName: cmpts.resourceName, secure: cmpts.secure, error: "" }; const options = Object.assign({}, opts); const uriTokens = []; const schemeHandler = getSchemeHandler(options.scheme || component.scheme); if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); if (component.path !== void 0) { if (!options.skipEscape) { component.path = escape(component.path); if (component.scheme !== void 0) { component.path = component.path.split("%3A").join(":"); } } else { component.path = unescape(component.path); } } if (options.reference !== "suffix" && component.scheme) { uriTokens.push(component.scheme, ":"); } const authority = recomposeAuthority(component); if (authority !== void 0) { if (options.reference !== "suffix") { uriTokens.push("//"); } uriTokens.push(authority); if (component.path && component.path[0] !== "/") { uriTokens.push("/"); } } if (component.path !== void 0) { let s = component.path; if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { s = removeDotSegments(s); } if (authority === void 0 && s[0] === "/" && s[1] === "/") { s = "/%2F" + s.slice(2); } uriTokens.push(s); } if (component.query !== void 0) { uriTokens.push("?", component.query); } if (component.fragment !== void 0) { uriTokens.push("#", component.fragment); } return uriTokens.join(""); } var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; function parse3(uri, opts) { const options = Object.assign({}, opts); const parsed = { scheme: void 0, userinfo: void 0, host: "", port: void 0, path: "", query: void 0, fragment: void 0 }; let isIP = false; if (options.reference === "suffix") { if (options.scheme) { uri = options.scheme + ":" + uri; } else { uri = "//" + uri; } } const matches = uri.match(URI_PARSE); if (matches) { parsed.scheme = matches[1]; parsed.userinfo = matches[3]; parsed.host = matches[4]; parsed.port = parseInt(matches[5], 10); parsed.path = matches[6] || ""; parsed.query = matches[7]; parsed.fragment = matches[8]; if (isNaN(parsed.port)) { parsed.port = matches[5]; } if (parsed.host) { const ipv4result = isIPv4(parsed.host); if (ipv4result === false) { const ipv6result = normalizeIPv6(parsed.host); parsed.host = ipv6result.host.toLowerCase(); isIP = ipv6result.isIPV6; } else { isIP = true; } } if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { parsed.reference = "same-document"; } else if (parsed.scheme === void 0) { parsed.reference = "relative"; } else if (parsed.fragment === void 0) { parsed.reference = "absolute"; } else { parsed.reference = "uri"; } if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; } const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { try { parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); } catch (e) { parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; } } } if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { if (uri.indexOf("%") !== -1) { if (parsed.scheme !== void 0) { parsed.scheme = unescape(parsed.scheme); } if (parsed.host !== void 0) { parsed.host = unescape(parsed.host); } } if (parsed.path) { parsed.path = escape(unescape(parsed.path)); } if (parsed.fragment) { parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); } } if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(parsed, options); } } else { parsed.error = parsed.error || "URI can not be parsed."; } return parsed; } var fastUri = { SCHEMES, normalize, resolve, resolveComponent, equal, serialize, parse: parse3 }; module2.exports = fastUri; module2.exports.default = fastUri; module2.exports.fastUri = fastUri; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/uri.js var require_uri = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/uri.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var uri = require_fast_uri(); uri.code = 'require("ajv/dist/runtime/uri").default'; exports2.default = uri; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/core.js var require_core = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/core.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0; var validate_1 = require_validate(); Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); var ref_error_1 = require_ref_error(); var rules_1 = require_rules(); var compile_1 = require_compile2(); var codegen_2 = require_codegen(); var resolve_1 = require_resolve(); var dataType_1 = require_dataType(); var util_1 = require_util4(); var $dataRefSchema = require_data(); var uri_1 = require_uri(); var defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error" ]); var removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }; var deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; var MAX_EXPRESSION = 200; function requiredOptions(o) { var _a2, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a2 = o.code) === null || _a2 === void 0 ? void 0 : _a2.optimize; const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver }; } var Ajv2 = class { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = {}; this._compilations = /* @__PURE__ */ new Set(); this._loading = {}; this._cache = /* @__PURE__ */ new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta: meta3, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta3 && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta: meta3, schemaId } = this.opts; return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; } validate(schemaKeyRef, data) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return sch.validate || this._compileSchemaEnv(sch); } compileAsync(schema, meta3) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta3); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta3); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== void 0 && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== void 0 && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === void 0) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return sch.validate || this._compileSchemaEnv(sch); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey2 = schemaKeyRef; this._cache.delete(cacheKey2); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === void 0) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { if (!errors || errors.length === 0) return "No errors"; return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== void 0) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } }; Ajv2.ValidationError = validation_error_1.default; Ajv2.MissingRefError = ref_error_1.default; exports2.default = Ajv2; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } var noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === void 0) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a2; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a2 = definition.implements) === null || _a2 === void 0 ? void 0 : _a2.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === void 0) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/id.js var require_id = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/id.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/ref.js var require_ref = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.callRef = exports2.getValidate = void 0; var ref_error_1 = require_ref_error(); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var compile_1 = require_compile2(); var util_1 = require_util4(); var def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } } }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports2.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._)`${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a2; if (!it.opts.unevaluated) return; const schEvaluated = (_a2 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a2 === void 0 ? void 0 : _a2.evaluated; if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } exports2.callRef = callRef; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/index.js var require_core2 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var id_1 = require_id(); var ref_1 = require_ref(); var core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default ]; exports2.default = core; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitNumber.js var require_limitNumber = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error48 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; var def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/multipleOf.js var require_multipleOf = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error48 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; var def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error: error48, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/ucs2length.js var require_ucs2length = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/ucs2length.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 55296 && value <= 56319 && pos < len) { value = str.charCodeAt(pos); if ((value & 64512) === 56320) pos++; } } return length; } exports2.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitLength.js var require_limitLength = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var ucs2length_1 = require_ucs2length(); var error48 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/pattern.js var require_pattern = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var util_1 = require_util4(); var codegen_1 = require_codegen(); var error48 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; var def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error: error48, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; if ($data) { const { regExp } = it.opts.code; const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); const valid = gen.let("valid"); gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); cxt.fail$data((0, codegen_1._)`!${valid}`); } else { const regExp = (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitProperties.js var require_limitProperties = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error48 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/required.js var require_required = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util4(); var error48 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; var def = { keyword: "required", type: "object", schemaType: "array", $data: true, error: error48, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitItems.js var require_limitItems = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error48 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/equal.js var require_equal = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/equal.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var equal = require_fast_deep_equal(); equal.code = 'require("ajv/dist/runtime/equal").default'; exports2.default = equal; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js var require_uniqueItems = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var dataType_1 = require_dataType(); var codegen_1 = require_codegen(); var util_1 = require_util4(); var equal_1 = require_equal(); var error48 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; var def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error: error48, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._)`${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._)`{}`); gen.for((0, codegen_1._)`;${i}--;`, () => { gen.let(item, (0, codegen_1._)`${data}[${i}]`); gen.if(wrongType, (0, codegen_1._)`continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/const.js var require_const = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/const.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var equal_1 = require_equal(); var error48 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, error: error48, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._)`${schema} !== ${data}`); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/enum.js var require_enum = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var equal_1 = require_equal(); var error48 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", $data: true, error: error48, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/index.js var require_validation2 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var limitNumber_1 = require_limitNumber(); var multipleOf_1 = require_multipleOf(); var limitLength_1 = require_limitLength(); var pattern_1 = require_pattern(); var limitProperties_1 = require_limitProperties(); var required_1 = require_required(); var limitItems_1 = require_limitItems(); var uniqueItems_1 = require_uniqueItems(); var const_1 = require_const(); var enum_1 = require_enum(); var validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default ]; exports2.default = validation; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js var require_additionalItems = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateAdditionalItems = void 0; var codegen_1 = require_codegen(); var util_1 = require_util4(); var error48 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error: error48, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); } }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._)`${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports2.validateAdditionalItems = validateAdditionalItems; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items.js var require_items = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateTuple = void 0; var codegen_1 = require_codegen(); var util_1 = require_util4(); var code_1 = require_code2(); var def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); } }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._)`${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports2.validateTuple = validateTuple; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js var require_prefixItems = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var items_1 = require_items(); var def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items2020.js var require_items2020 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var code_1 = require_code2(); var additionalItems_1 = require_additionalItems(); var error48 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error: error48, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/contains.js var require_contains = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var error48 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; var def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error: error48, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === void 0 ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._)`${data}.length`); cxt.setParams({ min, max }); if (max === void 0 && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== void 0 && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._)`${len} >= ${min}`; if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === void 0 && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._)`${count}++`); if (max === void 0) { gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); } } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/dependencies.js var require_dependencies = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0; var codegen_1 = require_codegen(); var util_1 = require_util4(); var code_1 = require_code2(); exports2.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}` // TODO change to reference }; var def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports2.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); } }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", ") }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports2.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if( (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports2.validateSchemaDeps = validateSchemaDeps; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js var require_propertyNames = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var error48 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; var def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error: error48, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js var require_additionalProperties = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var names_1 = require_names(); var util_1 = require_util4(); var error48 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; var def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error: error48, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false }); } cxt.subschema(subschema, valid); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/properties.js var require_properties = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var validate_1 = require_validate(); var code_1 = require_code2(); var util_1 = require_util4(); var additionalProperties_1 = require_additionalProperties(); var def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop }, valid); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js var require_patternProperties = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var codegen_1 = require_codegen(); var util_1 = require_util4(); var util_2 = require_util4(); var def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._)`${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/not.js var require_not = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util4(); var def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/anyOf.js var require_anyOf = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code2(); var def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/oneOf.js var require_oneOf = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var error48 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; var def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error: error48, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true }, schValid); } if (i > 0) { gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/allOf.js var require_allOf = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util4(); var def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/if.js var require_if = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util4(); var error48 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; var def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error: error48, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } } }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); } exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/thenElse.js var require_thenElse = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util4(); var def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/index.js var require_applicator = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var additionalItems_1 = require_additionalItems(); var prefixItems_1 = require_prefixItems(); var items_1 = require_items(); var items2020_1 = require_items2020(); var contains_1 = require_contains(); var dependencies_1 = require_dependencies(); var propertyNames_1 = require_propertyNames(); var additionalProperties_1 = require_additionalProperties(); var properties_1 = require_properties(); var patternProperties_1 = require_patternProperties(); var not_1 = require_not(); var anyOf_1 = require_anyOf(); var oneOf_1 = require_oneOf(); var allOf_1 = require_allOf(); var if_1 = require_if(); var thenElse_1 = require_thenElse(); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default ]; if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports2.default = getApplicator; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/format.js var require_format = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/format.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var error48 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; var def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error: error48, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._)`${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._)`await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/index.js var require_format2 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var format_1 = require_format(); var format = [format_1.default]; exports2.default = format; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/metadata.js var require_metadata = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/metadata.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.contentVocabulary = exports2.metadataVocabulary = void 0; exports2.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples" ]; exports2.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema" ]; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/draft7.js var require_draft7 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/draft7.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var core_1 = require_core2(); var validation_1 = require_validation2(); var applicator_1 = require_applicator(); var format_1 = require_format2(); var metadata_1 = require_metadata(); var draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary ]; exports2.default = draft7Vocabularies; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/types.js var require_types2 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DiscrError = void 0; var DiscrError; (function(DiscrError2) { DiscrError2["Tag"] = "tag"; DiscrError2["Mapping"] = "mapping"; })(DiscrError || (exports2.DiscrError = DiscrError = {})); } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/index.js var require_discriminator = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen(); var types_1 = require_types2(); var compile_1 = require_compile2(); var ref_error_1 = require_ref_error(); var util_1 = require_util4(); var error48 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; var def = { keyword: "discriminator", type: "object", schemaType: "object", error: error48, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a2; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a2 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a2 === void 0 ? void 0 : _a2[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required: required2 }) { return Array.isArray(required2) && required2.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } } }; exports2.default = def; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/json-schema-draft-07.json var require_json_schema_draft_07 = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports2, module2) { module2.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [ { $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true } ] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; } }); // node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/ajv.js var require_ajv = __commonJS({ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/ajv.js"(exports2, module2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MissingRefError = exports2.ValidationError = exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = exports2.Ajv = void 0; var core_1 = require_core(); var draft7_1 = require_draft7(); var discriminator_1 = require_discriminator(); var draft7MetaSchema = require_json_schema_draft_07(); var META_SUPPORT_DATA = ["/properties"]; var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; var Ajv2 = class extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; exports2.Ajv = Ajv2; module2.exports = exports2 = Ajv2; module2.exports.Ajv = Ajv2; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = Ajv2; var validate_1 = require_validate(); Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error(); Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error(); Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/ajv-formats/dist/formats.js var require_formats = __commonJS({ "node_modules/ajv-formats/dist/formats.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.formatNames = exports2.fastFormats = exports2.fullFormats = void 0; function fmtDef(validate2, compare) { return { validate: validate2, compare }; } exports2.fullFormats = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: fmtDef(date5, compareDate), // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: fmtDef(getTime(true), compareTime), "date-time": fmtDef(getDateTime(true), compareDateTime), "iso-time": fmtDef(getTime(), compareIsoTime), "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), // duration: https://tools.ietf.org/html/rfc3339#appendix-A duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, // uri-template: https://tools.ietf.org/html/rfc6570 "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types // byte: https://github.com/miguelmota/is-base64 byte, // signed 32 bit integer int32: { type: "number", validate: validateInt32 }, // signed 64 bit integer int64: { type: "number", validate: validateInt64 }, // C-type float float: { type: "number", validate: validateNumber }, // C-type double double: { type: "number", validate: validateNumber }, // hint to the UI to hide input strings password: true, // unchecked string payload binary: true }; exports2.fastFormats = { ...exports2.fullFormats, date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i }; exports2.formatNames = Object.keys(exports2.fullFormats); function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function date5(str) { const matches = DATE.exec(str); if (!matches) return false; const year = +matches[1]; const month = +matches[2]; const day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); } function compareDate(d1, d2) { if (!(d1 && d2)) return void 0; if (d1 > d2) return 1; if (d1 < d2) return -1; return 0; } var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; function getTime(strictTimeZone) { return function time3(str) { const matches = TIME.exec(str); if (!matches) return false; const hr = +matches[1]; const min = +matches[2]; const sec = +matches[3]; const tz = matches[4]; const tzSign = matches[5] === "-" ? -1 : 1; const tzH = +(matches[6] || 0); const tzM = +(matches[7] || 0); if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; if (hr <= 23 && min <= 59 && sec < 60) return true; const utcMin = min - tzM * tzSign; const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; }; } function compareTime(s1, s2) { if (!(s1 && s2)) return void 0; const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); if (!(t1 && t2)) return void 0; return t1 - t2; } function compareIsoTime(t1, t2) { if (!(t1 && t2)) return void 0; const a1 = TIME.exec(t1); const a2 = TIME.exec(t2); if (!(a1 && a2)) return void 0; t1 = a1[1] + a1[2] + a1[3]; t2 = a2[1] + a2[2] + a2[3]; if (t1 > t2) return 1; if (t1 < t2) return -1; return 0; } var DATE_TIME_SEPARATOR = /t|\s/i; function getDateTime(strictTimeZone) { const time3 = getTime(strictTimeZone); return function date_time(str) { const dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length === 2 && date5(dateTime[0]) && time3(dateTime[1]); }; } function compareDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const d1 = new Date(dt1).valueOf(); const d2 = new Date(dt2).valueOf(); if (!(d1 && d2)) return void 0; return d1 - d2; } function compareIsoDateTime(dt1, dt2) { if (!(dt1 && dt2)) return void 0; const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); const res = compareDate(d1, d2); if (res === void 0) return void 0; return res || compareTime(t1, t2); } var NOT_URI_FRAGMENT = /\/|:/; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; function uri(str) { return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; function byte(str) { BYTE.lastIndex = 0; return BYTE.test(str); } var MIN_INT32 = -(2 ** 31); var MAX_INT32 = 2 ** 31 - 1; function validateInt32(value) { return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; } function validateInt64(value) { return Number.isInteger(value); } function validateNumber() { return true; } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch (e) { return false; } } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js var require_code3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.regexpCode = exports2.getEsmExportName = exports2.getProperty = exports2.safeStringify = exports2.stringify = exports2.strConcat = exports2.addCodeArg = exports2.str = exports2._ = exports2.nil = exports2._Code = exports2.Name = exports2.IDENTIFIER = exports2._CodeOrName = void 0; var _CodeOrName = class { }; exports2._CodeOrName = _CodeOrName; exports2.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var Name = class extends _CodeOrName { constructor(s) { super(); if (!exports2.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); this.str = s; } toString() { return this.str; } emptyStr() { return false; } get names() { return { [this.str]: 1 }; } }; exports2.Name = Name; var _Code = class extends _CodeOrName { constructor(code) { super(); this._items = typeof code === "string" ? [code] : code; } toString() { return this.str; } emptyStr() { if (this._items.length > 1) return false; const item = this._items[0]; return item === "" || item === '""'; } get str() { var _a2; return (_a2 = this._str) !== null && _a2 !== void 0 ? _a2 : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); } get names() { var _a2; return (_a2 = this._names) !== null && _a2 !== void 0 ? _a2 : this._names = this._items.reduce((names, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; return names; }, {}); } }; exports2._Code = _Code; exports2.nil = new _Code(""); function _(strs, ...args) { const code = [strs[0]]; let i = 0; while (i < args.length) { addCodeArg(code, args[i]); code.push(strs[++i]); } return new _Code(code); } exports2._ = _; var plus = new _Code("+"); function str(strs, ...args) { const expr = [safeStringify(strs[0])]; let i = 0; while (i < args.length) { expr.push(plus); addCodeArg(expr, args[i]); expr.push(plus, safeStringify(strs[++i])); } optimize(expr); return new _Code(expr); } exports2.str = str; function addCodeArg(code, arg) { if (arg instanceof _Code) code.push(...arg._items); else if (arg instanceof Name) code.push(arg); else code.push(interpolate(arg)); } exports2.addCodeArg = addCodeArg; function optimize(expr) { let i = 1; while (i < expr.length - 1) { if (expr[i] === plus) { const res = mergeExprItems(expr[i - 1], expr[i + 1]); if (res !== void 0) { expr.splice(i - 1, 3, res); continue; } expr[i++] = "+"; } i++; } } function mergeExprItems(a, b) { if (b === '""') return a; if (a === '""') return b; if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return; if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; if (b[0] === '"') return a.slice(0, -1) + b.slice(1); return; } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; return; } function strConcat(c1, c2) { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; } exports2.strConcat = strConcat; function interpolate(x) { return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); } function stringify(x) { return new _Code(safeStringify(x)); } exports2.stringify = stringify; function safeStringify(x) { return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); } exports2.safeStringify = safeStringify; function getProperty(key) { return typeof key == "string" && exports2.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; } exports2.getProperty = getProperty; function getEsmExportName(key) { if (typeof key == "string" && exports2.IDENTIFIER.test(key)) { return new _Code(`${key}`); } throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); } exports2.getEsmExportName = getEsmExportName; function regexpCode(rx) { return new _Code(rx.toString()); } exports2.regexpCode = regexpCode; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js var require_scope2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ValueScope = exports2.ValueScopeName = exports2.Scope = exports2.varKinds = exports2.UsedValueState = void 0; var code_1 = require_code3(); var ValueError = class extends Error { constructor(name) { super(`CodeGen: "code" for ${name} not defined`); this.value = name.value; } }; var UsedValueState; (function(UsedValueState2) { UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; })(UsedValueState || (exports2.UsedValueState = UsedValueState = {})); exports2.varKinds = { const: new code_1.Name("const"), let: new code_1.Name("let"), var: new code_1.Name("var") }; var Scope = class { constructor({ prefixes, parent } = {}) { this._names = {}; this._prefixes = prefixes; this._parent = parent; } toName(nameOrPrefix) { return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } name(prefix) { return new code_1.Name(this._newName(prefix)); } _newName(prefix) { const ng = this._names[prefix] || this._nameGroup(prefix); return `${prefix}${ng.index++}`; } _nameGroup(prefix) { var _a2, _b; if (((_b = (_a2 = this._parent) === null || _a2 === void 0 ? void 0 : _a2._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } return this._names[prefix] = { prefix, index: 0 }; } }; exports2.Scope = Scope; var ValueScopeName = class extends code_1.Name { constructor(prefix, nameStr) { super(nameStr); this.prefix = prefix; } setValue(value, { property, itemIndex }) { this.value = value; this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; } }; exports2.ValueScopeName = ValueScopeName; var line = (0, code_1._)`\n`; var ValueScope = class extends Scope { constructor(opts) { super(opts); this._values = {}; this._scope = opts.scope; this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; } get() { return this._scope; } name(prefix) { return new ValueScopeName(prefix, this._newName(prefix)); } value(nameOrPrefix, value) { var _a2; if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); const name = this.toName(nameOrPrefix); const { prefix } = name; const valueKey = (_a2 = value.key) !== null && _a2 !== void 0 ? _a2 : value.ref; let vs = this._values[prefix]; if (vs) { const _name = vs.get(valueKey); if (_name) return _name; } else { vs = this._values[prefix] = /* @__PURE__ */ new Map(); } vs.set(valueKey, name); const s = this._scope[prefix] || (this._scope[prefix] = []); const itemIndex = s.length; s[itemIndex] = value.ref; name.setValue(value, { property: prefix, itemIndex }); return name; } getValue(prefix, keyOrRef) { const vs = this._values[prefix]; if (!vs) return; return vs.get(keyOrRef); } scopeRefs(scopeName, values = this._values) { return this._reduceValues(values, (name) => { if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return (0, code_1._)`${scopeName}${name.scopePath}`; }); } scopeCode(values = this._values, usedValues, getCode) { return this._reduceValues(values, (name) => { if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); return name.value.code; }, usedValues, getCode); } _reduceValues(values, valueCode, usedValues = {}, getCode) { let code = code_1.nil; for (const prefix in values) { const vs = values[prefix]; if (!vs) continue; const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); vs.forEach((name) => { if (nameSet.has(name)) return; nameSet.set(name, UsedValueState.Started); let c = valueCode(name); if (c) { const def = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const; code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { code = (0, code_1._)`${code}${c}${this.opts._n}`; } else { throw new ValueError(name); } nameSet.set(name, UsedValueState.Completed); }); } return code; } }; exports2.ValueScope = ValueScope; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js var require_codegen2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.or = exports2.and = exports2.not = exports2.CodeGen = exports2.operators = exports2.varKinds = exports2.ValueScopeName = exports2.ValueScope = exports2.Scope = exports2.Name = exports2.regexpCode = exports2.stringify = exports2.getProperty = exports2.nil = exports2.strConcat = exports2.str = exports2._ = void 0; var code_1 = require_code3(); var scope_1 = require_scope2(); var code_2 = require_code3(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return code_2._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return code_2.str; } }); Object.defineProperty(exports2, "strConcat", { enumerable: true, get: function() { return code_2.strConcat; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return code_2.nil; } }); Object.defineProperty(exports2, "getProperty", { enumerable: true, get: function() { return code_2.getProperty; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return code_2.stringify; } }); Object.defineProperty(exports2, "regexpCode", { enumerable: true, get: function() { return code_2.regexpCode; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return code_2.Name; } }); var scope_2 = require_scope2(); Object.defineProperty(exports2, "Scope", { enumerable: true, get: function() { return scope_2.Scope; } }); Object.defineProperty(exports2, "ValueScope", { enumerable: true, get: function() { return scope_2.ValueScope; } }); Object.defineProperty(exports2, "ValueScopeName", { enumerable: true, get: function() { return scope_2.ValueScopeName; } }); Object.defineProperty(exports2, "varKinds", { enumerable: true, get: function() { return scope_2.varKinds; } }); exports2.operators = { GT: new code_1._Code(">"), GTE: new code_1._Code(">="), LT: new code_1._Code("<"), LTE: new code_1._Code("<="), EQ: new code_1._Code("==="), NEQ: new code_1._Code("!=="), NOT: new code_1._Code("!"), OR: new code_1._Code("||"), AND: new code_1._Code("&&"), ADD: new code_1._Code("+") }; var Node = class { optimizeNodes() { return this; } optimizeNames(_names, _constants) { return this; } }; var Def = class extends Node { constructor(varKind, name, rhs) { super(); this.varKind = varKind; this.name = name; this.rhs = rhs; } render({ es5, _n }) { const varKind = es5 ? scope_1.varKinds.var : this.varKind; const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; return `${varKind} ${this.name}${rhs};` + _n; } optimizeNames(names, constants) { if (!names[this.name.str]) return; if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; var Assign = class extends Node { constructor(lhs, rhs, sideEffects) { super(); this.lhs = lhs; this.rhs = rhs; this.sideEffects = sideEffects; } render({ _n }) { return `${this.lhs} = ${this.rhs};` + _n; } optimizeNames(names, constants) { if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; this.rhs = optimizeExpr(this.rhs, names, constants); return this; } get names() { const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; return addExprNames(names, this.rhs); } }; var AssignOp = class extends Assign { constructor(lhs, op, rhs, sideEffects) { super(lhs, rhs, sideEffects); this.op = op; } render({ _n }) { return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } }; var Label = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { return `${this.label}:` + _n; } }; var Break = class extends Node { constructor(label) { super(); this.label = label; this.names = {}; } render({ _n }) { const label = this.label ? ` ${this.label}` : ""; return `break${label};` + _n; } }; var Throw = class extends Node { constructor(error48) { super(); this.error = error48; } render({ _n }) { return `throw ${this.error};` + _n; } get names() { return this.error.names; } }; var AnyCode = class extends Node { constructor(code) { super(); this.code = code; } render({ _n }) { return `${this.code};` + _n; } optimizeNodes() { return `${this.code}` ? this : void 0; } optimizeNames(names, constants) { this.code = optimizeExpr(this.code, names, constants); return this; } get names() { return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } }; var ParentNode = class extends Node { constructor(nodes = []) { super(); this.nodes = nodes; } render(opts) { return this.nodes.reduce((code, n) => code + n.render(opts), ""); } optimizeNodes() { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i].optimizeNodes(); if (Array.isArray(n)) nodes.splice(i, 1, ...n); else if (n) nodes[i] = n; else nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } optimizeNames(names, constants) { const { nodes } = this; let i = nodes.length; while (i--) { const n = nodes[i]; if (n.optimizeNames(names, constants)) continue; subtractNames(names, n.names); nodes.splice(i, 1); } return nodes.length > 0 ? this : void 0; } get names() { return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } }; var BlockNode = class extends ParentNode { render(opts) { return "{" + opts._n + super.render(opts) + "}" + opts._n; } }; var Root = class extends ParentNode { }; var Else = class extends BlockNode { }; Else.kind = "else"; var If = class _If extends BlockNode { constructor(condition, nodes) { super(nodes); this.condition = condition; } render(opts) { let code = `if(${this.condition})` + super.render(opts); if (this.else) code += "else " + this.else.render(opts); return code; } optimizeNodes() { super.optimizeNodes(); const cond = this.condition; if (cond === true) return this.nodes; let e = this.else; if (e) { const ns = e.optimizeNodes(); e = this.else = Array.isArray(ns) ? new Else(ns) : ns; } if (e) { if (cond === false) return e instanceof _If ? e : e.nodes; if (this.nodes.length) return this; return new _If(not(cond), e instanceof _If ? [e] : e.nodes); } if (cond === false || !this.nodes.length) return void 0; return this; } optimizeNames(names, constants) { var _a2; this.else = (_a2 = this.else) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names, constants); if (!(super.optimizeNames(names, constants) || this.else)) return; this.condition = optimizeExpr(this.condition, names, constants); return this; } get names() { const names = super.names; addExprNames(names, this.condition); if (this.else) addNames(names, this.else.names); return names; } }; If.kind = "if"; var For = class extends BlockNode { }; For.kind = "for"; var ForLoop = class extends For { constructor(iteration) { super(); this.iteration = iteration; } render(opts) { return `for(${this.iteration})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iteration = optimizeExpr(this.iteration, names, constants); return this; } get names() { return addNames(super.names, this.iteration.names); } }; var ForRange = class extends For { constructor(varKind, name, from, to) { super(); this.varKind = varKind; this.name = name; this.from = from; this.to = to; } render(opts) { const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; const { name, from, to } = this; return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); } get names() { const names = addExprNames(super.names, this.from); return addExprNames(names, this.to); } }; var ForIter = class extends For { constructor(loop, varKind, name, iterable) { super(); this.loop = loop; this.varKind = varKind; this.name = name; this.iterable = iterable; } render(opts) { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } optimizeNames(names, constants) { if (!super.optimizeNames(names, constants)) return; this.iterable = optimizeExpr(this.iterable, names, constants); return this; } get names() { return addNames(super.names, this.iterable.names); } }; var Func = class extends BlockNode { constructor(name, args, async) { super(); this.name = name; this.args = args; this.async = async; } render(opts) { const _async = this.async ? "async " : ""; return `${_async}function ${this.name}(${this.args})` + super.render(opts); } }; Func.kind = "func"; var Return = class extends ParentNode { render(opts) { return "return " + super.render(opts); } }; Return.kind = "return"; var Try = class extends BlockNode { render(opts) { let code = "try" + super.render(opts); if (this.catch) code += this.catch.render(opts); if (this.finally) code += this.finally.render(opts); return code; } optimizeNodes() { var _a2, _b; super.optimizeNodes(); (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNodes(); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); return this; } optimizeNames(names, constants) { var _a2, _b; super.optimizeNames(names, constants); (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names, constants); (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); return this; } get names() { const names = super.names; if (this.catch) addNames(names, this.catch.names); if (this.finally) addNames(names, this.finally.names); return names; } }; var Catch = class extends BlockNode { constructor(error48) { super(); this.error = error48; } render(opts) { return `catch(${this.error})` + super.render(opts); } }; Catch.kind = "catch"; var Finally = class extends BlockNode { render(opts) { return "finally" + super.render(opts); } }; Finally.kind = "finally"; var CodeGen = class { constructor(extScope, opts = {}) { this._values = {}; this._blockStarts = []; this._constants = {}; this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; this._extScope = extScope; this._scope = new scope_1.Scope({ parent: extScope }); this._nodes = [new Root()]; } toString() { return this._root.render(this.opts); } // returns unique name in the internal scope name(prefix) { return this._scope.name(prefix); } // reserves unique name in the external scope scopeName(prefix) { return this._extScope.name(prefix); } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName, value) { const name = this._extScope.value(prefixOrName, value); const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); vs.add(name); return name; } getScopeValue(prefix, keyOrRef) { return this._extScope.getValue(prefix, keyOrRef); } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName) { return this._extScope.scopeRefs(scopeName, this._values); } scopeCode() { return this._extScope.scopeCode(this._values); } _def(varKind, nameOrPrefix, rhs, constant) { const name = this._scope.toName(nameOrPrefix); if (rhs !== void 0 && constant) this._constants[name.str] = rhs; this._leafNode(new Def(varKind, name, rhs)); return name; } // `const` declaration (`var` in es5 mode) const(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } // `var` declaration with optional assignment var(nameOrPrefix, rhs, _constant) { return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } // assignment code assign(lhs, rhs, sideEffects) { return this._leafNode(new Assign(lhs, rhs, sideEffects)); } // `+=` code add(lhs, rhs) { return this._leafNode(new AssignOp(lhs, exports2.operators.ADD, rhs)); } // appends passed SafeExpr to code or executes Block code(c) { if (typeof c == "function") c(); else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); return this; } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues) { const code = ["{"]; for (const [key, value] of keyValues) { if (code.length > 1) code.push(","); code.push(key); if (key !== value || this.opts.es5) { code.push(":"); (0, code_1.addCodeArg)(code, value); } } code.push("}"); return new code_1._Code(code); } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition, thenBody, elseBody) { this._blockNode(new If(condition)); if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf(); } else if (thenBody) { this.code(thenBody).endIf(); } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body'); } return this; } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition) { return this._elseNode(new If(condition)); } // `else` clause - only valid after `if` or `else if` clauses else() { return this._elseNode(new Else()); } // end `if` statement (needed if gen.if was used only with condition) endIf() { return this._endBlockNode(If, Else); } _for(node, forBody) { this._blockNode(node); if (forBody) this.code(forBody).endFor(); return this; } // a generic `for` clause (or statement if `forBody` is passed) for(iteration, forBody) { return this._for(new ForLoop(iteration), forBody); } // `for` statement for a range of values forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { const name = this._scope.toName(nameOrPrefix); return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); } // `for-of` statement (in es5 mode replace with a normal for loop) forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { const name = this._scope.toName(nameOrPrefix); if (this.opts.es5) { const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { this.var(name, (0, code_1._)`${arr}[${i}]`); forBody(name); }); } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } const name = this._scope.toName(nameOrPrefix); return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); } // end `for` loop endFor() { return this._endBlockNode(For); } // `label` statement label(label) { return this._leafNode(new Label(label)); } // `break` statement break(label) { return this._leafNode(new Break(label)); } // `return` statement return(value) { const node = new Return(); this._blockNode(node); this.code(value); if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); return this._endBlockNode(Return); } // `try` statement try(tryBody, catchCode, finallyCode) { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); const node = new Try(); this._blockNode(node); this.code(tryBody); if (catchCode) { const error48 = this.name("e"); this._currNode = node.catch = new Catch(error48); catchCode(error48); } if (finallyCode) { this._currNode = node.finally = new Finally(); this.code(finallyCode); } return this._endBlockNode(Catch, Finally); } // `throw` statement throw(error48) { return this._leafNode(new Throw(error48)); } // start self-balancing block block(body, nodeCount) { this._blockStarts.push(this._nodes.length); if (body) this.code(body).endBlock(nodeCount); return this; } // end the current self-balancing block endBlock(nodeCount) { const len = this._blockStarts.pop(); if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); const toClose = this._nodes.length - len; if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); } this._nodes.length = len; return this; } // `function` heading (or definition if funcBody is passed) func(name, args = code_1.nil, async, funcBody) { this._blockNode(new Func(name, args, async)); if (funcBody) this.code(funcBody).endFunc(); return this; } // end function definition endFunc() { return this._endBlockNode(Func); } optimize(n = 1) { while (n-- > 0) { this._root.optimizeNodes(); this._root.optimizeNames(this._root.names, this._constants); } } _leafNode(node) { this._currNode.nodes.push(node); return this; } _blockNode(node) { this._currNode.nodes.push(node); this._nodes.push(node); } _endBlockNode(N1, N2) { const n = this._currNode; if (n instanceof N1 || N2 && n instanceof N2) { this._nodes.pop(); return this; } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } _elseNode(node) { const n = this._currNode; if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"'); } this._currNode = n.else = node; return this; } get _root() { return this._nodes[0]; } get _currNode() { const ns = this._nodes; return ns[ns.length - 1]; } set _currNode(node) { const ns = this._nodes; ns[ns.length - 1] = node; } }; exports2.CodeGen = CodeGen; function addNames(names, from) { for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); return names; } function addExprNames(names, from) { return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; } function optimizeExpr(expr, names, constants) { if (expr instanceof code_1.Name) return replaceName(expr); if (!canOptimize(expr)) return expr; return new code_1._Code(expr._items.reduce((items, c) => { if (c instanceof code_1.Name) c = replaceName(c); if (c instanceof code_1._Code) items.push(...c._items); else items.push(c); return items; }, [])); function replaceName(n) { const c = constants[n.str]; if (c === void 0 || names[n.str] !== 1) return n; delete names[n.str]; return c; } function canOptimize(e) { return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); } } function subtractNames(names, from) { for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); } function not(x) { return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; } exports2.not = not; var andCode = mappend(exports2.operators.AND); function and(...args) { return args.reduce(andCode); } exports2.and = and; var orCode = mappend(exports2.operators.OR); function or(...args) { return args.reduce(orCode); } exports2.or = or; function mappend(op) { return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; } function par(x) { return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js var require_util5 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.checkStrictMode = exports2.getErrorPath = exports2.Type = exports2.useFunc = exports2.setEvaluated = exports2.evaluatedPropsToName = exports2.mergeEvaluated = exports2.eachItem = exports2.unescapeJsonPointer = exports2.escapeJsonPointer = exports2.escapeFragment = exports2.unescapeFragment = exports2.schemaRefOrVal = exports2.schemaHasRulesButRef = exports2.schemaHasRules = exports2.checkUnknownRules = exports2.alwaysValidSchema = exports2.toHash = void 0; var codegen_1 = require_codegen2(); var code_1 = require_code3(); function toHash(arr) { const hash2 = {}; for (const item of arr) hash2[item] = true; return hash2; } exports2.toHash = toHash; function alwaysValidSchema(it, schema) { if (typeof schema == "boolean") return schema; if (Object.keys(schema).length === 0) return true; checkUnknownRules(it, schema); return !schemaHasRules(schema, it.self.RULES.all); } exports2.alwaysValidSchema = alwaysValidSchema; function checkUnknownRules(it, schema = it.schema) { const { opts, self } = it; if (!opts.strictSchema) return; if (typeof schema === "boolean") return; const rules = self.RULES.keywords; for (const key in schema) { if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); } } exports2.checkUnknownRules = checkUnknownRules; function schemaHasRules(schema, rules) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (rules[key]) return true; return false; } exports2.schemaHasRules = schemaHasRules; function schemaHasRulesButRef(schema, RULES) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; return false; } exports2.schemaHasRulesButRef = schemaHasRulesButRef; function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { if (!$data) { if (typeof schema == "number" || typeof schema == "boolean") return schema; if (typeof schema == "string") return (0, codegen_1._)`${schema}`; } return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; } exports2.schemaRefOrVal = schemaRefOrVal; function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } exports2.unescapeFragment = unescapeFragment; function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } exports2.escapeFragment = escapeFragment; function escapeJsonPointer(str) { if (typeof str == "number") return `${str}`; return str.replace(/~/g, "~0").replace(/\//g, "~1"); } exports2.escapeJsonPointer = escapeJsonPointer; function unescapeJsonPointer(str) { return str.replace(/~1/g, "/").replace(/~0/g, "~"); } exports2.unescapeJsonPointer = unescapeJsonPointer; function eachItem(xs, f) { if (Array.isArray(xs)) { for (const x of xs) f(x); } else { f(xs); } } exports2.eachItem = eachItem; function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { return (gen, from, to, toName) => { const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; }; } exports2.mergeEvaluated = { props: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); }), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { if (from === true) { gen.assign(to, true); } else { gen.assign(to, (0, codegen_1._)`${to} || {}`); setEvaluated(gen, to, from); } }), mergeValues: (from, to) => from === true ? true : { ...from, ...to }, resultToName: evaluatedPropsToName }), items: makeMergeEvaluated({ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), mergeValues: (from, to) => from === true ? true : Math.max(from, to), resultToName: (gen, items) => gen.var("items", items) }) }; function evaluatedPropsToName(gen, ps) { if (ps === true) return gen.var("props", true); const props = gen.var("props", (0, codegen_1._)`{}`); if (ps !== void 0) setEvaluated(gen, props, ps); return props; } exports2.evaluatedPropsToName = evaluatedPropsToName; function setEvaluated(gen, props, ps) { Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); } exports2.setEvaluated = setEvaluated; var snippets = {}; function useFunc(gen, f) { return gen.scopeValue("func", { ref: f, code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) }); } exports2.useFunc = useFunc; var Type; (function(Type2) { Type2[Type2["Num"] = 0] = "Num"; Type2[Type2["Str"] = 1] = "Str"; })(Type || (exports2.Type = Type = {})); function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { if (dataProp instanceof codegen_1.Name) { const isNumber = dataPropType === Type.Num; return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; } return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); } exports2.getErrorPath = getErrorPath; function checkStrictMode(it, msg, mode = it.opts.strictSchema) { if (!mode) return; msg = `strict mode: ${msg}`; if (mode === true) throw new Error(msg); it.self.logger.warn(msg); } exports2.checkStrictMode = checkStrictMode; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js var require_names2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var names = { // validation function arguments data: new codegen_1.Name("data"), // data passed to validation function // args passed from referencing schema valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below instancePath: new codegen_1.Name("instancePath"), parentData: new codegen_1.Name("parentData"), parentDataProperty: new codegen_1.Name("parentDataProperty"), rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef // function scoped variables vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors errors: new codegen_1.Name("errors"), // counter of validation errors this: new codegen_1.Name("this"), // "globals" self: new codegen_1.Name("self"), scope: new codegen_1.Name("scope"), // JTD serialize/parse name for JSON string and position json: new codegen_1.Name("json"), jsonPos: new codegen_1.Name("jsonPos"), jsonLen: new codegen_1.Name("jsonLen"), jsonPart: new codegen_1.Name("jsonPart") }; exports2.default = names; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js var require_errors3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util5(); var names_1 = require_names2(); exports2.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; exports2.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; function reportError(cxt, error48 = exports2.keywordError, errorPaths, overrideAllErrors) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error48, errorPaths); if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { addError(gen, errObj); } else { returnErrors(it, (0, codegen_1._)`[${errObj}]`); } } exports2.reportError = reportError; function reportExtraError(cxt, error48 = exports2.keywordError, errorPaths) { const { it } = cxt; const { gen, compositeRule, allErrors } = it; const errObj = errorObjectCode(cxt, error48, errorPaths); addError(gen, errObj); if (!(compositeRule || allErrors)) { returnErrors(it, names_1.default.vErrors); } } exports2.reportExtraError = reportExtraError; function resetErrorsCount(gen, errsCount) { gen.assign(names_1.default.errors, errsCount); gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); } exports2.resetErrorsCount = resetErrorsCount; function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { if (errsCount === void 0) throw new Error("ajv implementation error"); const err = gen.name("err"); gen.forRange("i", errsCount, names_1.default.errors, (i) => { gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); if (it.opts.verbose) { gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); gen.assign((0, codegen_1._)`${err}.data`, data); } }); } exports2.extendErrors = extendErrors; function addError(gen, errObj) { const err = gen.const("err", errObj); gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); gen.code((0, codegen_1._)`${names_1.default.errors}++`); } function returnErrors(it, errs) { const { gen, validateName, schemaEnv } = it; if (schemaEnv.$async) { gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, errs); gen.return(false); } } var E = { keyword: new codegen_1.Name("keyword"), schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors params: new codegen_1.Name("params"), propertyName: new codegen_1.Name("propertyName"), message: new codegen_1.Name("message"), schema: new codegen_1.Name("schema"), parentSchema: new codegen_1.Name("parentSchema") }; function errorObjectCode(cxt, error48, errorPaths) { const { createErrors } = cxt.it; if (createErrors === false) return (0, codegen_1._)`{}`; return errorObject(cxt, error48, errorPaths); } function errorObject(cxt, error48, errorPaths = {}) { const { gen, it } = cxt; const keyValues = [ errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths) ]; extraErrorProps(cxt, error48, keyValues); return gen.object(...keyValues); } function errorInstancePath({ errorPath }, { instancePath }) { const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; } function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; if (schemaPath) { schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } return [E.schemaPath, schPath]; } function extraErrorProps(cxt, { params, message }, keyValues) { const { keyword, data, schemaValue, it } = cxt; const { opts, propertyName, topSchemaRef, schemaPath } = it; keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); if (opts.messages) { keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } if (opts.verbose) { keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } if (propertyName) keyValues.push([E.propertyName, propertyName]); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js var require_boolSchema2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.boolOrEmptySchema = exports2.topBoolOrEmptySchema = void 0; var errors_1 = require_errors3(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var boolError = { message: "boolean schema is false" }; function topBoolOrEmptySchema(it) { const { gen, schema, validateName } = it; if (schema === false) { falseSchemaError(it, false); } else if (typeof schema == "object" && schema.$async === true) { gen.return(names_1.default.data); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, null); gen.return(true); } } exports2.topBoolOrEmptySchema = topBoolOrEmptySchema; function boolOrEmptySchema(it, valid) { const { gen, schema } = it; if (schema === false) { gen.var(valid, false); falseSchemaError(it); } else { gen.var(valid, true); } } exports2.boolOrEmptySchema = boolOrEmptySchema; function falseSchemaError(it, overrideAllErrors) { const { gen, data } = it; const cxt = { gen, keyword: "false schema", data, schema: false, schemaCode: false, schemaValue: false, params: {}, it }; (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js var require_rules2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getRules = exports2.isJSONType = void 0; var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; var jsonTypes = new Set(_jsonTypes); function isJSONType(x) { return typeof x == "string" && jsonTypes.has(x); } exports2.isJSONType = isJSONType; function getRules() { const groups = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; return { types: { ...groups, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], post: { rules: [] }, all: {}, keywords: {} }; } exports2.getRules = getRules; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js var require_applicability2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.shouldUseRule = exports2.shouldUseGroup = exports2.schemaHasRulesForType = void 0; function schemaHasRulesForType({ schema, self }, type) { const group = self.RULES.types[type]; return group && group !== true && shouldUseGroup(schema, group); } exports2.schemaHasRulesForType = schemaHasRulesForType; function shouldUseGroup(schema, group) { return group.rules.some((rule) => shouldUseRule(schema, rule)); } exports2.shouldUseGroup = shouldUseGroup; function shouldUseRule(schema, rule) { var _a2; return schema[rule.keyword] !== void 0 || ((_a2 = rule.definition.implements) === null || _a2 === void 0 ? void 0 : _a2.some((kwd) => schema[kwd] !== void 0)); } exports2.shouldUseRule = shouldUseRule; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js var require_dataType2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.reportTypeError = exports2.checkDataTypes = exports2.checkDataType = exports2.coerceAndCheckDataType = exports2.getJSONTypes = exports2.getSchemaTypes = exports2.DataType = void 0; var rules_1 = require_rules2(); var applicability_1 = require_applicability2(); var errors_1 = require_errors3(); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var DataType; (function(DataType2) { DataType2[DataType2["Correct"] = 0] = "Correct"; DataType2[DataType2["Wrong"] = 1] = "Wrong"; })(DataType || (exports2.DataType = DataType = {})); function getSchemaTypes(schema) { const types = getJSONTypes(schema.type); const hasNull = types.includes("null"); if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); } else { if (!types.length && schema.nullable !== void 0) { throw new Error('"nullable" cannot be used without "type"'); } if (schema.nullable === true) types.push("null"); } return types; } exports2.getSchemaTypes = getSchemaTypes; function getJSONTypes(ts) { const types = Array.isArray(ts) ? ts : ts ? [ts] : []; if (types.every(rules_1.isJSONType)) return types; throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); } exports2.getJSONTypes = getJSONTypes; function coerceAndCheckDataType(it, types) { const { gen, data, opts } = it; const coerceTo = coerceToTypes(types, opts.coerceTypes); const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); if (checkTypes) { const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); gen.if(wrongType, () => { if (coerceTo.length) coerceData(it, types, coerceTo); else reportTypeError(it); }); } return checkTypes; } exports2.coerceAndCheckDataType = coerceAndCheckDataType; var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); function coerceToTypes(types, coerceTypes) { return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; } function coerceData(it, types, coerceTo) { const { gen, data, opts } = it; const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); if (opts.coerceTypes === "array") { gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } gen.if((0, codegen_1._)`${coerced} !== undefined`); for (const t of coerceTo) { if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { coerceSpecificType(t); } } gen.else(); reportTypeError(it); gen.endIf(); gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { gen.assign(data, coerced); assignParentData(it, coerced); }); function coerceSpecificType(t) { switch (t) { case "string": gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); return; case "number": gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "integer": gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); return; case "boolean": gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); return; case "null": gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); gen.assign(coerced, null); return; case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } } function assignParentData({ gen, parentData, parentDataProperty }, expr) { gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); } function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; let cond; switch (dataType) { case "null": return (0, codegen_1._)`${data} ${EQ} null`; case "array": cond = (0, codegen_1._)`Array.isArray(${data})`; break; case "object": cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; break; case "integer": cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); break; case "number": cond = numCond(); break; default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; } return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); function numCond(_cond = codegen_1.nil) { return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } } exports2.checkDataType = checkDataType; function checkDataTypes(dataTypes, data, strictNums, correct) { if (dataTypes.length === 1) { return checkDataType(dataTypes[0], data, strictNums, correct); } let cond; const types = (0, util_1.toHash)(dataTypes); if (types.array && types.object) { const notObj = (0, codegen_1._)`typeof ${data} != "object"`; cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; delete types.null; delete types.array; delete types.object; } else { cond = codegen_1.nil; } if (types.number) delete types.integer; for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); return cond; } exports2.checkDataTypes = checkDataTypes; var typeError = { message: ({ schema }) => `must be ${schema}`, params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; function reportTypeError(it) { const cxt = getTypeErrorContext(it); (0, errors_1.reportError)(cxt, typeError); } exports2.reportTypeError = reportTypeError; function getTypeErrorContext(it) { const { gen, data, schema } = it; const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, it }; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js var require_defaults2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.assignDefaults = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util5(); function assignDefaults(it, ty) { const { properties, items } = it.schema; if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default); } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i) => assignDefault(it, i, sch.default)); } } exports2.assignDefaults = assignDefaults; function assignDefault(it, prop, defaultValue) { const { gen, compositeRule, data, opts } = it; if (defaultValue === void 0) return; const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; if (compositeRule) { (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); return; } let condition = (0, codegen_1._)`${childData} === undefined`; if (opts.useDefaults === "empty") { condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js var require_code4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util5(); var names_1 = require_names2(); var util_2 = require_util5(); function checkReportMissingProp(cxt, prop) { const { gen, data, it } = cxt; gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); cxt.error(); }); } exports2.checkReportMissingProp = checkReportMissingProp; function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); } exports2.checkMissingProp = checkMissingProp; function reportMissingProp(cxt, missing) { cxt.setParams({ missingProperty: missing }, true); cxt.error(); } exports2.reportMissingProp = reportMissingProp; function hasPropFunc(gen) { return gen.scopeValue("func", { // eslint-disable-next-line @typescript-eslint/unbound-method ref: Object.prototype.hasOwnProperty, code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); } exports2.hasPropFunc = hasPropFunc; function isOwnProperty(gen, data, property) { return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; } exports2.isOwnProperty = isOwnProperty; function propertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; } exports2.propertyInData = propertyInData; function noPropertyInData(gen, data, property, ownProperties) { const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; } exports2.noPropertyInData = noPropertyInData; function allSchemaProperties(schemaMap) { return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; } exports2.allSchemaProperties = allSchemaProperties; function schemaProperties(it, schemaMap) { return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); } exports2.schemaProperties = schemaProperties; function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; const valCxt = [ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], [names_1.default.parentData, it.parentData], [names_1.default.parentDataProperty, it.parentDataProperty], [names_1.default.rootData, names_1.default.rootData] ]; if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; } exports2.callValidateCode = callValidateCode; var newRegExp = (0, codegen_1._)`new RegExp`; function usePattern({ gen, it: { opts } }, pattern) { const u = opts.unicodeRegExp ? "u" : ""; const { regExp } = opts.code; const rx = regExp(pattern, u); return gen.scopeValue("pattern", { key: rx.toString(), ref: rx, code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` }); } exports2.usePattern = usePattern; function validateArray(cxt) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); if (it.allErrors) { const validArr = gen.let("valid", true); validateItems(() => gen.assign(validArr, false)); return validArr; } gen.var(valid, true); validateItems(() => gen.break()); return valid; function validateItems(notValid) { const len = gen.const("len", (0, codegen_1._)`${data}.length`); gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); gen.if((0, codegen_1.not)(valid), notValid); }); } } exports2.validateArray = validateArray; function validateUnion(cxt) { const { gen, schema, keyword, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); if (alwaysValid && !it.opts.unevaluated) return; const valid = gen.let("valid", false); const schValid = gen.name("_valid"); gen.block(() => schema.forEach((_sch, i) => { const schCxt = cxt.subschema({ keyword, schemaProp: i, compositeRule: true }, schValid); gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); const merged = cxt.mergeValidEvaluated(schCxt, schValid); if (!merged) gen.if((0, codegen_1.not)(valid)); })); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); } exports2.validateUnion = validateUnion; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js var require_keyword2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateKeywordUsage = exports2.validSchemaType = exports2.funcKeywordCode = exports2.macroKeywordCode = void 0; var codegen_1 = require_codegen2(); var names_1 = require_names2(); var code_1 = require_code4(); var errors_1 = require_errors3(); function macroKeywordCode(cxt, def) { const { gen, keyword, schema, parentSchema, it } = cxt; const macroSchema = def.macro.call(it.self, schema, parentSchema, it); const schemaRef = useKeyword(gen, keyword, macroSchema); if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); const valid = gen.name("valid"); cxt.subschema({ schema: macroSchema, schemaPath: codegen_1.nil, errSchemaPath: `${it.errSchemaPath}/${keyword}`, topSchemaRef: schemaRef, compositeRule: true }, valid); cxt.pass(valid, () => cxt.error(true)); } exports2.macroKeywordCode = macroKeywordCode; function funcKeywordCode(cxt, def) { var _a2; const { gen, keyword, schema, parentSchema, $data, it } = cxt; checkAsyncKeyword(it, def); const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; const validateRef = useKeyword(gen, keyword, validate2); const valid = gen.let("valid"); cxt.block$data(valid, validateKeyword); cxt.ok((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid); function validateKeyword() { if (def.errors === false) { assignValid(); if (def.modifying) modifyData(cxt); reportErrs(() => cxt.error()); } else { const ruleErrs = def.async ? validateAsync() : validateSync(); if (def.modifying) modifyData(cxt); reportErrs(() => addErrs(cxt, ruleErrs)); } } function validateAsync() { const ruleErrs = gen.let("ruleErrs", null); gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); return ruleErrs; } function validateSync() { const validateErrs = (0, codegen_1._)`${validateRef}.errors`; gen.assign(validateErrs, null); assignValid(codegen_1.nil); return validateErrs; } function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; const passSchema = !("compile" in def && !$data || def.schema === false); gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } function reportErrs(errors) { var _a3; gen.if((0, codegen_1.not)((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid), errors); } } exports2.funcKeywordCode = funcKeywordCode; function modifyData(cxt) { const { gen, data, it } = cxt; gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); } function addErrs(cxt, errs) { const { gen } = cxt; gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); (0, errors_1.extendErrors)(cxt); }, () => cxt.error()); } function checkAsyncKeyword({ schemaEnv }, def) { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); } function useKeyword(gen, keyword, result) { if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); } function validSchemaType(schema, schemaType, allowUndefined = false) { return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); } exports2.validSchemaType = validSchemaType; function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error"); } const deps = def.dependencies; if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } if (def.validateSchema) { const valid = def.validateSchema(schema[keyword]); if (!valid) { const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); if (opts.validateSchema === "log") self.logger.error(msg); else throw new Error(msg); } } } exports2.validateKeywordUsage = validateKeywordUsage; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js var require_subschema2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.extendSubschemaMode = exports2.extendSubschemaData = exports2.getSubschema = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util5(); function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { if (keyword !== void 0 && schema !== void 0) { throw new Error('both "keyword" and "schema" passed, only one allowed'); } if (keyword !== void 0) { const sch = it.schema[keyword]; return schemaProp === void 0 ? { schema: sch, schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}` } : { schema: sch[schemaProp], schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` }; } if (schema !== void 0) { if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } return { schema, schemaPath, topSchemaRef, errSchemaPath }; } throw new Error('either "keyword" or "schema" must be passed'); } exports2.getSubschema = getSubschema; function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { if (data !== void 0 && dataProp !== void 0) { throw new Error('both "data" and "dataProp" passed, only one allowed'); } const { gen } = it; if (dataProp !== void 0) { const { errorPath, dataPathArr, opts } = it; const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); dataContextProps(nextData); subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } if (data !== void 0) { const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); dataContextProps(nextData); if (propertyName !== void 0) subschema.propertyName = propertyName; } if (dataTypes) subschema.dataTypes = dataTypes; function dataContextProps(_nextData) { subschema.data = _nextData; subschema.dataLevel = it.dataLevel + 1; subschema.dataTypes = []; it.definedProperties = /* @__PURE__ */ new Set(); subschema.parentData = it.data; subschema.dataNames = [...it.dataNames, _nextData]; } } exports2.extendSubschemaData = extendSubschemaData; function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { if (compositeRule !== void 0) subschema.compositeRule = compositeRule; if (createErrors !== void 0) subschema.createErrors = createErrors; if (allErrors !== void 0) subschema.allErrors = allErrors; subschema.jtdDiscriminator = jtdDiscriminator; subschema.jtdMetadata = jtdMetadata; } exports2.extendSubschemaMode = extendSubschemaMode; } }); // node_modules/ajv-formats/node_modules/json-schema-traverse/index.js var require_json_schema_traverse2 = __commonJS({ "node_modules/ajv-formats/node_modules/json-schema-traverse/index.js"(exports2, module2) { "use strict"; var traverse = module2.exports = function(schema, opts, cb) { if (typeof opts == "function") { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = typeof cb == "function" ? cb : cb.pre || function() { }; var post = cb.post || function() { }; _traverse(opts, pre, post, schema, "", schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == "object" && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); } } else if (key in traverse.propsKeywords) { if (sch && typeof sch == "object") { for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); } } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); } } post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } function escapeJsonPtr(str) { return str.replace(/~/g, "~0").replace(/\//g, "~1"); } } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js var require_resolve2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0; var util_1 = require_util5(); var equal = require_fast_deep_equal(); var traverse = require_json_schema_traverse2(); var SIMPLE_INLINED = /* @__PURE__ */ new Set([ "type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const" ]); function inlineRef(schema, limit = true) { if (typeof schema == "boolean") return true; if (limit === true) return !hasRef(schema); if (!limit) return false; return countKeys(schema) <= limit; } exports2.inlineRef = inlineRef; var REF_KEYWORDS = /* @__PURE__ */ new Set([ "$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor" ]); function hasRef(schema) { for (const key in schema) { if (REF_KEYWORDS.has(key)) return true; const sch = schema[key]; if (Array.isArray(sch) && sch.some(hasRef)) return true; if (typeof sch == "object" && hasRef(sch)) return true; } return false; } function countKeys(schema) { let count = 0; for (const key in schema) { if (key === "$ref") return Infinity; count++; if (SIMPLE_INLINED.has(key)) continue; if (typeof schema[key] == "object") { (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); } if (count === Infinity) return Infinity; } return count; } function getFullPath(resolver, id = "", normalize) { if (normalize !== false) id = normalizeId(id); const p = resolver.parse(id); return _getFullPath(resolver, p); } exports2.getFullPath = getFullPath; function _getFullPath(resolver, p) { const serialized = resolver.serialize(p); return serialized.split("#")[0] + "#"; } exports2._getFullPath = _getFullPath; var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } exports2.normalizeId = normalizeId; function resolveUrl(resolver, baseId, id) { id = normalizeId(id); return resolver.resolve(baseId, id); } exports2.resolveUrl = resolveUrl; var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; function getSchemaRefs(schema, baseId) { if (typeof schema == "boolean") return {}; const { schemaId, uriResolver } = this.opts; const schId = normalizeId(schema[schemaId] || baseId); const baseIds = { "": schId }; const pathPrefix = getFullPath(uriResolver, schId, false); const localRefs = {}; const schemaRefs = /* @__PURE__ */ new Set(); traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { if (parentJsonPtr === void 0) return; const fullPath = pathPrefix + jsonPtr; let innerBaseId = baseIds[parentJsonPtr]; if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); addAnchor.call(this, sch.$anchor); addAnchor.call(this, sch.$dynamicAnchor); baseIds[jsonPtr] = innerBaseId; function addRef(ref) { const _resolve = this.opts.uriResolver.resolve; ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); if (schemaRefs.has(ref)) throw ambiguos(ref); schemaRefs.add(ref); let schOrRef = this.refs[ref]; if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; if (typeof schOrRef == "object") { checkAmbiguosRef(sch, schOrRef.schema, ref); } else if (ref !== normalizeId(fullPath)) { if (ref[0] === "#") { checkAmbiguosRef(sch, localRefs[ref], ref); localRefs[ref] = sch; } else { this.refs[ref] = fullPath; } } return ref; } function addAnchor(anchor) { if (typeof anchor == "string") { if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); addRef.call(this, `#${anchor}`); } } }); return localRefs; function checkAmbiguosRef(sch1, sch2, ref) { if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); } function ambiguos(ref) { return new Error(`reference "${ref}" resolves to more than one schema`); } } exports2.getSchemaRefs = getSchemaRefs; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js var require_validate2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getData = exports2.KeywordCxt = exports2.validateFunctionCode = void 0; var boolSchema_1 = require_boolSchema2(); var dataType_1 = require_dataType2(); var applicability_1 = require_applicability2(); var dataType_2 = require_dataType2(); var defaults_1 = require_defaults2(); var keyword_1 = require_keyword2(); var subschema_1 = require_subschema2(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var resolve_1 = require_resolve2(); var util_1 = require_util5(); var errors_1 = require_errors3(); function validateFunctionCode(it) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { topSchemaObjCode(it); return; } } validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); } exports2.validateFunctionCode = validateFunctionCode; function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { if (opts.code.es5) { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); destructureValCxtES5(gen, opts); gen.code(body); }); } else { gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); } } function destructureValCxt(opts) { return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; } function destructureValCxtES5(gen, opts) { gen.if(names_1.default.valCxt, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); }, () => { gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); gen.var(names_1.default.rootData, names_1.default.data); if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); }); } function topSchemaObjCode(it) { const { schema, opts, gen } = it; validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it); checkNoDefault(it); gen.let(names_1.default.vErrors, null); gen.let(names_1.default.errors, 0); if (opts.unevaluated) resetEvaluated(it); typeAndKeywords(it); returnResults(it); }); return; } function resetEvaluated(it) { const { gen, validateName } = it; it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); } function funcSourceUrl(schema, opts) { const schId = typeof schema == "object" && schema[opts.schemaId]; return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; } function subschemaCode(it, valid) { if (isSchemaObj(it)) { checkKeywords(it); if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid); return; } } (0, boolSchema_1.boolOrEmptySchema)(it, valid); } function schemaCxtHasRules({ schema, self }) { if (typeof schema == "boolean") return !schema; for (const key in schema) if (self.RULES.all[key]) return true; return false; } function isSchemaObj(it) { return typeof it.schema != "boolean"; } function subSchemaObjCode(it, valid) { const { schema, gen, opts } = it; if (opts.$comment && schema.$comment) commentKeyword(it); updateContext(it); checkAsyncSchema(it); const errsCount = gen.const("_errs", names_1.default.errors); typeAndKeywords(it, errsCount); gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); } function checkKeywords(it) { (0, util_1.checkUnknownRules)(it); checkRefsAndKeywords(it); } function typeAndKeywords(it, errsCount) { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); const types = (0, dataType_1.getSchemaTypes)(it.schema); const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); schemaKeywords(it, types, !checkedTypes, errsCount); } function checkRefsAndKeywords(it) { const { schema, errSchemaPath, opts, self } = it; if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } } function checkNoDefault(it) { const { schema, opts } = it; if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } } function updateContext(it) { const schId = it.schema[it.opts.schemaId]; if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); } function checkAsyncSchema(it) { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); } function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { const msg = schema.$comment; if (opts.$comment === true) { gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); } else if (typeof opts.$comment == "function") { const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } } function returnResults(it) { const { gen, schemaEnv, validateName, ValidationError, opts } = it; if (schemaEnv.$async) { gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); } else { gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); if (opts.unevaluated) assignEvaluated(it); gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } } function assignEvaluated({ gen, evaluated, props, items }) { if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); } function schemaKeywords(it, types, typeErrors, errsCount) { const { gen, schema, data, allErrors, opts, self } = it; const { RULES } = self; if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); return; } if (!opts.jtd) checkStrictTypes(it, types); gen.block(() => { for (const group of RULES.rules) groupKeywords(group); groupKeywords(RULES.post); }); function groupKeywords(group) { if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; if (group.type) { gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); iterateKeywords(it, group); if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else(); (0, dataType_2.reportTypeError)(it); } gen.endIf(); } else { iterateKeywords(it, group); } if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } } function iterateKeywords(it, group) { const { gen, schema, opts: { useDefaults } } = it; if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); gen.block(() => { for (const rule of group.rules) { if ((0, applicability_1.shouldUseRule)(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type); } } }); } function checkStrictTypes(it, types) { if (it.schemaEnv.meta || !it.opts.strictTypes) return; checkContextTypes(it, types); if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); checkKeywordTypes(it, it.dataTypes); } function checkContextTypes(it, types) { if (!types.length) return; if (!it.dataTypes.length) { it.dataTypes = types; return; } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); } }); narrowSchemaTypes(it, types); } function checkMultipleTypes(it, ts) { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } } function checkKeywordTypes(it, ts) { const rules = it.self.RULES.all; for (const keyword in rules) { const rule = rules[keyword]; if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { const { type } = rule.definition; if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); } } } } function hasApplicableType(schTs, kwdT) { return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); } function includesType(ts, t) { return ts.includes(t) || t === "integer" && ts.includes("number"); } function narrowSchemaTypes(it, withTypes) { const ts = []; for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t); else if (withTypes.includes("integer") && t === "number") ts.push("integer"); } it.dataTypes = ts; } function strictTypesError(it, msg) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; msg += ` at "${schemaPath}" (strictTypes)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); } var KeywordCxt = class { constructor(it, def, keyword) { (0, keyword_1.validateKeywordUsage)(it, def, keyword); this.gen = it.gen; this.allErrors = it.allErrors; this.keyword = keyword; this.data = it.data; this.schema = it.schema[keyword]; this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); this.schemaType = def.schemaType; this.parentSchema = it.schema; this.params = {}; this.it = it; this.def = def; if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); } else { this.schemaCode = this.schemaValue; if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", names_1.default.errors); } } result(condition, successAction, failAction) { this.failResult((0, codegen_1.not)(condition), successAction, failAction); } failResult(condition, successAction, failAction) { this.gen.if(condition); if (failAction) failAction(); else this.error(); if (successAction) { this.gen.else(); successAction(); if (this.allErrors) this.gen.endIf(); } else { if (this.allErrors) this.gen.endIf(); else this.gen.else(); } } pass(condition, failAction) { this.failResult((0, codegen_1.not)(condition), void 0, failAction); } fail(condition) { if (condition === void 0) { this.error(); if (!this.allErrors) this.gen.if(false); return; } this.gen.if(condition); this.error(); if (this.allErrors) this.gen.endIf(); else this.gen.else(); } fail$data(condition) { if (!this.$data) return this.fail(condition); const { schemaCode } = this; this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } error(append, errorParams, errorPaths) { if (errorParams) { this.setParams(errorParams); this._error(append, errorPaths); this.setParams({}); return; } this._error(append, errorPaths); } _error(append, errorPaths) { ; (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } $dataError() { (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } reset() { if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } ok(cond) { if (!this.allErrors) this.gen.if(cond); } setParams(obj, assign) { if (assign) Object.assign(this.params, obj); else this.params = obj; } block$data(valid, codeBlock, $dataValid = codegen_1.nil) { this.gen.block(() => { this.check$data(valid, $dataValid); codeBlock(); }); } check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { if (!this.$data) return; const { gen, schemaCode, schemaType, def } = this; gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); if (valid !== codegen_1.nil) gen.assign(valid, true); if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()); this.$dataError(); if (valid !== codegen_1.nil) gen.assign(valid, false); } gen.else(); } invalid$data() { const { gen, schemaCode, schemaType, def, it } = this; return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); function wrong$DataType() { if (schemaType.length) { if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); const st = Array.isArray(schemaType) ? schemaType : [schemaType]; return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; } return codegen_1.nil; } function invalid$DataSchema() { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; } return codegen_1.nil; } } subschema(appl, valid) { const subschema = (0, subschema_1.getSubschema)(this.it, appl); (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); (0, subschema_1.extendSubschemaMode)(subschema, appl); const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; subschemaCode(nextContext, valid); return nextContext; } mergeEvaluated(schemaCxt, toName) { const { it, gen } = this; if (!it.opts.unevaluated) return; if (it.props !== true && schemaCxt.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); } if (it.items !== true && schemaCxt.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); } } mergeValidEvaluated(schemaCxt, valid) { const { it, gen } = this; if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); return true; } } }; exports2.KeywordCxt = KeywordCxt; function keywordCode(it, keyword, def, ruleType) { const cxt = new KeywordCxt(it, def, keyword); if ("code" in def) { def.code(cxt, ruleType); } else if (cxt.$data && def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } else if ("macro" in def) { (0, keyword_1.macroKeywordCode)(cxt, def); } else if (def.compile || def.validate) { (0, keyword_1.funcKeywordCode)(cxt, def); } } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, { dataLevel, dataNames, dataPathArr }) { let jsonPointer; let data; if ($data === "") return names_1.default.rootData; if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); jsonPointer = $data; data = names_1.default.rootData; } else { const matches = RELATIVE_JSON_POINTER.exec($data); if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); const up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); return dataPathArr[dataLevel - up]; } if (up > dataLevel) throw new Error(errorMsg("data", up)); data = dataNames[dataLevel - up]; if (!jsonPointer) return data; } let expr = data; const segments = jsonPointer.split("/"); for (const segment2 of segments) { if (segment2) { data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment2))}`; expr = (0, codegen_1._)`${expr} && ${data}`; } } return expr; function errorMsg(pointerType, up) { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } } exports2.getData = getData; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js var require_validation_error2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var ValidationError = class extends Error { constructor(errors) { super("validation failed"); this.errors = errors; this.ajv = this.validation = true; } }; exports2.default = ValidationError; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js var require_ref_error2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var resolve_1 = require_resolve2(); var MissingRefError = class extends Error { constructor(resolver, baseId, ref, msg) { super(msg || `can't resolve reference ${ref} from id ${baseId}`); this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; exports2.default = MissingRefError; } }); // node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js var require_compile3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0; var codegen_1 = require_codegen2(); var validation_error_1 = require_validation_error2(); var names_1 = require_names2(); var resolve_1 = require_resolve2(); var util_1 = require_util5(); var validate_1 = require_validate2(); var SchemaEnv = class { constructor(env) { var _a2; this.refs = {}; this.dynamicAnchors = {}; let schema; if (typeof env.schema == "object") schema = env.schema; this.schema = env.schema; this.schemaId = env.schemaId; this.root = env.root || this; this.baseId = (_a2 = env.baseId) !== null && _a2 !== void 0 ? _a2 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); this.schemaPath = env.schemaPath; this.localRefs = env.localRefs; this.meta = env.meta; this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; this.refs = {}; } }; exports2.SchemaEnv = SchemaEnv; function compileSchema(sch) { const _sch = getCompilingSchema.call(this, sch); if (_sch) return _sch; const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); const { es5, lines } = this.opts.code; const { ownProperties } = this.opts; const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); let _ValidationError; if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: validation_error_1.default, code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` }); } const validateName = gen.scopeName("validate"); sch.validateName = validateName; const schemaCxt = { gen, allErrors: this.opts.allErrors, data: names_1.default.data, parentData: names_1.default.parentData, parentDataProperty: names_1.default.parentDataProperty, dataNames: [names_1.default.data], dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: codegen_1.nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: (0, codegen_1._)`""`, opts: this.opts, self: this }; let sourceCode; try { this._compilations.add(sch); (0, validate_1.validateFunctionCode)(schemaCxt); gen.optimize(this.opts.code.optimize); const validateCode = gen.toString(); sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); const validate2 = makeValidate(this, this.scope.get()); this.scope.value(validateName, { ref: validate2 }); validate2.errors = null; validate2.schema = sch.schema; validate2.schemaEnv = sch; if (sch.$async) validate2.$async = true; if (this.opts.code.source === true) { validate2.source = { validateName, validateCode, scopeValues: gen._values }; } if (this.opts.unevaluated) { const { props, items } = schemaCxt; validate2.evaluated = { props: props instanceof codegen_1.Name ? void 0 : props, items: items instanceof codegen_1.Name ? void 0 : items, dynamicProps: props instanceof codegen_1.Name, dynamicItems: items instanceof codegen_1.Name }; if (validate2.source) validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); } sch.validate = validate2; return sch; } catch (e) { delete sch.validate; delete sch.validateName; if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); throw e; } finally { this._compilations.delete(sch); } } exports2.compileSchema = compileSchema; function resolveRef2(root, baseId, ref) { var _a2; ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); const schOrFunc = root.refs[ref]; if (schOrFunc) return schOrFunc; let _sch = resolve.call(this, root, ref); if (_sch === void 0) { const schema = (_a2 = root.localRefs) === null || _a2 === void 0 ? void 0 : _a2[ref]; const { schemaId } = this.opts; if (schema) _sch = new SchemaEnv({ schema, schemaId, root, baseId }); } if (_sch === void 0) return; return root.refs[ref] = inlineOrCompile.call(this, _sch); } exports2.resolveRef = resolveRef2; function inlineOrCompile(sch) { if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; return sch.validate ? sch : compileSchema.call(this, sch); } function getCompilingSchema(schEnv) { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) return sch; } } exports2.getCompilingSchema = getCompilingSchema; function sameSchemaEnv(s1, s2) { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; } function resolve(root, ref) { let sch; while (typeof (sch = this.refs[ref]) == "string") ref = sch; return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); } function resolveSchema(root, ref) { const p = this.opts.uriResolver.parse(ref); const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); if (Object.keys(root.schema).length > 0 && refPath === baseId) { return getJsonPointer.call(this, p, root); } const id = (0, resolve_1.normalizeId)(refPath); const schOrRef = this.refs[id] || this.schemas[id]; if (typeof schOrRef == "string") { const sch = resolveSchema.call(this, root, schOrRef); if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; return getJsonPointer.call(this, p, sch); } if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; if (!schOrRef.validate) compileSchema.call(this, schOrRef); if (id === (0, resolve_1.normalizeId)(ref)) { const { schema } = schOrRef; const { schemaId } = this.opts; const schId = schema[schemaId]; if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); return new SchemaEnv({ schema, schemaId, root, baseId }); } return getJsonPointer.call(this, p, schOrRef); } exports2.resolveSchema = resolveSchema; var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ "properties", "patternProperties", "enum", "dependencies", "definitions" ]); function getJsonPointer(parsedRef, { baseId, schema, root }) { var _a2; if (((_a2 = parsedRef.fragment) === null || _a2 === void 0 ? void 0 : _a2[0]) !== "/") return; for (const part of parsedRef.fragment.slice(1).split("/")) { if (typeof schema === "boolean") return; const partSchema = schema[(0, util_1.unescapeFragment)(part)]; if (partSchema === void 0) return; schema = partSchema; const schId = typeof schema === "object" && schema[this.opts.schemaId]; if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); } } let env; if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); env = resolveSchema.call(this, root, $ref); } const { schemaId } = this.opts; env = env || new SchemaEnv({ schema, schemaId, root, baseId }); if (env.schema !== env.root.schema) return env; return void 0; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json var require_data2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json"(exports2, module2) { module2.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js var require_uri2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var uri = require_fast_uri(); uri.code = 'require("ajv/dist/runtime/uri").default'; exports2.default = uri; } }); // node_modules/ajv-formats/node_modules/ajv/dist/core.js var require_core3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/core.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0; var validate_1 = require_validate2(); Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen2(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error2(); var ref_error_1 = require_ref_error2(); var rules_1 = require_rules2(); var compile_1 = require_compile3(); var codegen_2 = require_codegen2(); var resolve_1 = require_resolve2(); var dataType_1 = require_dataType2(); var util_1 = require_util5(); var $dataRefSchema = require_data2(); var uri_1 = require_uri2(); var defaultRegExp = (str, flags) => new RegExp(str, flags); defaultRegExp.code = "new RegExp"; var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ "validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error" ]); var removedOptions = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }; var deprecatedOptions = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; var MAX_EXPRESSION = 200; function requiredOptions(o) { var _a2, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; const s = o.strict; const _optz = (_a2 = o.code) === null || _a2 === void 0 ? void 0 : _a2.optimize; const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; return { strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, uriResolver }; } var Ajv2 = class { constructor(opts = {}) { this.schemas = {}; this.refs = {}; this.formats = {}; this._compilations = /* @__PURE__ */ new Set(); this._loading = {}; this._cache = /* @__PURE__ */ new Map(); opts = this.opts = { ...opts, ...requiredOptions(opts) }; const { es5, lines } = this.opts.code; this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); this.logger = getLogger(opts.logger); const formatOpt = opts.validateFormats; opts.validateFormats = false; this.RULES = (0, rules_1.getRules)(); checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); this._metaOpts = getMetaSchemaOptions.call(this); if (opts.formats) addInitialFormats.call(this); this._addVocabularies(); this._addDefaultMetaSchema(); if (opts.keywords) addInitialKeywords.call(this, opts.keywords); if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); addInitialSchemas.call(this); opts.validateFormats = formatOpt; } _addVocabularies() { this.addKeyword("$async"); } _addDefaultMetaSchema() { const { $data, meta: meta3, schemaId } = this.opts; let _dataRefSchema = $dataRefSchema; if (schemaId === "id") { _dataRefSchema = { ...$dataRefSchema }; _dataRefSchema.id = _dataRefSchema.$id; delete _dataRefSchema.$id; } if (meta3 && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } defaultMeta() { const { meta: meta3, schemaId } = this.opts; return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; } validate(schemaKeyRef, data) { let v; if (typeof schemaKeyRef == "string") { v = this.getSchema(schemaKeyRef); if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); } else { v = this.compile(schemaKeyRef); } const valid = v(data); if (!("$async" in v)) this.errors = v.errors; return valid; } compile(schema, _meta) { const sch = this._addSchema(schema, _meta); return sch.validate || this._compileSchemaEnv(sch); } compileAsync(schema, meta3) { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function"); } const { loadSchema } = this.opts; return runCompileAsync.call(this, schema, meta3); async function runCompileAsync(_schema, _meta) { await loadMetaSchema.call(this, _schema.$schema); const sch = this._addSchema(_schema, _meta); return sch.validate || _compileAsync.call(this, sch); } async function loadMetaSchema($ref) { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, { $ref }, true); } } async function _compileAsync(sch) { try { return this._compileSchemaEnv(sch); } catch (e) { if (!(e instanceof ref_error_1.default)) throw e; checkLoaded.call(this, e); await loadMissingSchema.call(this, e.missingSchema); return _compileAsync.call(this, sch); } } function checkLoaded({ missingSchema: ref, missingRef }) { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); } } async function loadMissingSchema(ref) { const _schema = await _loadSchema.call(this, ref); if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); if (!this.refs[ref]) this.addSchema(_schema, ref, meta3); } async function _loadSchema(ref) { const p = this._loading[ref]; if (p) return p; try { return await (this._loading[ref] = loadSchema(ref)); } finally { delete this._loading[ref]; } } } // Adds schema to the instance addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); return this; } let id; if (typeof schema === "object") { const { schemaId } = this.opts; id = schema[schemaId]; if (id !== void 0 && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`); } } key = (0, resolve_1.normalizeId)(key || id); this._checkUnique(key); this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); return this; } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { this.addSchema(schema, key, true, _validateSchema); return this; } // Validate schema against its meta-schema validateSchema(schema, throwOrLogError) { if (typeof schema == "boolean") return true; let $schema; $schema = schema.$schema; if ($schema !== void 0 && typeof $schema != "string") { throw new Error("$schema must be a string"); } $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); if (!$schema) { this.logger.warn("meta-schema not available"); this.errors = null; return true; } const valid = this.validate($schema, schema); if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText(); if (this.opts.validateSchema === "log") this.logger.error(message); else throw new Error(message); } return valid; } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema(keyRef) { let sch; while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; if (sch === void 0) { const { schemaId } = this.opts; const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); sch = compile_1.resolveSchema.call(this, root, keyRef); if (!sch) return; this.refs[keyRef] = sch; } return sch.validate || this._compileSchemaEnv(sch); } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef); this._removeAllSchemas(this.refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas); this._removeAllSchemas(this.refs); this._cache.clear(); return this; case "string": { const sch = getSchEnv.call(this, schemaKeyRef); if (typeof sch == "object") this._cache.delete(sch.schema); delete this.schemas[schemaKeyRef]; delete this.refs[schemaKeyRef]; return this; } case "object": { const cacheKey2 = schemaKeyRef; this._cache.delete(cacheKey2); let id = schemaKeyRef[this.opts.schemaId]; if (id) { id = (0, resolve_1.normalizeId)(id); delete this.schemas[id]; delete this.refs[id]; } return this; } default: throw new Error("ajv.removeSchema: invalid parameter"); } } // add "vocabulary" - a collection of keywords addVocabulary(definitions) { for (const def of definitions) this.addKeyword(def); return this; } addKeyword(kwdOrDef, def) { let keyword; if (typeof kwdOrDef == "string") { keyword = kwdOrDef; if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword"); def.keyword = keyword; } } else if (typeof kwdOrDef == "object" && def === void 0) { def = kwdOrDef; keyword = def.keyword; if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array"); } } else { throw new Error("invalid addKeywords parameters"); } checkKeyword.call(this, keyword, def); if (!def) { (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); return this; } keywordMetaschema.call(this, def); const definition = { ...def, type: (0, dataType_1.getJSONTypes)(def.type), schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) }; (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); return this; } getKeyword(keyword) { const rule = this.RULES.all[keyword]; return typeof rule == "object" ? rule.definition : !!rule; } // Remove keyword removeKeyword(keyword) { const { RULES } = this; delete RULES.keywords[keyword]; delete RULES.all[keyword]; for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword); if (i >= 0) group.rules.splice(i, 1); } return this; } // Add format addFormat(name, format) { if (typeof format == "string") format = new RegExp(format); this.formats[name] = format; return this; } errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { if (!errors || errors.length === 0) return "No errors"; return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); } $dataMetaSchema(metaSchema, keywordsJsonPointers) { const rules = this.RULES.all; metaSchema = JSON.parse(JSON.stringify(metaSchema)); for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1); let keywords = metaSchema; for (const seg of segments) keywords = keywords[seg]; for (const key in rules) { const rule = rules[key]; if (typeof rule != "object") continue; const { $data } = rule.definition; const schema = keywords[key]; if ($data && schema) keywords[key] = schemaOrData(schema); } } return metaSchema; } _removeAllSchemas(schemas, regex) { for (const keyRef in schemas) { const sch = schemas[keyRef]; if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef]; } else if (sch && !sch.meta) { this._cache.delete(sch.schema); delete schemas[keyRef]; } } } } _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { let id; const { schemaId } = this.opts; if (typeof schema == "object") { id = schema[schemaId]; } else { if (this.opts.jtd) throw new Error("schema must be object"); else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); } let sch = this._cache.get(schema); if (sch !== void 0) return sch; baseId = (0, resolve_1.normalizeId)(id || baseId); const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs }); this._cache.set(sch.schema, sch); if (addSchema && !baseId.startsWith("#")) { if (baseId) this._checkUnique(baseId); this.refs[baseId] = sch; } if (validateSchema) this.validateSchema(schema, true); return sch; } _checkUnique(id) { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`); } } _compileSchemaEnv(sch) { if (sch.meta) this._compileMetaSchema(sch); else compile_1.compileSchema.call(this, sch); if (!sch.validate) throw new Error("ajv implementation error"); return sch.validate; } _compileMetaSchema(sch) { const currentOpts = this.opts; this.opts = this._metaOpts; try { compile_1.compileSchema.call(this, sch); } finally { this.opts = currentOpts; } } }; Ajv2.ValidationError = validation_error_1.default; Ajv2.MissingRefError = ref_error_1.default; exports2.default = Ajv2; function checkOptions(checkOpts, options, msg, log = "error") { for (const key in checkOpts) { const opt = key; if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); } } function getSchEnv(keyRef) { keyRef = (0, resolve_1.normalizeId)(keyRef); return this.schemas[keyRef] || this.refs[keyRef]; } function addInitialSchemas() { const optsSchemas = this.opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); } function addInitialFormats() { for (const name in this.opts.formats) { const format = this.opts.formats[name]; if (format) this.addFormat(name, format); } } function addInitialKeywords(defs) { if (Array.isArray(defs)) { this.addVocabulary(defs); return; } this.logger.warn("keywords option as map is deprecated, pass array"); for (const keyword in defs) { const def = defs[keyword]; if (!def.keyword) def.keyword = keyword; this.addKeyword(def); } } function getMetaSchemaOptions() { const metaOpts = { ...this.opts }; for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; return metaOpts; } var noLogs = { log() { }, warn() { }, error() { } }; function getLogger(logger) { if (logger === false) return noLogs; if (logger === void 0) return console; if (logger.log && logger.warn && logger.error) return logger; throw new Error("logger must implement log, warn and error methods"); } var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; function checkKeyword(keyword, def) { const { RULES } = this; (0, util_1.eachItem)(keyword, (kwd) => { if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); }); if (!def) return; if (def.$data && !("code" in def || "validate" in def)) { throw new Error('$data keyword must have "code" or "validate" function'); } } function addRule(keyword, definition, dataType) { var _a2; const post = definition === null || definition === void 0 ? void 0 : definition.post; if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); const { RULES } = this; let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.rules.push(ruleGroup); } RULES.keywords[keyword] = true; if (!definition) return; const rule = { keyword, definition: { ...definition, type: (0, dataType_1.getJSONTypes)(definition.type), schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } }; if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); else ruleGroup.rules.push(rule); RULES.all[keyword] = rule; (_a2 = definition.implements) === null || _a2 === void 0 ? void 0 : _a2.forEach((kwd) => this.addKeyword(kwd)); } function addBeforeRule(ruleGroup, rule, before) { const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); if (i >= 0) { ruleGroup.rules.splice(i, 0, rule); } else { ruleGroup.rules.push(rule); this.logger.warn(`rule ${before} is not defined`); } } function keywordMetaschema(def) { let { metaSchema } = def; if (metaSchema === void 0) return; if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); def.validateSchema = this.compile(metaSchema, true); } var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; function schemaOrData(schema) { return { anyOf: [schema, $dataRef] }; } } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js var require_id2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var def = { keyword: "id", code() { throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js var require_ref2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.callRef = exports2.getValidate = void 0; var ref_error_1 = require_ref_error2(); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var compile_1 = require_compile3(); var util_1 = require_util5(); var def = { keyword: "$ref", schemaType: "string", code(cxt) { const { gen, schema: $ref, it } = cxt; const { baseId, schemaEnv: env, validateName, opts, self } = it; const { root } = env; if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); return inlineRefSchema(schOrEnv); function callRootRef() { if (env === root) return callRef(cxt, validateName, env, env.$async); const rootName = gen.scopeValue("root", { ref: root }); return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); } function callValidate(sch) { const v = getValidate(cxt, sch); callRef(cxt, v, sch, sch.$async); } function inlineRefSchema(sch) { const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); const valid = gen.name("valid"); const schCxt = cxt.subschema({ schema: sch, dataTypes: [], schemaPath: codegen_1.nil, topSchemaRef: schName, errSchemaPath: $ref }, valid); cxt.mergeEvaluated(schCxt); cxt.ok(valid); } } }; function getValidate(cxt, sch) { const { gen } = cxt; return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; } exports2.getValidate = getValidate; function callRef(cxt, v, sch, $async) { const { gen, it } = cxt; const { allErrors, schemaEnv: env, opts } = it; const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; if ($async) callAsyncRef(); else callSyncRef(); function callAsyncRef() { if (!env.$async) throw new Error("async schema referenced by sync schema"); const valid = gen.let("valid"); gen.try(() => { gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); addEvaluatedFrom(v); if (!allErrors) gen.assign(valid, true); }, (e) => { gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); addErrorsFrom(e); if (!allErrors) gen.assign(valid, false); }); cxt.ok(valid); } function callSyncRef() { cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); } function addErrorsFrom(source) { const errs = (0, codegen_1._)`${source}.errors`; gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); } function addEvaluatedFrom(source) { var _a2; if (!it.opts.unevaluated) return; const schEvaluated = (_a2 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a2 === void 0 ? void 0 : _a2.evaluated; if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== void 0) { it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } } else { const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== void 0) { it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } } else { const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } } } exports2.callRef = callRef; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js var require_core4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var id_1 = require_id2(); var ref_1 = require_ref2(); var core = [ "$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", id_1.default, ref_1.default ]; exports2.default = core; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js var require_limitNumber2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var ops = codegen_1.operators; var KWDs = { maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error48 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; var def = { keyword: Object.keys(KWDs), type: "number", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode } = cxt; cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js var require_multipleOf2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error48 = { message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` }; var def = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error: error48, code(cxt) { const { gen, data, schemaCode, it } = cxt; const prec = it.opts.multipleOfPrecision; const res = gen.let("res"); const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js var require_ucs2length2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); function ucs2length(str) { const len = str.length; let length = 0; let pos = 0; let value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 55296 && value <= 56319 && pos < len) { value = str.charCodeAt(pos); if ((value & 64512) === 56320) pos++; } } return length; } exports2.default = ucs2length; ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js var require_limitLength2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var ucs2length_1 = require_ucs2length2(); var error48 = { message({ keyword, schemaCode }) { const comp = keyword === "maxLength" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode, it } = cxt; const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js var require_pattern2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code4(); var util_1 = require_util5(); var codegen_1 = require_codegen2(); var error48 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` }; var def = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error: error48, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; const u = it.opts.unicodeRegExp ? "u" : ""; if ($data) { const { regExp } = it.opts.code; const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); const valid = gen.let("valid"); gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); cxt.fail$data((0, codegen_1._)`!${valid}`); } else { const regExp = (0, code_1.usePattern)(cxt, schema); cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js var require_limitProperties2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error48 = { message({ keyword, schemaCode }) { const comp = keyword === "maxProperties" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js var require_required2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var error48 = { message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` }; var def = { keyword: "required", type: "object", schemaType: "array", $data: true, error: error48, code(cxt) { const { gen, schema, schemaCode, data, $data, it } = cxt; const { opts } = it; if (!$data && schema.length === 0) return; const useLoop = schema.length >= opts.loopRequired; if (it.allErrors) allErrorsMode(); else exitOnErrorMode(); if (opts.strictRequired) { const props = cxt.parentSchema.properties; const { definedProperties } = cxt.it; for (const requiredKey of schema) { if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); } } } function allErrorsMode() { if (useLoop || $data) { cxt.block$data(codegen_1.nil, loopAllRequired); } else { for (const prop of schema) { (0, code_1.checkReportMissingProp)(cxt, prop); } } } function exitOnErrorMode() { const missing = gen.let("missing"); if (useLoop || $data) { const valid = gen.let("valid", true); cxt.block$data(valid, () => loopUntilMissing(missing, valid)); cxt.ok(valid); } else { gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } function loopAllRequired() { gen.forOf("prop", schemaCode, (prop) => { cxt.setParams({ missingProperty: prop }); gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); }); } function loopUntilMissing(missing, valid) { cxt.setParams({ missingProperty: missing }); gen.forOf(missing, schemaCode, () => { gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); gen.if((0, codegen_1.not)(valid), () => { cxt.error(); gen.break(); }); }, codegen_1.nil); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js var require_limitItems2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error48 = { message({ keyword, schemaCode }) { const comp = keyword === "maxItems" ? "more" : "fewer"; return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; }, params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` }; var def = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error: error48, code(cxt) { const { keyword, data, schemaCode } = cxt; const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js var require_equal2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var equal = require_fast_deep_equal(); equal.code = 'require("ajv/dist/runtime/equal").default'; exports2.default = equal; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js var require_uniqueItems2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var dataType_1 = require_dataType2(); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var equal_1 = require_equal2(); var error48 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` }; var def = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error: error48, code(cxt) { const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; if (!$data && !schema) return; const valid = gen.let("valid"); const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); cxt.ok(valid); function validateUniqueItems() { const i = gen.let("i", (0, codegen_1._)`${data}.length`); const j = gen.let("j"); cxt.setParams({ i, j }); gen.assign(valid, true); gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); } function canOptimize() { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); } function loopN(i, j) { const item = gen.name("item"); const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); const indices = gen.const("indices", (0, codegen_1._)`{}`); gen.for((0, codegen_1._)`;${i}--;`, () => { gen.let(item, (0, codegen_1._)`${data}[${i}]`); gen.if(wrongType, (0, codegen_1._)`continue`); if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); cxt.error(); gen.assign(valid, false).break(); }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); }); } function loopN2(i, j) { const eql = (0, util_1.useFunc)(gen, equal_1.default); const outer = gen.name("outer"); gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error(); gen.assign(valid, false).break(outer); }))); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js var require_const2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var equal_1 = require_equal2(); var error48 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` }; var def = { keyword: "const", $data: true, error: error48, code(cxt) { const { gen, data, $data, schemaCode, schema } = cxt; if ($data || schema && typeof schema == "object") { cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); } else { cxt.fail((0, codegen_1._)`${schema} !== ${data}`); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js var require_enum2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var equal_1 = require_equal2(); var error48 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` }; var def = { keyword: "enum", schemaType: "array", $data: true, error: error48, code(cxt) { const { gen, data, $data, schema, schemaCode, it } = cxt; if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); const useLoop = schema.length >= it.opts.loopEnum; let eql; const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); let valid; if (useLoop || $data) { valid = gen.let("valid"); cxt.block$data(valid, loopEnum); } else { if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const vSchema = gen.const("vSchema", schemaCode); valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); } cxt.pass(valid); function loopEnum() { gen.assign(valid, false); gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } function equalCode(vSchema, i) { const sch = schema[i]; return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js var require_validation3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var limitNumber_1 = require_limitNumber2(); var multipleOf_1 = require_multipleOf2(); var limitLength_1 = require_limitLength2(); var pattern_1 = require_pattern2(); var limitProperties_1 = require_limitProperties2(); var required_1 = require_required2(); var limitItems_1 = require_limitItems2(); var uniqueItems_1 = require_uniqueItems2(); var const_1 = require_const2(); var enum_1 = require_enum2(); var validation = [ // number limitNumber_1.default, multipleOf_1.default, // string limitLength_1.default, pattern_1.default, // object limitProperties_1.default, required_1.default, // array limitItems_1.default, uniqueItems_1.default, // any { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, const_1.default, enum_1.default ]; exports2.default = validation; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js var require_additionalItems2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateAdditionalItems = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util5(); var error48 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error: error48, code(cxt) { const { parentSchema, it } = cxt; const { items } = parentSchema; if (!Array.isArray(items)) { (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; } validateAdditionalItems(cxt, items); } }; function validateAdditionalItems(cxt, items) { const { gen, schema, data, keyword, it } = cxt; it.items = true; const len = gen.const("len", (0, codegen_1._)`${data}.length`); if (schema === false) { cxt.setParams({ len: items.length }); cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); cxt.ok(valid); } function validateItems(valid) { gen.forRange("i", items.length, len, (i) => { cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); }); } } exports2.validateAdditionalItems = validateAdditionalItems; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js var require_items2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateTuple = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util5(); var code_1 = require_code4(); var def = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(cxt) { const { schema, it } = cxt; if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; cxt.ok((0, code_1.validateArray)(cxt)); } }; function validateTuple(cxt, extraItems, schArr = cxt.schema) { const { gen, parentSchema, data, keyword, it } = cxt; checkStrictTuple(parentSchema); if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } const valid = gen.name("valid"); const len = gen.const("len", (0, codegen_1._)`${data}.length`); schArr.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ keyword, schemaProp: i, dataProp: i }, valid)); cxt.ok(valid); }); function checkStrictTuple(sch) { const { opts, errSchemaPath } = it; const l = schArr.length; const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); } } } exports2.validateTuple = validateTuple; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js var require_prefixItems2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var items_1 = require_items2(); var def = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js var require_items20202 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var code_1 = require_code4(); var additionalItems_1 = require_additionalItems2(); var error48 = { message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` }; var def = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error: error48, code(cxt) { const { schema, parentSchema, it } = cxt; const { prefixItems } = parentSchema; it.items = true; if ((0, util_1.alwaysValidSchema)(it, schema)) return; if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); else cxt.ok((0, code_1.validateArray)(cxt)); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js var require_contains2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var error48 = { message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` }; var def = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error: error48, code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; let min; let max; const { minContains, maxContains } = parentSchema; if (it.opts.next) { min = minContains === void 0 ? 1 : minContains; max = maxContains; } else { min = 1; } const len = gen.const("len", (0, codegen_1._)`${data}.length`); cxt.setParams({ min, max }); if (max === void 0 && min === 0) { (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); return; } if (max !== void 0 && min > max) { (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); cxt.fail(); return; } if ((0, util_1.alwaysValidSchema)(it, schema)) { let cond = (0, codegen_1._)`${len} >= ${min}`; if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; cxt.pass(cond); return; } it.items = true; const valid = gen.name("valid"); if (max === void 0 && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())); } else if (min === 0) { gen.let(valid, true); if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); } else { gen.let(valid, false); validateItemsWithCount(); } cxt.result(valid, () => cxt.reset()); function validateItemsWithCount() { const schValid = gen.name("_valid"); const count = gen.let("count", 0); validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); } function validateItems(_valid, block) { gen.forRange("i", 0, len, (i) => { cxt.subschema({ keyword: "contains", dataProp: i, dataPropType: util_1.Type.Num, compositeRule: true }, _valid); block(); }); } function checkLimits(count) { gen.code((0, codegen_1._)`${count}++`); if (max === void 0) { gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); } else { gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); if (min === 1) gen.assign(valid, true); else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); } } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js var require_dependencies2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0; var codegen_1 = require_codegen2(); var util_1 = require_util5(); var code_1 = require_code4(); exports2.error = { message: ({ params: { property, depsCount, deps } }) => { const property_ies = depsCount === 1 ? "property" : "properties"; return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; }, params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, missingProperty: ${missingProperty}, depsCount: ${depsCount}, deps: ${deps}}` // TODO change to reference }; var def = { keyword: "dependencies", type: "object", schemaType: "object", error: exports2.error, code(cxt) { const [propDeps, schDeps] = splitDependencies(cxt); validatePropertyDeps(cxt, propDeps); validateSchemaDeps(cxt, schDeps); } }; function splitDependencies({ schema }) { const propertyDeps = {}; const schemaDeps = {}; for (const key in schema) { if (key === "__proto__") continue; const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; deps[key] = schema[key]; } return [propertyDeps, schemaDeps]; } function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { const { gen, data, it } = cxt; if (Object.keys(propertyDeps).length === 0) return; const missing = gen.let("missing"); for (const prop in propertyDeps) { const deps = propertyDeps[prop]; if (deps.length === 0) continue; const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", ") }); if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { (0, code_1.checkReportMissingProp)(cxt, depProp); } }); } else { gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); (0, code_1.reportMissingProp)(cxt, missing); gen.else(); } } } exports2.validatePropertyDeps = validatePropertyDeps; function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { const { gen, data, keyword, it } = cxt; const valid = gen.name("valid"); for (const prop in schemaDeps) { if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; gen.if( (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); cxt.mergeValidEvaluated(schCxt, valid); }, () => gen.var(valid, true) // TODO var ); cxt.ok(valid); } } exports2.validateSchemaDeps = validateSchemaDeps; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js var require_propertyNames2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var error48 = { message: "property name must be valid", params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` }; var def = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error: error48, code(cxt) { const { gen, schema, data, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) return; const valid = gen.name("valid"); gen.forIn("key", data, (key) => { cxt.setParams({ propertyName: key }); cxt.subschema({ keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true }, valid); gen.if((0, codegen_1.not)(valid), () => { cxt.error(true); if (!it.allErrors) gen.break(); }); }); cxt.ok(valid); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js var require_additionalProperties2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var names_1 = require_names2(); var util_1 = require_util5(); var error48 = { message: "must NOT have additional properties", params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` }; var def = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error: error48, code(cxt) { const { gen, schema, parentSchema, data, errsCount, it } = cxt; if (!errsCount) throw new Error("ajv implementation error"); const { allErrors, opts } = it; it.props = true; if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; const props = (0, code_1.allSchemaProperties)(parentSchema.properties); const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); checkAdditionalProperties(); cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); function checkAdditionalProperties() { gen.forIn("key", data, (key) => { if (!props.length && !patProps.length) additionalPropertyCode(key); else gen.if(isAdditional(key), () => additionalPropertyCode(key)); }); } function isAdditional(key) { let definedProp; if (props.length > 8) { const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); } else if (props.length) { definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); } else { definedProp = codegen_1.nil; } if (patProps.length) { definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); } return (0, codegen_1.not)(definedProp); } function deleteAdditional(key) { gen.code((0, codegen_1._)`delete ${data}[${key}]`); } function additionalPropertyCode(key) { if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { deleteAdditional(key); return; } if (schema === false) { cxt.setParams({ additionalProperty: key }); cxt.error(); if (!allErrors) gen.break(); return; } if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { const valid = gen.name("valid"); if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false); gen.if((0, codegen_1.not)(valid), () => { cxt.reset(); deleteAdditional(key); }); } else { applyAdditionalSchema(key, valid); if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); } } } function applyAdditionalSchema(key, valid, errors) { const subschema = { keyword: "additionalProperties", dataProp: key, dataPropType: util_1.Type.Str }; if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false }); } cxt.subschema(subschema, valid); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js var require_properties2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var validate_1 = require_validate2(); var code_1 = require_code4(); var util_1 = require_util5(); var additionalProperties_1 = require_additionalProperties2(); var def = { keyword: "properties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, parentSchema, data, it } = cxt; if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } const allProps = (0, code_1.allSchemaProperties)(schema); for (const prop of allProps) { it.definedProperties.add(prop); } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); } const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); if (properties.length === 0) return; const valid = gen.name("valid"); for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop); } else { gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); applyPropertySchema(prop); if (!it.allErrors) gen.else().var(valid, true); gen.endIf(); } cxt.it.definedProperties.add(prop); cxt.ok(valid); } function hasDefault(prop) { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; } function applyPropertySchema(prop) { cxt.subschema({ keyword: "properties", schemaProp: prop, dataProp: prop }, valid); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js var require_patternProperties2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code4(); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var util_2 = require_util5(); var def = { keyword: "patternProperties", type: "object", schemaType: "object", code(cxt) { const { gen, schema, data, parentSchema, it } = cxt; const { opts } = it; const patterns = (0, code_1.allSchemaProperties)(schema); const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { return; } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; const valid = gen.name("valid"); if (it.props !== true && !(it.props instanceof codegen_1.Name)) { it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); } const { props } = it; validatePatternProperties(); function validatePatternProperties() { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat); if (it.allErrors) { validateProperties(pat); } else { gen.var(valid, true); validateProperties(pat); gen.if(valid); } } } function checkMatchingProperties(pat) { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } function validateProperties(pat) { gen.forIn("key", data, (key) => { gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat); if (!alwaysValid) { cxt.subschema({ keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: util_2.Type.Str }, valid); } if (it.opts.unevaluated && props !== true) { gen.assign((0, codegen_1._)`${props}[${key}]`, true); } else if (!alwaysValid && !it.allErrors) { gen.if((0, codegen_1.not)(valid), () => gen.break()); } }); }); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js var require_not2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util5(); var def = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(cxt) { const { gen, schema, it } = cxt; if ((0, util_1.alwaysValidSchema)(it, schema)) { cxt.fail(); return; } const valid = gen.name("valid"); cxt.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, valid); cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); }, error: { message: "must NOT be valid" } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js var require_anyOf2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var code_1 = require_code4(); var def = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: code_1.validateUnion, error: { message: "must match a schema in anyOf" } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js var require_oneOf2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var error48 = { message: "must match exactly one schema in oneOf", params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` }; var def = { keyword: "oneOf", schemaType: "array", trackErrors: true, error: error48, code(cxt) { const { gen, schema, parentSchema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); if (it.opts.discriminator && parentSchema.discriminator) return; const schArr = schema; const valid = gen.let("valid", false); const passing = gen.let("passing", null); const schValid = gen.name("_valid"); cxt.setParams({ passing }); gen.block(validateOneOf); cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); function validateOneOf() { schArr.forEach((sch, i) => { let schCxt; if ((0, util_1.alwaysValidSchema)(it, sch)) { gen.var(schValid, true); } else { schCxt = cxt.subschema({ keyword: "oneOf", schemaProp: i, compositeRule: true }, schValid); } if (i > 0) { gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); } gen.if(schValid, () => { gen.assign(valid, true); gen.assign(passing, i); if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); }); }); } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js var require_allOf2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util5(); var def = { keyword: "allOf", schemaType: "array", code(cxt) { const { gen, schema, it } = cxt; if (!Array.isArray(schema)) throw new Error("ajv implementation error"); const valid = gen.name("valid"); schema.forEach((sch, i) => { if ((0, util_1.alwaysValidSchema)(it, sch)) return; const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); cxt.ok(valid); cxt.mergeEvaluated(schCxt); }); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js var require_if2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var util_1 = require_util5(); var error48 = { message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` }; var def = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error: error48, code(cxt) { const { gen, parentSchema, it } = cxt; if (parentSchema.then === void 0 && parentSchema.else === void 0) { (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); } const hasThen = hasSchema(it, "then"); const hasElse = hasSchema(it, "else"); if (!hasThen && !hasElse) return; const valid = gen.let("valid", true); const schValid = gen.name("_valid"); validateIf(); cxt.reset(); if (hasThen && hasElse) { const ifClause = gen.let("ifClause"); cxt.setParams({ ifClause }); gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); } else if (hasThen) { gen.if(schValid, validateClause("then")); } else { gen.if((0, codegen_1.not)(schValid), validateClause("else")); } cxt.pass(valid, () => cxt.error(true)); function validateIf() { const schCxt = cxt.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, schValid); cxt.mergeEvaluated(schCxt); } function validateClause(keyword, ifClause) { return () => { const schCxt = cxt.subschema({ keyword }, schValid); gen.assign(valid, schValid); cxt.mergeValidEvaluated(schCxt, valid); if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); else cxt.setParams({ ifClause: keyword }); }; } } }; function hasSchema(it, keyword) { const schema = it.schema[keyword]; return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); } exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js var require_thenElse2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var util_1 = require_util5(); var def = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword, parentSchema, it }) { if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js var require_applicator2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var additionalItems_1 = require_additionalItems2(); var prefixItems_1 = require_prefixItems2(); var items_1 = require_items2(); var items2020_1 = require_items20202(); var contains_1 = require_contains2(); var dependencies_1 = require_dependencies2(); var propertyNames_1 = require_propertyNames2(); var additionalProperties_1 = require_additionalProperties2(); var properties_1 = require_properties2(); var patternProperties_1 = require_patternProperties2(); var not_1 = require_not2(); var anyOf_1 = require_anyOf2(); var oneOf_1 = require_oneOf2(); var allOf_1 = require_allOf2(); var if_1 = require_if2(); var thenElse_1 = require_thenElse2(); function getApplicator(draft2020 = false) { const applicator = [ // any not_1.default, anyOf_1.default, oneOf_1.default, allOf_1.default, if_1.default, thenElse_1.default, // object propertyNames_1.default, additionalProperties_1.default, dependencies_1.default, properties_1.default, patternProperties_1.default ]; if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); else applicator.push(additionalItems_1.default, items_1.default); applicator.push(contains_1.default); return applicator; } exports2.default = getApplicator; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js var require_format3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var error48 = { message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` }; var def = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error: error48, code(cxt, ruleType) { const { gen, data, $data, schema, schemaCode, it } = cxt; const { opts, errSchemaPath, schemaEnv, self } = it; if (!opts.validateFormats) return; if ($data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); const fType = gen.let("fType"); const format = gen.let("format"); gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); function unknownFmt() { if (opts.strictSchema === false) return codegen_1.nil; return (0, codegen_1._)`${schemaCode} && !${format}`; } function invalidFmt() { const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; } } function validateFormat() { const formatDef = self.formats[schema]; if (!formatDef) { unknownFormat(); return; } if (formatDef === true) return; const [fmtType, format, fmtRef] = getFormat(formatDef); if (fmtType === ruleType) cxt.pass(validCondition()); function unknownFormat() { if (opts.strictSchema === false) { self.logger.warn(unknownMsg()); return; } throw new Error(unknownMsg()); function unknownMsg() { return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; } } function getFormat(fmtDef) { const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; } return ["string", fmtDef, fmt]; } function validCondition() { if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { if (!schemaEnv.$async) throw new Error("async format in sync schema"); return (0, codegen_1._)`await ${fmtRef}(${data})`; } return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js var require_format4 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var format_1 = require_format3(); var format = [format_1.default]; exports2.default = format; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js var require_metadata2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.contentVocabulary = exports2.metadataVocabulary = void 0; exports2.metadataVocabulary = [ "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples" ]; exports2.contentVocabulary = [ "contentMediaType", "contentEncoding", "contentSchema" ]; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js var require_draft72 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var core_1 = require_core4(); var validation_1 = require_validation3(); var applicator_1 = require_applicator2(); var format_1 = require_format4(); var metadata_1 = require_metadata2(); var draft7Vocabularies = [ core_1.default, validation_1.default, (0, applicator_1.default)(), format_1.default, metadata_1.metadataVocabulary, metadata_1.contentVocabulary ]; exports2.default = draft7Vocabularies; } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js var require_types3 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DiscrError = void 0; var DiscrError; (function(DiscrError2) { DiscrError2["Tag"] = "tag"; DiscrError2["Mapping"] = "mapping"; })(DiscrError || (exports2.DiscrError = DiscrError = {})); } }); // node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js var require_discriminator2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var codegen_1 = require_codegen2(); var types_1 = require_types3(); var compile_1 = require_compile3(); var ref_error_1 = require_ref_error2(); var util_1 = require_util5(); var error48 = { message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` }; var def = { keyword: "discriminator", type: "object", schemaType: "object", error: error48, code(cxt) { const { gen, data, schema, parentSchema, it } = cxt; const { oneOf } = parentSchema; if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option"); } const tagName = schema.propertyName; if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); if (schema.mapping) throw new Error("discriminator: mapping is not supported"); if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); const valid = gen.let("valid", false); const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); cxt.ok(valid); function validateMapping() { const mapping = getMapping(); gen.if(false); for (const tagValue in mapping) { gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); gen.assign(valid, applyTagSchema(mapping[tagValue])); } gen.else(); cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); gen.endIf(); } function applyTagSchema(schemaProp) { const _valid = gen.name("valid"); const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); cxt.mergeEvaluated(schCxt, codegen_1.Name); return _valid; } function getMapping() { var _a2; const oneOfMapping = {}; const topRequired = hasRequired(parentSchema); let tagRequired = true; for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i]; if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { const ref = sch.$ref; sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); } const propSch = (_a2 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a2 === void 0 ? void 0 : _a2[tagName]; if (typeof propSch != "object") { throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); } tagRequired = tagRequired && (topRequired || hasRequired(sch)); addMappings(propSch, i); } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); return oneOfMapping; function hasRequired({ required: required2 }) { return Array.isArray(required2) && required2.includes(tagName); } function addMappings(sch, i) { if (sch.const) { addMapping(sch.const, i); } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i); } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } } function addMapping(tagValue, i) { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`); } oneOfMapping[tagValue] = i; } } } }; exports2.default = def; } }); // node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json var require_json_schema_draft_072 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports2, module2) { module2.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [ { $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true } ] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; } }); // node_modules/ajv-formats/node_modules/ajv/dist/ajv.js var require_ajv2 = __commonJS({ "node_modules/ajv-formats/node_modules/ajv/dist/ajv.js"(exports2, module2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.MissingRefError = exports2.ValidationError = exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = exports2.Ajv = void 0; var core_1 = require_core3(); var draft7_1 = require_draft72(); var discriminator_1 = require_discriminator2(); var draft7MetaSchema = require_json_schema_draft_072(); var META_SUPPORT_DATA = ["/properties"]; var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; var Ajv2 = class extends core_1.default { _addVocabularies() { super._addVocabularies(); draft7_1.default.forEach((v) => this.addVocabulary(v)); if (this.opts.discriminator) this.addKeyword(discriminator_1.default); } _addDefaultMetaSchema() { super._addDefaultMetaSchema(); if (!this.opts.meta) return; const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; } defaultMeta() { return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; exports2.Ajv = Ajv2; module2.exports = exports2 = Ajv2; module2.exports.Ajv = Ajv2; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = Ajv2; var validate_1 = require_validate2(); Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() { return validate_1.KeywordCxt; } }); var codegen_1 = require_codegen2(); Object.defineProperty(exports2, "_", { enumerable: true, get: function() { return codegen_1._; } }); Object.defineProperty(exports2, "str", { enumerable: true, get: function() { return codegen_1.str; } }); Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() { return codegen_1.stringify; } }); Object.defineProperty(exports2, "nil", { enumerable: true, get: function() { return codegen_1.nil; } }); Object.defineProperty(exports2, "Name", { enumerable: true, get: function() { return codegen_1.Name; } }); Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() { return codegen_1.CodeGen; } }); var validation_error_1 = require_validation_error2(); Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: function() { return validation_error_1.default; } }); var ref_error_1 = require_ref_error2(); Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: function() { return ref_error_1.default; } }); } }); // node_modules/ajv-formats/dist/limit.js var require_limit = __commonJS({ "node_modules/ajv-formats/dist/limit.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.formatLimitDefinition = void 0; var ajv_1 = require_ajv2(); var codegen_1 = require_codegen2(); var ops = codegen_1.operators; var KWDs = { formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error48 = { message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; exports2.formatLimitDefinition = { keyword: Object.keys(KWDs), type: "string", schemaType: "string", $data: true, error: error48, code(cxt) { const { gen, data, schemaCode, keyword, it } = cxt; const { opts, self } = it; if (!opts.validateFormats) return; const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); if (fCxt.$data) validate$DataFormat(); else validateFormat(); function validate$DataFormat() { const fmts = gen.scopeValue("formats", { ref: self.formats, code: opts.code.formats }); const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); } function validateFormat() { const format = fCxt.schema; const fmtDef = self.formats[format]; if (!fmtDef || fmtDef === true) return; if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); } const fmt = gen.scopeValue("formats", { key: format, ref: fmtDef, code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 }); cxt.fail$data(compareCode(fmt)); } function compareCode(fmt) { return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; } }, dependencies: ["format"] }; var formatLimitPlugin = (ajv) => { ajv.addKeyword(exports2.formatLimitDefinition); return ajv; }; exports2.default = formatLimitPlugin; } }); // node_modules/ajv-formats/dist/index.js var require_dist5 = __commonJS({ "node_modules/ajv-formats/dist/index.js"(exports2, module2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var formats_1 = require_formats(); var limit_1 = require_limit(); var codegen_1 = require_codegen2(); var fullName = new codegen_1.Name("fullFormats"); var fastName = new codegen_1.Name("fastFormats"); var formatsPlugin = (ajv, opts = { keywords: true }) => { if (Array.isArray(opts)) { addFormats(ajv, opts, formats_1.fullFormats, fullName); return ajv; } const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; const list = opts.formats || formats_1.formatNames; addFormats(ajv, list, formats, exportName); if (opts.keywords) (0, limit_1.default)(ajv); return ajv; }; formatsPlugin.get = (name, mode = "full") => { const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; const f = formats[name]; if (!f) throw new Error(`Unknown format "${name}"`); return f; }; function addFormats(ajv, list, fs, exportName) { var _a2; var _b; (_a2 = (_b = ajv.opts.code).formats) !== null && _a2 !== void 0 ? _a2 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; for (const f of list) ajv.addFormat(f, fs[f]); } module2.exports = exports2 = formatsPlugin; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.default = formatsPlugin; } }); // node_modules/bytes/index.js var require_bytes = __commonJS({ "node_modules/bytes/index.js"(exports2, module2) { "use strict"; module2.exports = bytes2; module2.exports.format = format; module2.exports.parse = parse3; var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; var map2 = { b: 1, kb: 1 << 10, mb: 1 << 20, gb: 1 << 30, tb: Math.pow(1024, 4), pb: Math.pow(1024, 5) }; var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; function bytes2(value, options) { if (typeof value === "string") { return parse3(value); } if (typeof value === "number") { return format(value, options); } return null; } function format(value, options) { if (!Number.isFinite(value)) { return null; } var mag = Math.abs(value); var thousandsSeparator = options && options.thousandsSeparator || ""; var unitSeparator = options && options.unitSeparator || ""; var decimalPlaces = options && options.decimalPlaces !== void 0 ? options.decimalPlaces : 2; var fixedDecimals = Boolean(options && options.fixedDecimals); var unit = options && options.unit || ""; if (!unit || !map2[unit.toLowerCase()]) { if (mag >= map2.pb) { unit = "PB"; } else if (mag >= map2.tb) { unit = "TB"; } else if (mag >= map2.gb) { unit = "GB"; } else if (mag >= map2.mb) { unit = "MB"; } else if (mag >= map2.kb) { unit = "KB"; } else { unit = "B"; } } var val = value / map2[unit.toLowerCase()]; var str = val.toFixed(decimalPlaces); if (!fixedDecimals) { str = str.replace(formatDecimalsRegExp, "$1"); } if (thousandsSeparator) { str = str.split(".").map(function(s, i) { return i === 0 ? s.replace(formatThousandsRegExp, thousandsSeparator) : s; }).join("."); } return str + unitSeparator + unit; } function parse3(val) { if (typeof val === "number" && !isNaN(val)) { return val; } if (typeof val !== "string") { return null; } var results = parseRegExp.exec(val); var floatValue; var unit = "b"; if (!results) { floatValue = parseInt(val, 10); unit = "b"; } else { floatValue = parseFloat(results[1]); unit = results[4].toLowerCase(); } if (isNaN(floatValue)) { return null; } return Math.floor(map2[unit] * floatValue); } } }); // node_modules/content-type/index.js var require_content_type = __commonJS({ "node_modules/content-type/index.js"(exports2) { "use strict"; var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/; var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; var QUOTE_REGEXP = /([\\"])/g; var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; exports2.format = format; exports2.parse = parse3; function format(obj) { if (!obj || typeof obj !== "object") { throw new TypeError("argument obj is required"); } var parameters = obj.parameters; var type = obj.type; if (!type || !TYPE_REGEXP.test(type)) { throw new TypeError("invalid type"); } var string4 = type; if (parameters && typeof parameters === "object") { var param; var params = Object.keys(parameters).sort(); for (var i = 0; i < params.length; i++) { param = params[i]; if (!TOKEN_REGEXP.test(param)) { throw new TypeError("invalid parameter name"); } string4 += "; " + param + "=" + qstring(parameters[param]); } } return string4; } function parse3(string4) { if (!string4) { throw new TypeError("argument string is required"); } var header = typeof string4 === "object" ? getcontenttype(string4) : string4; if (typeof header !== "string") { throw new TypeError("argument string is required to be a string"); } var index = header.indexOf(";"); var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); if (!TYPE_REGEXP.test(type)) { throw new TypeError("invalid media type"); } var obj = new ContentType(type.toLowerCase()); if (index !== -1) { var key; var match; var value; PARAM_REGEXP.lastIndex = index; while (match = PARAM_REGEXP.exec(header)) { if (match.index !== index) { throw new TypeError("invalid parameter format"); } index += match[0].length; key = match[1].toLowerCase(); value = match[2]; if (value.charCodeAt(0) === 34) { value = value.slice(1, -1); if (value.indexOf("\\") !== -1) { value = value.replace(QESC_REGEXP, "$1"); } } obj.parameters[key] = value; } if (index !== header.length) { throw new TypeError("invalid parameter format"); } } return obj; } function getcontenttype(obj) { var header; if (typeof obj.getHeader === "function") { header = obj.getHeader("content-type"); } else if (typeof obj.headers === "object") { header = obj.headers && obj.headers["content-type"]; } if (typeof header !== "string") { throw new TypeError("content-type header is missing from object"); } return header; } function qstring(val) { var str = String(val); if (TOKEN_REGEXP.test(str)) { return str; } if (str.length > 0 && !TEXT_REGEXP.test(str)) { throw new TypeError("invalid parameter value"); } return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"'; } function ContentType(type) { this.parameters = /* @__PURE__ */ Object.create(null); this.type = type; } } }); // node_modules/isexe/windows.js var require_windows = __commonJS({ "node_modules/isexe/windows.js"(exports2, module2) { module2.exports = isexe; isexe.sync = sync; var fs = require("fs"); function checkPathExt(path, options) { var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT; if (!pathext) { return true; } pathext = pathext.split(";"); if (pathext.indexOf("") !== -1) { return true; } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase(); if (p && path.substr(-p.length).toLowerCase() === p) { return true; } } return false; } function checkStat(stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false; } return checkPathExt(path, options); } function isexe(path, options, cb) { fs.stat(path, function(er, stat) { cb(er, er ? false : checkStat(stat, path, options)); }); } function sync(path, options) { return checkStat(fs.statSync(path), path, options); } } }); // node_modules/isexe/mode.js var require_mode = __commonJS({ "node_modules/isexe/mode.js"(exports2, module2) { module2.exports = isexe; isexe.sync = sync; var fs = require("fs"); function isexe(path, options, cb) { fs.stat(path, function(er, stat) { cb(er, er ? false : checkStat(stat, options)); }); } function sync(path, options) { return checkStat(fs.statSync(path), options); } function checkStat(stat, options) { return stat.isFile() && checkMode(stat, options); } function checkMode(stat, options) { var mod = stat.mode; var uid = stat.uid; var gid = stat.gid; var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid(); var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid(); var u = parseInt("100", 8); var g = parseInt("010", 8); var o = parseInt("001", 8); var ug = u | g; var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0; return ret; } } }); // node_modules/isexe/index.js var require_isexe = __commonJS({ "node_modules/isexe/index.js"(exports2, module2) { var fs = require("fs"); var core; if (process.platform === "win32" || global.TESTING_WINDOWS) { core = require_windows(); } else { core = require_mode(); } module2.exports = isexe; isexe.sync = sync; function isexe(path, options, cb) { if (typeof options === "function") { cb = options; options = {}; } if (!cb) { if (typeof Promise !== "function") { throw new TypeError("callback not provided"); } return new Promise(function(resolve, reject) { isexe(path, options || {}, function(er, is) { if (er) { reject(er); } else { resolve(is); } }); }); } core(path, options || {}, function(er, is) { if (er) { if (er.code === "EACCES" || options && options.ignoreErrors) { er = null; is = false; } } cb(er, is); }); } function sync(path, options) { try { return core.sync(path, options || {}); } catch (er) { if (options && options.ignoreErrors || er.code === "EACCES") { return false; } else { throw er; } } } } }); // node_modules/which/which.js var require_which = __commonJS({ "node_modules/which/which.js"(exports2, module2) { var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys"; var path = require("path"); var COLON = isWindows ? ";" : ":"; var isexe = require_isexe(); var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }); var getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON; const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [ // windows always checks the cwd first ...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ "").split(colon) ]; const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : ""; const pathExt = isWindows ? pathExtExe.split(colon) : [""]; if (isWindows) { if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift(""); } return { pathEnv, pathExt, pathExtExe }; }; var which = (cmd, opt, cb) => { if (typeof opt === "function") { cb = opt; opt = {}; } if (!opt) opt = {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; const step = (i) => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)); const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; resolve(subStep(p, i, 0)); }); const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)); const ext = pathExt[ii]; isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext); else return resolve(p + ext); } return resolve(subStep(p, i, ii + 1)); }); }); return cb ? step(0).then((res) => cb(null, res), cb) : step(0); }; var whichSync = (cmd, opt) => { opt = opt || {}; const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); const found = []; for (let i = 0; i < pathEnv.length; i++) { const ppRaw = pathEnv[i]; const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; const pCmd = path.join(pathPart, cmd); const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; for (let j = 0; j < pathExt.length; j++) { const cur = p + pathExt[j]; try { const is = isexe.sync(cur, { pathExt: pathExtExe }); if (is) { if (opt.all) found.push(cur); else return cur; } } catch (ex) { } } } if (opt.all && found.length) return found; if (opt.nothrow) return null; throw getNotFoundError(cmd); }; module2.exports = which; which.sync = whichSync; } }); // node_modules/path-key/index.js var require_path_key = __commonJS({ "node_modules/path-key/index.js"(exports2, module2) { "use strict"; var pathKey = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== "win32") { return "PATH"; } return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path"; }; module2.exports = pathKey; module2.exports.default = pathKey; } }); // node_modules/cross-spawn/lib/util/resolveCommand.js var require_resolveCommand = __commonJS({ "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2, module2) { "use strict"; var path = require("path"); var which = require_which(); var getPathKey = require_path_key(); function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled; if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path.delimiter : void 0 }); } catch (e) { } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } if (resolved) { resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved); } return resolved; } function resolveCommand(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } module2.exports = resolveCommand; } }); // node_modules/cross-spawn/lib/util/escape.js var require_escape = __commonJS({ "node_modules/cross-spawn/lib/util/escape.js"(exports2, module2) { "use strict"; var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { arg = arg.replace(metaCharsRegExp, "^$1"); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { arg = `${arg}`; arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1"); arg = `"${arg}"`; arg = arg.replace(metaCharsRegExp, "^$1"); if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, "^$1"); } return arg; } module2.exports.command = escapeCommand; module2.exports.argument = escapeArgument; } }); // node_modules/shebang-regex/index.js var require_shebang_regex = __commonJS({ "node_modules/shebang-regex/index.js"(exports2, module2) { "use strict"; module2.exports = /^#!(.*)/; } }); // node_modules/shebang-command/index.js var require_shebang_command = __commonJS({ "node_modules/shebang-command/index.js"(exports2, module2) { "use strict"; var shebangRegex = require_shebang_regex(); module2.exports = (string4 = "") => { const match = string4.match(shebangRegex); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, "").split(" "); const binary = path.split("/").pop(); if (binary === "env") { return argument; } return argument ? `${binary} ${argument}` : binary; }; } }); // node_modules/cross-spawn/lib/util/readShebang.js var require_readShebang = __commonJS({ "node_modules/cross-spawn/lib/util/readShebang.js"(exports2, module2) { "use strict"; var fs = require("fs"); var shebangCommand = require_shebang_command(); function readShebang(command) { const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs.openSync(command, "r"); fs.readSync(fd, buffer, 0, size, 0); fs.closeSync(fd); } catch (e) { } return shebangCommand(buffer.toString()); } module2.exports = readShebang; } }); // node_modules/cross-spawn/lib/parse.js var require_parse5 = __commonJS({ "node_modules/cross-spawn/lib/parse.js"(exports2, module2) { "use strict"; var path = require("path"); var resolveCommand = require_resolveCommand(); var escape2 = require_escape(); var readShebang = require_readShebang(); var isWin2 = process.platform === "win32"; var isExecutableRegExp = /\.(?:com|exe)$/i; var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin2) { return parsed; } const commandFile = detectShebang(parsed); const needsShell = !isExecutableRegExp.test(commandFile); if (parsed.options.forceShell || needsShell) { const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); parsed.command = path.normalize(parsed.command); parsed.command = escape2.command(parsed.command); parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(" "); parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`]; parsed.command = process.env.comspec || "cmd.exe"; parsed.options.windowsVerbatimArguments = true; } return parsed; } function parse3(command, args, options) { if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; options = Object.assign({}, options); const parsed = { command, args, options, file: void 0, original: { command, args } }; return options.shell ? parsed : parseNonShell(parsed); } module2.exports = parse3; } }); // node_modules/cross-spawn/lib/enoent.js var require_enoent = __commonJS({ "node_modules/cross-spawn/lib/enoent.js"(exports2, module2) { "use strict"; var isWin2 = process.platform === "win32"; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: "ENOENT", errno: "ENOENT", syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args }); } function hookChildProcess(cp, parsed) { if (!isWin2) { return; } const originalEmit = cp.emit; cp.emit = function(name, arg1) { if (name === "exit") { const err = verifyENOENT(arg1, parsed); if (err) { return originalEmit.call(cp, "error", err); } } return originalEmit.apply(cp, arguments); }; } function verifyENOENT(status, parsed) { if (isWin2 && status === 1 && !parsed.file) { return notFoundError(parsed.original, "spawn"); } return null; } function verifyENOENTSync(status, parsed) { if (isWin2 && status === 1 && !parsed.file) { return notFoundError(parsed.original, "spawnSync"); } return null; } module2.exports = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError }; } }); // node_modules/cross-spawn/index.js var require_cross_spawn = __commonJS({ "node_modules/cross-spawn/index.js"(exports2, module2) { "use strict"; var cp = require("child_process"); var parse3 = require_parse5(); var enoent = require_enoent(); function spawn2(command, args, options) { const parsed = parse3(command, args, options); const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { const parsed = parse3(command, args, options); const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } module2.exports = spawn2; module2.exports.spawn = spawn2; module2.exports.sync = spawnSync; module2.exports._parse = parse3; module2.exports._enoent = enoent; } }); // packages/playwright-core/src/utilsBundle.ts var utilsBundle_exports = {}; __export(utilsBundle_exports, { CallToolRequestSchema: () => CallToolRequestSchema, Client: () => Client, HttpsProxyAgent: () => import_https_proxy_agent.HttpsProxyAgent, ListRootsRequestSchema: () => ListRootsRequestSchema, ListToolsRequestSchema: () => ListToolsRequestSchema, PNG: () => import_pngjs.PNG, PingRequestSchema: () => PingRequestSchema, ProgramOption: () => Option, ProgressNotificationSchema: () => ProgressNotificationSchema, SSEClientTransport: () => SSEClientTransport, SSEServerTransport: () => SSEServerTransport, Server: () => Server, SocksProxyAgent: () => import_socks_proxy_agent.SocksProxyAgent, StdioClientTransport: () => StdioClientTransport, StdioServerTransport: () => StdioServerTransport, StreamableHTTPClientTransport: () => StreamableHTTPClientTransport, StreamableHTTPServerTransport: () => StreamableHTTPServerTransport, chokidar: () => chokidar, colors: () => colors, debug: () => debug, diff: () => diff, dotenv: () => dotenv, enquirer: () => enquirer, getEastAsianWidth: () => getEastAsianWidth, getProxyForUrl: () => getProxyForUrl, getStream: () => getStream, gracefulFs: () => gracefulFs, httpProxyAgent: () => httpProxyAgent, ini: () => ini, jpegjs: () => jpegjs, json5: () => json5, mime: () => mime, minimatch: () => minimatch, onExit: () => onExit, open: () => open, program: () => program, progress: () => progress, retry: () => retry, socksProxyAgent: () => socksProxyAgent, sourceMapSupport: () => sourceMapSupport, ws: () => ws, wsReceiver: () => wsReceiver, wsSender: () => wsSender, wsServer: () => wsServer, yaml: () => yaml, yazl: () => yazl, z: () => zod_exports, zodToJsonSchema: () => zodToJsonSchema }); module.exports = __toCommonJS(utilsBundle_exports); var import_safe = __toESM(require_safe()); var import_debug = __toESM(require_src()); var iniLibrary = __toESM(require_ini()); // node_modules/diff/libesm/index.js var libesm_exports = {}; __export(libesm_exports, { Diff: () => Diff, FILE_HEADERS_ONLY: () => FILE_HEADERS_ONLY, INCLUDE_HEADERS: () => INCLUDE_HEADERS, OMIT_HEADERS: () => OMIT_HEADERS, applyPatch: () => applyPatch, applyPatches: () => applyPatches, arrayDiff: () => arrayDiff, canonicalize: () => canonicalize, characterDiff: () => characterDiff, convertChangesToDMP: () => convertChangesToDMP, convertChangesToXML: () => convertChangesToXML, createPatch: () => createPatch, createTwoFilesPatch: () => createTwoFilesPatch, cssDiff: () => cssDiff, diffArrays: () => diffArrays, diffChars: () => diffChars, diffCss: () => diffCss, diffJson: () => diffJson, diffLines: () => diffLines, diffSentences: () => diffSentences, diffTrimmedLines: () => diffTrimmedLines, diffWords: () => diffWords, diffWordsWithSpace: () => diffWordsWithSpace, formatPatch: () => formatPatch, jsonDiff: () => jsonDiff, lineDiff: () => lineDiff, parsePatch: () => parsePatch, reversePatch: () => reversePatch, sentenceDiff: () => sentenceDiff, structuredPatch: () => structuredPatch, wordDiff: () => wordDiff, wordsWithSpaceDiff: () => wordsWithSpaceDiff }); // node_modules/diff/libesm/diff/base.js var Diff = class { diff(oldStr, newStr, options = {}) { let callback; if (typeof options === "function") { callback = options; options = {}; } else if ("callback" in options) { callback = options.callback; } const oldString = this.castInput(oldStr, options); const newString = this.castInput(newStr, options); const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); const newTokens = this.removeEmpty(this.tokenize(newString, options)); return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); } diffWithOptionsObj(oldTokens, newTokens, options, callback) { var _a2; const done = (value) => { value = this.postProcess(value, options); if (callback) { setTimeout(function() { callback(value); }, 0); return void 0; } else { return value; } }; const newLen = newTokens.length, oldLen = oldTokens.length; let editLength = 1; let maxEditLength = newLen + oldLen; if (options.maxEditLength != null) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } const maxExecutionTime = (_a2 = options.timeout) !== null && _a2 !== void 0 ? _a2 : Infinity; const abortAfterTimestamp = Date.now() + maxExecutionTime; const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); } let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; const execEditLength = () => { for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { let basePath; const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { bestPath[diagonalPath - 1] = void 0; } let canAdd = false; if (addPath) { const addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } const canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { bestPath[diagonalPath] = void 0; continue; } if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { basePath = this.addToPath(addPath, true, false, 0, options); } else { basePath = this.addToPath(removePath, false, true, 1, options); } newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; }; if (callback) { (function exec() { setTimeout(function() { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(void 0); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { const ret = execEditLength(); if (ret) { return ret; } } } } addToPath(path, added, removed, oldPosInc, options) { const last = path.lastComponent; if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added, removed, previousComponent: last } }; } } extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { const newLen = newTokens.length, oldLen = oldTokens.length; let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { newPos++; oldPos++; commonCount++; if (options.oneChangePerToken) { basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; } } if (commonCount && !options.oneChangePerToken) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; } basePath.oldPos = oldPos; return newPos; } equals(left, right, options) { if (options.comparator) { return options.comparator(left, right); } else { return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } } removeEmpty(array2) { const ret = []; for (let i = 0; i < array2.length; i++) { if (array2[i]) { ret.push(array2[i]); } } return ret; } // eslint-disable-next-line @typescript-eslint/no-unused-vars castInput(value, options) { return value; } // eslint-disable-next-line @typescript-eslint/no-unused-vars tokenize(value, options) { return Array.from(value); } join(chars) { return chars.join(""); } postProcess(changeObjects, options) { return changeObjects; } get useLongestToken() { return false; } buildValues(lastComponent, newTokens, oldTokens) { const components = []; let nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); const componentLen = components.length; let componentPos = 0, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { const component = components[componentPos]; if (!component.removed) { if (!component.added && this.useLongestToken) { let value = newTokens.slice(newPos, newPos + component.count); value = value.map(function(value2, i) { const oldValue = oldTokens[oldPos + i]; return oldValue.length > value2.length ? oldValue : value2; }); component.value = this.join(value); } else { component.value = this.join(newTokens.slice(newPos, newPos + component.count)); } newPos += component.count; if (!component.added) { oldPos += component.count; } } else { component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); oldPos += component.count; } } return components; } }; // node_modules/diff/libesm/diff/character.js var CharacterDiff = class extends Diff { }; var characterDiff = new CharacterDiff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } // node_modules/diff/libesm/util/string.js function longestCommonPrefix(str1, str2) { let i; for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[i] != str2[i]) { return str1.slice(0, i); } } return str1.slice(0, i); } function longestCommonSuffix(str1, str2) { let i; if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) { return ""; } for (i = 0; i < str1.length && i < str2.length; i++) { if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) { return str1.slice(-i); } } return str1.slice(-i); } function replacePrefix(string4, oldPrefix, newPrefix) { if (string4.slice(0, oldPrefix.length) != oldPrefix) { throw Error(`string ${JSON.stringify(string4)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`); } return newPrefix + string4.slice(oldPrefix.length); } function replaceSuffix(string4, oldSuffix, newSuffix) { if (!oldSuffix) { return string4 + newSuffix; } if (string4.slice(-oldSuffix.length) != oldSuffix) { throw Error(`string ${JSON.stringify(string4)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`); } return string4.slice(0, -oldSuffix.length) + newSuffix; } function removePrefix(string4, oldPrefix) { return replacePrefix(string4, oldPrefix, ""); } function removeSuffix(string4, oldSuffix) { return replaceSuffix(string4, oldSuffix, ""); } function maximumOverlap(string1, string22) { return string22.slice(0, overlapCount(string1, string22)); } function overlapCount(a, b) { let startA = 0; if (a.length > b.length) { startA = a.length - b.length; } let endB = b.length; if (a.length < b.length) { endB = a.length; } const map2 = Array(endB); let k = 0; map2[0] = 0; for (let j = 1; j < endB; j++) { if (b[j] == b[k]) { map2[j] = map2[k]; } else { map2[j] = k; } while (k > 0 && b[j] != b[k]) { k = map2[k]; } if (b[j] == b[k]) { k++; } } k = 0; for (let i = startA; i < a.length; i++) { while (k > 0 && a[i] != b[k]) { k = map2[k]; } if (a[i] == b[k]) { k++; } } return k; } function hasOnlyWinLineEndings(string4) { return string4.includes("\r\n") && !string4.startsWith("\n") && !string4.match(/[^\r]\n/); } function hasOnlyUnixLineEndings(string4) { return !string4.includes("\r\n") && string4.includes("\n"); } function segment(string4, segmenter) { const parts = []; for (const segmentObj of Array.from(segmenter.segment(string4))) { const segment2 = segmentObj.segment; if (parts.length && /\s/.test(parts[parts.length - 1]) && /\s/.test(segment2)) { parts[parts.length - 1] += segment2; } else { parts.push(segment2); } } return parts; } function trailingWs(string4, segmenter) { if (segmenter) { return leadingAndTrailingWs(string4, segmenter)[1]; } let i; for (i = string4.length - 1; i >= 0; i--) { if (!string4[i].match(/\s/)) { break; } } return string4.substring(i + 1); } function leadingWs(string4, segmenter) { if (segmenter) { return leadingAndTrailingWs(string4, segmenter)[0]; } const match = string4.match(/^\s*/); return match ? match[0] : ""; } function leadingAndTrailingWs(string4, segmenter) { if (!segmenter) { return [leadingWs(string4), trailingWs(string4)]; } if (segmenter.resolvedOptions().granularity != "word") { throw new Error('The segmenter passed must have a granularity of "word"'); } const segments = segment(string4, segmenter); const firstSeg = segments[0]; const lastSeg = segments[segments.length - 1]; const head = /\s/.test(firstSeg) ? firstSeg : ""; const tail = /\s/.test(lastSeg) ? lastSeg : ""; return [head, tail]; } // node_modules/diff/libesm/diff/word.js var extendedWordChars = "a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}"; var tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, "ug"); var WordDiff = class extends Diff { equals(left, right, options) { if (options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left.trim() === right.trim(); } tokenize(value, options = {}) { let parts; if (options.intlSegmenter) { const segmenter = options.intlSegmenter; if (segmenter.resolvedOptions().granularity != "word") { throw new Error('The segmenter passed must have a granularity of "word"'); } parts = segment(value, segmenter); } else { parts = value.match(tokenizeIncludingWhitespace) || []; } const tokens = []; let prevPart = null; parts.forEach((part) => { if (/\s/.test(part)) { if (prevPart == null) { tokens.push(part); } else { tokens.push(tokens.pop() + part); } } else if (prevPart != null && /\s/.test(prevPart)) { if (tokens[tokens.length - 1] == prevPart) { tokens.push(tokens.pop() + part); } else { tokens.push(prevPart + part); } } else { tokens.push(part); } prevPart = part; }); return tokens; } join(tokens) { return tokens.map((token, i) => { if (i == 0) { return token; } else { return token.replace(/^\s+/, ""); } }).join(""); } postProcess(changes, options) { if (!changes || options.oneChangePerToken) { return changes; } let lastKeep = null; let insertion = null; let deletion = null; changes.forEach((change) => { if (change.added) { insertion = change; } else if (change.removed) { deletion = change; } else { if (insertion || deletion) { dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change, options.intlSegmenter); } lastKeep = change; insertion = null; deletion = null; } }); if (insertion || deletion) { dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter); } return changes; } }; var wordDiff = new WordDiff(); function diffWords(oldStr, newStr, options) { if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) { return diffWordsWithSpace(oldStr, newStr, options); } return wordDiff.diff(oldStr, newStr, options); } function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep, segmenter) { if (deletion && insertion) { const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter); const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter); if (startKeep) { const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix); startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix); deletion.value = removePrefix(deletion.value, commonWsPrefix); insertion.value = removePrefix(insertion.value, commonWsPrefix); } if (endKeep) { const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix); endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix); deletion.value = removeSuffix(deletion.value, commonWsSuffix); insertion.value = removeSuffix(insertion.value, commonWsSuffix); } } else if (insertion) { if (startKeep) { const ws2 = leadingWs(insertion.value, segmenter); insertion.value = insertion.value.substring(ws2.length); } if (endKeep) { const ws2 = leadingWs(endKeep.value, segmenter); endKeep.value = endKeep.value.substring(ws2.length); } } else if (startKeep && endKeep) { const newWsFull = leadingWs(endKeep.value, segmenter), [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion.value, segmenter); const newWsStart = longestCommonPrefix(newWsFull, delWsStart); deletion.value = removePrefix(deletion.value, newWsStart); const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd); deletion.value = removeSuffix(deletion.value, newWsEnd); endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd); startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length)); } else if (endKeep) { const endKeepWsPrefix = leadingWs(endKeep.value, segmenter); const deletionWsSuffix = trailingWs(deletion.value, segmenter); const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix); deletion.value = removeSuffix(deletion.value, overlap); } else if (startKeep) { const startKeepWsSuffix = trailingWs(startKeep.value, segmenter); const deletionWsPrefix = leadingWs(deletion.value, segmenter); const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); deletion.value = removePrefix(deletion.value, overlap); } } var WordsWithSpaceDiff = class extends Diff { tokenize(value) { const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, "ug"); return value.match(regex) || []; } }; var wordsWithSpaceDiff = new WordsWithSpaceDiff(); function diffWordsWithSpace(oldStr, newStr, options) { return wordsWithSpaceDiff.diff(oldStr, newStr, options); } // node_modules/diff/libesm/util/params.js function generateOptions(options, defaults) { if (typeof options === "function") { defaults.callback = options; } else if (options) { for (const name in options) { if (Object.prototype.hasOwnProperty.call(options, name)) { defaults[name] = options[name]; } } } return defaults; } // node_modules/diff/libesm/diff/line.js var LineDiff = class extends Diff { constructor() { super(...arguments); this.tokenize = tokenize; } equals(left, right, options) { if (options.ignoreWhitespace) { if (!options.newlineIsToken || !left.includes("\n")) { left = left.trim(); } if (!options.newlineIsToken || !right.includes("\n")) { right = right.trim(); } } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { if (left.endsWith("\n")) { left = left.slice(0, -1); } if (right.endsWith("\n")) { right = right.slice(0, -1); } } return super.equals(left, right, options); } }; var lineDiff = new LineDiff(); function diffLines(oldStr, newStr, options) { return lineDiff.diff(oldStr, newStr, options); } function diffTrimmedLines(oldStr, newStr, options) { options = generateOptions(options, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } function tokenize(value, options) { if (options.stripTrailingCr) { value = value.replace(/\r\n/g, "\n"); } const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } for (let i = 0; i < linesAndNewlines.length; i++) { const line = linesAndNewlines[i]; if (i % 2 && !options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { retLines.push(line); } } return retLines; } // node_modules/diff/libesm/diff/sentence.js function isSentenceEndPunct(char) { return char == "." || char == "!" || char == "?"; } var SentenceDiff = class extends Diff { tokenize(value) { var _a2; const result = []; let tokenStartI = 0; for (let i = 0; i < value.length; i++) { if (i == value.length - 1) { result.push(value.slice(tokenStartI)); break; } if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\s/)) { result.push(value.slice(tokenStartI, i + 1)); i = tokenStartI = i + 1; while ((_a2 = value[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.match(/\s/)) { i++; } result.push(value.slice(tokenStartI, i + 1)); tokenStartI = i + 1; } } return result; } }; var sentenceDiff = new SentenceDiff(); function diffSentences(oldStr, newStr, options) { return sentenceDiff.diff(oldStr, newStr, options); } // node_modules/diff/libesm/diff/css.js var CssDiff = class extends Diff { tokenize(value) { return value.split(/([{}:;,]|\s+)/); } }; var cssDiff = new CssDiff(); function diffCss(oldStr, newStr, options) { return cssDiff.diff(oldStr, newStr, options); } // node_modules/diff/libesm/diff/json.js var JsonDiff = class extends Diff { constructor() { super(...arguments); this.tokenize = tokenize; } get useLongestToken() { return true; } castInput(value, options) { const { undefinedReplacement, stringifyReplacer = (k, v) => typeof v === "undefined" ? undefinedReplacement : v } = options; return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, " "); } equals(left, right, options) { return super.equals(left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"), options); } }; var jsonDiff = new JsonDiff(); function diffJson(oldStr, newStr, options) { return jsonDiff.diff(oldStr, newStr, options); } function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key === void 0 ? "" : key, obj); } let i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } let canonicalizedObj; if ("[object Array]" === Object.prototype.toString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, String(i)); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (typeof obj === "object" && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); const sortedKeys = []; let key2; for (key2 in obj) { if (Object.prototype.hasOwnProperty.call(obj, key2)) { sortedKeys.push(key2); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { key2 = sortedKeys[i]; canonicalizedObj[key2] = canonicalize(obj[key2], stack, replacementStack, replacer, key2); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } // node_modules/diff/libesm/diff/array.js var ArrayDiff = class extends Diff { tokenize(value) { return value.slice(); } join(value) { return value; } removeEmpty(value) { return value; } }; var arrayDiff = new ArrayDiff(); function diffArrays(oldArr, newArr, options) { return arrayDiff.diff(oldArr, newArr, options); } // node_modules/diff/libesm/patch/line-endings.js function unixToWin(patch) { if (Array.isArray(patch)) { return patch.map((p) => unixToWin(p)); } return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => { var _a2; return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")) ? line : line + "\r"; }) })) }); } function winToUnix(patch) { if (Array.isArray(patch)) { return patch.map((p) => winToUnix(p)); } return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map((hunk) => Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line) => line.endsWith("\r") ? line.substring(0, line.length - 1) : line) })) }); } function isUnix(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return !patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => !line.startsWith("\\") && line.endsWith("\r")))); } function isWin(patch) { if (!Array.isArray(patch)) { patch = [patch]; } return patch.some((index) => index.hunks.some((hunk) => hunk.lines.some((line) => line.endsWith("\r")))) && patch.every((index) => index.hunks.every((hunk) => hunk.lines.every((line, i) => { var _a2; return line.startsWith("\\") || line.endsWith("\r") || ((_a2 = hunk.lines[i + 1]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\")); }))); } // node_modules/diff/libesm/patch/parse.js function parsePatch(uniDiff) { const diffstr = uniDiff.split(/\n/), list = []; let i = 0; function parseIndex() { const index = {}; list.push(index); while (i < diffstr.length) { const line = diffstr[i]; if (/^(---|\+\+\+|@@)\s/.test(line)) { break; } const headerMatch = /^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line); if (headerMatch) { index.index = line.substring(headerMatch[0].length).trim(); } i++; } parseFileHeader(index); parseFileHeader(index); index.hunks = []; while (i < diffstr.length) { const line = diffstr[i]; if (/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/.test(line)) { break; } else if (/^@@/.test(line)) { index.hunks.push(parseHunk()); } else if (line) { throw new Error("Unknown line " + (i + 1) + " " + JSON.stringify(line)); } else { i++; } } } function parseFileHeader(index) { const fileHeaderMatch = /^(---|\+\+\+)\s+/.exec(diffstr[i]); if (fileHeaderMatch) { const prefix = fileHeaderMatch[1], data = diffstr[i].substring(3).trim().split(" ", 2), header = (data[1] || "").trim(); let fileName = data[0].replace(/\\\\/g, "\\"); if (fileName.startsWith('"') && fileName.endsWith('"')) { fileName = fileName.substr(1, fileName.length - 2); } if (prefix === "---") { index.oldFileName = fileName; index.oldHeader = header; } else { index.newFileName = fileName; index.newHeader = header; } i++; } } function parseHunk() { var _a2; const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); const hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === "undefined" ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === "undefined" ? 1 : +chunkHeader[4], lines: [] }; if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } let addCount = 0, removeCount = 0; for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a2 = diffstr[i]) === null || _a2 === void 0 ? void 0 : _a2.startsWith("\\"))); i++) { const operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? " " : diffstr[i][0]; if (operation === "+" || operation === "-" || operation === " " || operation === "\\") { hunk.lines.push(diffstr[i]); if (operation === "+") { addCount++; } else if (operation === "-") { removeCount++; } else if (operation === " ") { addCount++; removeCount++; } } else { throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`); } } if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } if (addCount !== hunk.newLines) { throw new Error("Added line count did not match for hunk at line " + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error("Removed line count did not match for hunk at line " + (chunkHeaderIndex + 1)); } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // node_modules/diff/libesm/util/distance-iterator.js function distance_iterator_default(start, minLine, maxLine) { let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } if (start + localOffset <= maxLine) { return start + localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } if (minLine <= start - localOffset) { return start - localOffset++; } backwardExhausted = true; return iterator(); } return void 0; }; } // node_modules/diff/libesm/patch/apply.js function applyPatch(source, patch, options = {}) { let patches; if (typeof patch === "string") { patches = parsePatch(patch); } else if (Array.isArray(patch)) { patches = patch; } else { patches = [patch]; } if (patches.length > 1) { throw new Error("applyPatch only works with a single input."); } return applyStructuredPatch(source, patches[0], options); } function applyStructuredPatch(source, patch, options = {}) { if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) { if (hasOnlyWinLineEndings(source) && isUnix(patch)) { patch = unixToWin(patch); } else if (hasOnlyUnixLineEndings(source) && isWin(patch)) { patch = winToUnix(patch); } } const lines = source.split("\n"), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0; let minLine = 0; if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) { throw new Error("fuzzFactor must be a non-negative integer"); } if (!hunks.length) { return source; } let prevLine = "", removeEOFNL = false, addEOFNL = false; for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) { const line = hunks[hunks.length - 1].lines[i]; if (line[0] == "\\") { if (prevLine[0] == "+") { removeEOFNL = true; } else if (prevLine[0] == "-") { addEOFNL = true; } } prevLine = line; } if (removeEOFNL) { if (addEOFNL) { if (!fuzzFactor && lines[lines.length - 1] == "") { return false; } } else if (lines[lines.length - 1] == "") { lines.pop(); } else if (!fuzzFactor) { return false; } } else if (addEOFNL) { if (lines[lines.length - 1] != "") { lines.push(""); } else if (!fuzzFactor) { return false; } } function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) { let nConsecutiveOldContextLines = 0; let nextContextLineMustMatch = false; for (; hunkLinesI < hunkLines.length; hunkLinesI++) { const hunkLine = hunkLines[hunkLinesI], operation = hunkLine.length > 0 ? hunkLine[0] : " ", content = hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine; if (operation === "-") { if (compareLine(toPos + 1, lines[toPos], operation, content)) { toPos++; nConsecutiveOldContextLines = 0; } else { if (!maxErrors || lines[toPos] == null) { return null; } patchedLines[patchedLinesLength] = lines[toPos]; return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1); } } if (operation === "+") { if (!lastContextLineMatched) { return null; } patchedLines[patchedLinesLength] = content; patchedLinesLength++; nConsecutiveOldContextLines = 0; nextContextLineMustMatch = true; } if (operation === " ") { nConsecutiveOldContextLines++; patchedLines[patchedLinesLength] = lines[toPos]; if (compareLine(toPos + 1, lines[toPos], operation, content)) { patchedLinesLength++; lastContextLineMatched = true; nextContextLineMustMatch = false; toPos++; } else { if (nextContextLineMustMatch || !maxErrors) { return null; } return lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength); } } } patchedLinesLength -= nConsecutiveOldContextLines; toPos -= nConsecutiveOldContextLines; patchedLines.length = patchedLinesLength; return { patchedLines, oldLineLastI: toPos - 1 }; } const resultLines = []; let prevHunkOffset = 0; for (let i = 0; i < hunks.length; i++) { const hunk = hunks[i]; let hunkResult; const maxLine = lines.length - hunk.oldLines + fuzzFactor; let toPos; for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) { toPos = hunk.oldStart + prevHunkOffset - 1; const iterator = distance_iterator_default(toPos, minLine, maxLine); for (; toPos !== void 0; toPos = iterator()) { hunkResult = applyHunk(hunk.lines, toPos, maxErrors); if (hunkResult) { break; } } if (hunkResult) { break; } } if (!hunkResult) { return false; } for (let i2 = minLine; i2 < toPos; i2++) { resultLines.push(lines[i2]); } for (let i2 = 0; i2 < hunkResult.patchedLines.length; i2++) { const line = hunkResult.patchedLines[i2]; resultLines.push(line); } minLine = hunkResult.oldLineLastI + 1; prevHunkOffset = toPos + 1 - hunk.oldStart; } for (let i = minLine; i < lines.length; i++) { resultLines.push(lines[i]); } return resultLines.join("\n"); } function applyPatches(uniDiff, options) { const spDiff = typeof uniDiff === "string" ? parsePatch(uniDiff) : uniDiff; let currentIndex = 0; function processIndex() { const index = spDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function(err, data) { if (err) { return options.complete(err); } const updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function(err2) { if (err2) { return options.complete(err2); } processIndex(); }); }); } processIndex(); } // node_modules/diff/libesm/patch/reverse.js function reversePatch(structuredPatch2) { if (Array.isArray(structuredPatch2)) { return structuredPatch2.map((patch) => reversePatch(patch)).reverse(); } return Object.assign(Object.assign({}, structuredPatch2), { oldFileName: structuredPatch2.newFileName, oldHeader: structuredPatch2.newHeader, newFileName: structuredPatch2.oldFileName, newHeader: structuredPatch2.oldHeader, hunks: structuredPatch2.hunks.map((hunk) => { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, lines: hunk.lines.map((l) => { if (l.startsWith("-")) { return `+${l.slice(1)}`; } if (l.startsWith("+")) { return `-${l.slice(1)}`; } return l; }) }; }) }); } // node_modules/diff/libesm/patch/create.js var INCLUDE_HEADERS = { includeIndex: true, includeUnderline: true, includeFileHeaders: true }; var FILE_HEADERS_ONLY = { includeIndex: false, includeUnderline: false, includeFileHeaders: true }; var OMIT_HEADERS = { includeIndex: false, includeUnderline: false, includeFileHeaders: false }; function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { let optionsObj; if (!options) { optionsObj = {}; } else if (typeof options === "function") { optionsObj = { callback: options }; } else { optionsObj = options; } if (typeof optionsObj.context === "undefined") { optionsObj.context = 4; } const context = optionsObj.context; if (optionsObj.newlineIsToken) { throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions"); } if (!optionsObj.callback) { return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); } else { const { callback } = optionsObj; diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff2) => { const patch = diffLinesResultToPatch(diff2); callback(patch); } })); } function diffLinesResultToPatch(diff2) { if (!diff2) { return; } diff2.push({ value: "", lines: [] }); function contextLines(lines) { return lines.map(function(entry) { return " " + entry; }); } const hunks = []; let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (let i = 0; i < diff2.length; i++) { const current = diff2[i], lines = current.lines || splitLines(current.value); current.lines = lines; if (current.added || current.removed) { if (!oldRangeStart) { const prev = diff2[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } for (const line of lines) { curRange.push((current.added ? "+" : "-") + line); } if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { if (oldRangeStart) { if (lines.length <= context * 2 && i < diff2.length - 2) { for (const line of contextLines(lines)) { curRange.push(line); } } else { const contextSize = Math.min(lines.length, context); for (const line of contextLines(lines.slice(0, contextSize))) { curRange.push(line); } const hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } } for (const hunk of hunks) { for (let i = 0; i < hunk.lines.length; i++) { if (hunk.lines[i].endsWith("\n")) { hunk.lines[i] = hunk.lines[i].slice(0, -1); } else { hunk.lines.splice(i + 1, 0, "\\ No newline at end of file"); i++; } } } return { oldFileName, newFileName, oldHeader, newHeader, hunks }; } } function formatPatch(patch, headerOptions) { if (!headerOptions) { headerOptions = INCLUDE_HEADERS; } if (Array.isArray(patch)) { if (patch.length > 1 && !headerOptions.includeFileHeaders) { throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)"); } return patch.map((p) => formatPatch(p, headerOptions)).join("\n"); } const ret = []; if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { ret.push("Index: " + patch.oldFileName); } if (headerOptions.includeUnderline) { ret.push("==================================================================="); } if (headerOptions.includeFileHeaders) { ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader)); ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader)); } for (let i = 0; i < patch.hunks.length; i++) { const hunk = patch.hunks[i]; if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@"); for (const line of hunk.lines) { ret.push(line); } } return ret.join("\n") + "\n"; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (typeof options === "function") { options = { callback: options }; } if (!(options === null || options === void 0 ? void 0 : options.callback)) { const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); if (!patchObj) { return; } return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); } else { const { callback } = options; structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => { if (!patchObj) { callback(void 0); } else { callback(formatPatch(patchObj, options.headerOptions)); } } })); } } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } function splitLines(text) { const hasTrailingNl = text.endsWith("\n"); const result = text.split("\n").map((line) => line + "\n"); if (hasTrailingNl) { result.pop(); } else { result.push(result.pop().slice(0, -1)); } return result; } // node_modules/diff/libesm/convert/dmp.js function convertChangesToDMP(changes) { const ret = []; let change, operation; for (let i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } // node_modules/diff/libesm/convert/xml.js function convertChangesToXML(changes) { const ret = []; for (let i = 0; i < changes.length; i++) { const change = changes[i]; if (change.added) { ret.push(""); } else if (change.removed) { ret.push(""); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(""); } else if (change.removed) { ret.push(""); } } return ret.join(""); } function escapeHTML(s) { let n = s; n = n.replace(/&/g, "&"); n = n.replace(//g, ">"); n = n.replace(/"/g, """); return n; } // packages/playwright-core/src/utilsBundle.ts var import_dotenv = __toESM(require_main()); // node_modules/proxy-from-env/index.js var DEFAULT_PORTS = { ftp: 21, gopher: 70, http: 80, https: 443, ws: 80, wss: 443 }; function parseUrl(urlString) { try { return new URL(urlString); } catch { return null; } } function getProxyForUrl(url2) { var parsedUrl = (typeof url2 === "string" ? parseUrl(url2) : url2) || {}; var proto = parsedUrl.protocol; var hostname3 = parsedUrl.host; var port = parsedUrl.port; if (typeof hostname3 !== "string" || !hostname3 || typeof proto !== "string") { return ""; } proto = proto.split(":", 1)[0]; hostname3 = hostname3.replace(/:\d*$/, ""); port = parseInt(port) || DEFAULT_PORTS[proto] || 0; if (!shouldProxy(hostname3, port)) { return ""; } var proxy = getEnv(proto + "_proxy") || getEnv("all_proxy"); if (proxy && proxy.indexOf("://") === -1) { proxy = proto + "://" + proxy; } return proxy; } function shouldProxy(hostname3, port) { var NO_PROXY = getEnv("no_proxy").toLowerCase(); if (!NO_PROXY) { return true; } if (NO_PROXY === "*") { return false; } return NO_PROXY.split(/[,\s]/).every(function(proxy) { if (!proxy) { return true; } var parsedProxy = proxy.match(/^(.+):(\d+)$/); var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; if (parsedProxyPort && parsedProxyPort !== port) { return true; } if (!/^[.*]/.test(parsedProxyHostname)) { return hostname3 !== parsedProxyHostname; } if (parsedProxyHostname.charAt(0) === "*") { parsedProxyHostname = parsedProxyHostname.slice(1); } return !hostname3.endsWith(parsedProxyHostname); }); } function getEnv(key) { return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ""; } // packages/playwright-core/src/utilsBundle.ts var import_https_proxy_agent = __toESM(require_dist2()); var import_jpeg_js = __toESM(require_jpeg_js()); var import_mime = __toESM(require_mime()); var import_minimatch = __toESM(require_minimatch()); var import_open = __toESM(require_open()); var import_pngjs = __toESM(require_png()); // node_modules/commander/esm.mjs var import_index = __toESM(require_commander(), 1); var { program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, // deprecated old name Command, Argument, Option, Help } = import_index.default; // packages/playwright-core/src/utilsBundle.ts var import_progress = __toESM(require_progress()); var import_socks_proxy_agent = __toESM(require_dist3()); // node_modules/ws/wrapper.mjs var import_stream = __toESM(require_stream(), 1); var import_receiver = __toESM(require_receiver(), 1); var import_sender = __toESM(require_sender(), 1); var import_websocket = __toESM(require_websocket(), 1); var import_websocket_server = __toESM(require_websocket_server(), 1); var wrapper_default = import_websocket.default; // packages/playwright-core/src/utilsBundle.ts var import_yaml = __toESM(require_dist4()); var import_json5 = __toESM(require_lib()); var import_source_map_support = __toESM(require_source_map_support()); var import_enquirer = __toESM(require_enquirer()); var import_chokidar = __toESM(require_chokidar()); // node_modules/get-east-asian-width/index.js var get_east_asian_width_exports = {}; __export(get_east_asian_width_exports, { _isNarrowWidth: () => _isNarrowWidth, eastAsianWidth: () => eastAsianWidth, eastAsianWidthType: () => eastAsianWidthType }); // node_modules/get-east-asian-width/lookup.js function isAmbiguous(x) { return x === 161 || x === 164 || x === 167 || x === 168 || x === 170 || x === 173 || x === 174 || x >= 176 && x <= 180 || x >= 182 && x <= 186 || x >= 188 && x <= 191 || x === 198 || x === 208 || x === 215 || x === 216 || x >= 222 && x <= 225 || x === 230 || x >= 232 && x <= 234 || x === 236 || x === 237 || x === 240 || x === 242 || x === 243 || x >= 247 && x <= 250 || x === 252 || x === 254 || x === 257 || x === 273 || x === 275 || x === 283 || x === 294 || x === 295 || x === 299 || x >= 305 && x <= 307 || x === 312 || x >= 319 && x <= 322 || x === 324 || x >= 328 && x <= 331 || x === 333 || x === 338 || x === 339 || x === 358 || x === 359 || x === 363 || x === 462 || x === 464 || x === 466 || x === 468 || x === 470 || x === 472 || x === 474 || x === 476 || x === 593 || x === 609 || x === 708 || x === 711 || x >= 713 && x <= 715 || x === 717 || x === 720 || x >= 728 && x <= 731 || x === 733 || x === 735 || x >= 768 && x <= 879 || x >= 913 && x <= 929 || x >= 931 && x <= 937 || x >= 945 && x <= 961 || x >= 963 && x <= 969 || x === 1025 || x >= 1040 && x <= 1103 || x === 1105 || x === 8208 || x >= 8211 && x <= 8214 || x === 8216 || x === 8217 || x === 8220 || x === 8221 || x >= 8224 && x <= 8226 || x >= 8228 && x <= 8231 || x === 8240 || x === 8242 || x === 8243 || x === 8245 || x === 8251 || x === 8254 || x === 8308 || x === 8319 || x >= 8321 && x <= 8324 || x === 8364 || x === 8451 || x === 8453 || x === 8457 || x === 8467 || x === 8470 || x === 8481 || x === 8482 || x === 8486 || x === 8491 || x === 8531 || x === 8532 || x >= 8539 && x <= 8542 || x >= 8544 && x <= 8555 || x >= 8560 && x <= 8569 || x === 8585 || x >= 8592 && x <= 8601 || x === 8632 || x === 8633 || x === 8658 || x === 8660 || x === 8679 || x === 8704 || x === 8706 || x === 8707 || x === 8711 || x === 8712 || x === 8715 || x === 8719 || x === 8721 || x === 8725 || x === 8730 || x >= 8733 && x <= 8736 || x === 8739 || x === 8741 || x >= 8743 && x <= 8748 || x === 8750 || x >= 8756 && x <= 8759 || x === 8764 || x === 8765 || x === 8776 || x === 8780 || x === 8786 || x === 8800 || x === 8801 || x >= 8804 && x <= 8807 || x === 8810 || x === 8811 || x === 8814 || x === 8815 || x === 8834 || x === 8835 || x === 8838 || x === 8839 || x === 8853 || x === 8857 || x === 8869 || x === 8895 || x === 8978 || x >= 9312 && x <= 9449 || x >= 9451 && x <= 9547 || x >= 9552 && x <= 9587 || x >= 9600 && x <= 9615 || x >= 9618 && x <= 9621 || x === 9632 || x === 9633 || x >= 9635 && x <= 9641 || x === 9650 || x === 9651 || x === 9654 || x === 9655 || x === 9660 || x === 9661 || x === 9664 || x === 9665 || x >= 9670 && x <= 9672 || x === 9675 || x >= 9678 && x <= 9681 || x >= 9698 && x <= 9701 || x === 9711 || x === 9733 || x === 9734 || x === 9737 || x === 9742 || x === 9743 || x === 9756 || x === 9758 || x === 9792 || x === 9794 || x === 9824 || x === 9825 || x >= 9827 && x <= 9829 || x >= 9831 && x <= 9834 || x === 9836 || x === 9837 || x === 9839 || x === 9886 || x === 9887 || x === 9919 || x >= 9926 && x <= 9933 || x >= 9935 && x <= 9939 || x >= 9941 && x <= 9953 || x === 9955 || x === 9960 || x === 9961 || x >= 9963 && x <= 9969 || x === 9972 || x >= 9974 && x <= 9977 || x === 9979 || x === 9980 || x === 9982 || x === 9983 || x === 10045 || x >= 10102 && x <= 10111 || x >= 11094 && x <= 11097 || x >= 12872 && x <= 12879 || x >= 57344 && x <= 63743 || x >= 65024 && x <= 65039 || x === 65533 || x >= 127232 && x <= 127242 || x >= 127248 && x <= 127277 || x >= 127280 && x <= 127337 || x >= 127344 && x <= 127373 || x === 127375 || x === 127376 || x >= 127387 && x <= 127404 || x >= 917760 && x <= 917999 || x >= 983040 && x <= 1048573 || x >= 1048576 && x <= 1114109; } function isFullWidth(x) { return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510; } function isWide(x) { return x >= 4352 && x <= 4447 || x === 8986 || x === 8987 || x === 9001 || x === 9002 || x >= 9193 && x <= 9196 || x === 9200 || x === 9203 || x === 9725 || x === 9726 || x === 9748 || x === 9749 || x >= 9776 && x <= 9783 || x >= 9800 && x <= 9811 || x === 9855 || x >= 9866 && x <= 9871 || x === 9875 || x === 9889 || x === 9898 || x === 9899 || x === 9917 || x === 9918 || x === 9924 || x === 9925 || x === 9934 || x === 9940 || x === 9962 || x === 9970 || x === 9971 || x === 9973 || x === 9978 || x === 9981 || x === 9989 || x === 9994 || x === 9995 || x === 10024 || x === 10060 || x === 10062 || x >= 10067 && x <= 10069 || x === 10071 || x >= 10133 && x <= 10135 || x === 10160 || x === 10175 || x === 11035 || x === 11036 || x === 11088 || x === 11093 || x >= 11904 && x <= 11929 || x >= 11931 && x <= 12019 || x >= 12032 && x <= 12245 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12353 && x <= 12438 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12773 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 42124 || x >= 42128 && x <= 42182 || x >= 43360 && x <= 43388 || x >= 44032 && x <= 55203 || x >= 63744 && x <= 64255 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 94176 && x <= 94180 || x === 94192 || x === 94193 || x >= 94208 && x <= 100343 || x >= 100352 && x <= 101589 || x >= 101631 && x <= 101640 || x >= 110576 && x <= 110579 || x >= 110581 && x <= 110587 || x === 110589 || x === 110590 || x >= 110592 && x <= 110882 || x === 110898 || x >= 110928 && x <= 110930 || x === 110933 || x >= 110948 && x <= 110951 || x >= 110960 && x <= 111355 || x >= 119552 && x <= 119638 || x >= 119648 && x <= 119670 || x === 126980 || x === 127183 || x === 127374 || x >= 127377 && x <= 127386 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x === 127568 || x === 127569 || x >= 127584 && x <= 127589 || x >= 127744 && x <= 127776 || x >= 127789 && x <= 127797 || x >= 127799 && x <= 127868 || x >= 127870 && x <= 127891 || x >= 127904 && x <= 127946 || x >= 127951 && x <= 127955 || x >= 127968 && x <= 127984 || x === 127988 || x >= 127992 && x <= 128062 || x === 128064 || x >= 128066 && x <= 128252 || x >= 128255 && x <= 128317 || x >= 128331 && x <= 128334 || x >= 128336 && x <= 128359 || x === 128378 || x === 128405 || x === 128406 || x === 128420 || x >= 128507 && x <= 128591 || x >= 128640 && x <= 128709 || x === 128716 || x >= 128720 && x <= 128722 || x >= 128725 && x <= 128727 || x >= 128732 && x <= 128735 || x === 128747 || x === 128748 || x >= 128756 && x <= 128764 || x >= 128992 && x <= 129003 || x === 129008 || x >= 129292 && x <= 129338 || x >= 129340 && x <= 129349 || x >= 129351 && x <= 129535 || x >= 129648 && x <= 129660 || x >= 129664 && x <= 129673 || x >= 129679 && x <= 129734 || x >= 129742 && x <= 129756 || x >= 129759 && x <= 129769 || x >= 129776 && x <= 129784 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141; } function getCategory(x) { if (isAmbiguous(x)) return "ambiguous"; if (isFullWidth(x)) return "fullwidth"; if (x === 8361 || x >= 65377 && x <= 65470 || x >= 65474 && x <= 65479 || x >= 65482 && x <= 65487 || x >= 65490 && x <= 65495 || x >= 65498 && x <= 65500 || x >= 65512 && x <= 65518) { return "halfwidth"; } if (x >= 32 && x <= 126 || x === 162 || x === 163 || x === 165 || x === 166 || x === 172 || x === 175 || x >= 10214 && x <= 10221 || x === 10629 || x === 10630) { return "narrow"; } if (isWide(x)) return "wide"; return "neutral"; } // node_modules/get-east-asian-width/index.js function validate(codePoint) { if (!Number.isSafeInteger(codePoint)) { throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`); } } function eastAsianWidthType(codePoint) { validate(codePoint); return getCategory(codePoint); } function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) { validate(codePoint); if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) { return 2; } return 1; } var _isNarrowWidth = (codePoint) => !(isFullWidth(codePoint) || isWide(codePoint)); // packages/playwright-core/src/utilsBundle.ts var yazl = __toESM(require_yazl()); var gracefulFsLibrary = __toESM(require_graceful_fs()); var import_retry = __toESM(require_retry2()); var import_signal_exit = __toESM(require_signal_exit()); var import_get_stream = __toESM(require_get_stream()); var import_https_proxy_agent2 = __toESM(require_dist2()); var import_socks_proxy_agent2 = __toESM(require_dist3()); // node_modules/zod/index.js var zod_exports = {}; __export(zod_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodExactOptional: () => ZodExactOptional, ZodFile: () => ZodFile, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMAC: () => ZodMAC, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRealError: () => ZodRealError, ZodRecord: () => ZodRecord, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, ZodXID: () => ZodXID, ZodXor: () => ZodXor, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, clone: () => clone, codec: () => codec, coerce: () => coerce_exports, config: () => config, core: () => core_exports2, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom, date: () => date3, decode: () => decode2, decodeAsync: () => decodeAsync2, default: () => zod_default, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, encode: () => encode2, encodeAsync: () => encodeAsync2, endsWith: () => _endsWith, enum: () => _enum2, exactOptional: () => exactOptional, file: () => file, flattenError: () => flattenError, float32: () => float32, float64: () => float64, formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, gte: () => _gte, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, includes: () => _includes, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, ipv4: () => ipv42, ipv6: () => ipv62, iso: () => iso_exports, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, length: () => _length, literal: () => literal, locales: () => locales_exports, looseObject: () => looseObject, looseRecord: () => looseRecord, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, mac: () => mac2, map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, negative: () => _negative, never: () => never, nonnegative: () => _nonnegative, nonoptional: () => nonoptional, nonpositive: () => _nonpositive, normalize: () => _normalize, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object, optional: () => optional, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, partialRecord: () => partialRecord, pipe: () => pipe, positive: () => _positive, prefault: () => prefault, preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, property: () => _property, readonly: () => readonly, record: () => record, refine: () => refine, regex: () => _regex, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode2, safeDecodeAsync: () => safeDecodeAsync2, safeEncode: () => safeEncode2, safeEncodeAsync: () => safeEncodeAsync2, safeParse: () => safeParse2, safeParseAsync: () => safeParseAsync2, set: () => set, setErrorMap: () => setErrorMap, size: () => _size, slugify: () => _slugify, startsWith: () => _startsWith, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol, templateLiteral: () => templateLiteral, toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, uppercase: () => _uppercase, url: () => url, util: () => util_exports, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2, xor: () => xor, z: () => external_exports }); // node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { $brand: () => $brand, $input: () => $input, $output: () => $output, NEVER: () => NEVER, TimePrecision: () => TimePrecision, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodExactOptional: () => ZodExactOptional, ZodFile: () => ZodFile, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMAC: () => ZodMAC, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRealError: () => ZodRealError, ZodRecord: () => ZodRecord, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, ZodXID: () => ZodXID, ZodXor: () => ZodXor, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, clone: () => clone, codec: () => codec, coerce: () => coerce_exports, config: () => config, core: () => core_exports2, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom, date: () => date3, decode: () => decode2, decodeAsync: () => decodeAsync2, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, encode: () => encode2, encodeAsync: () => encodeAsync2, endsWith: () => _endsWith, enum: () => _enum2, exactOptional: () => exactOptional, file: () => file, flattenError: () => flattenError, float32: () => float32, float64: () => float64, formatError: () => formatError, fromJSONSchema: () => fromJSONSchema, function: () => _function, getErrorMap: () => getErrorMap, globalRegistry: () => globalRegistry, gt: () => _gt, gte: () => _gte, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, includes: () => _includes, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, ipv4: () => ipv42, ipv6: () => ipv62, iso: () => iso_exports, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, length: () => _length, literal: () => literal, locales: () => locales_exports, looseObject: () => looseObject, looseRecord: () => looseRecord, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, mac: () => mac2, map: () => map, maxLength: () => _maxLength, maxSize: () => _maxSize, meta: () => meta2, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, negative: () => _negative, never: () => never, nonnegative: () => _nonnegative, nonoptional: () => nonoptional, nonpositive: () => _nonpositive, normalize: () => _normalize, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object, optional: () => optional, overwrite: () => _overwrite, parse: () => parse2, parseAsync: () => parseAsync2, partialRecord: () => partialRecord, pipe: () => pipe, positive: () => _positive, prefault: () => prefault, preprocess: () => preprocess, prettifyError: () => prettifyError, promise: () => promise, property: () => _property, readonly: () => readonly, record: () => record, refine: () => refine, regex: () => _regex, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode2, safeDecodeAsync: () => safeDecodeAsync2, safeEncode: () => safeEncode2, safeEncodeAsync: () => safeEncodeAsync2, safeParse: () => safeParse2, safeParseAsync: () => safeParseAsync2, set: () => set, setErrorMap: () => setErrorMap, size: () => _size, slugify: () => _slugify, startsWith: () => _startsWith, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol, templateLiteral: () => templateLiteral, toJSONSchema: () => toJSONSchema, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, transform: () => transform, treeifyError: () => treeifyError, trim: () => _trim, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, uppercase: () => _uppercase, url: () => url, util: () => util_exports, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2, xor: () => xor }); // node_modules/zod/v4/core/index.js var core_exports2 = {}; __export(core_exports2, { $ZodAny: () => $ZodAny, $ZodArray: () => $ZodArray, $ZodAsyncError: () => $ZodAsyncError, $ZodBase64: () => $ZodBase64, $ZodBase64URL: () => $ZodBase64URL, $ZodBigInt: () => $ZodBigInt, $ZodBigIntFormat: () => $ZodBigIntFormat, $ZodBoolean: () => $ZodBoolean, $ZodCIDRv4: () => $ZodCIDRv4, $ZodCIDRv6: () => $ZodCIDRv6, $ZodCUID: () => $ZodCUID, $ZodCUID2: () => $ZodCUID2, $ZodCatch: () => $ZodCatch, $ZodCheck: () => $ZodCheck, $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, $ZodCheckEndsWith: () => $ZodCheckEndsWith, $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, $ZodCheckIncludes: () => $ZodCheckIncludes, $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, $ZodCheckLessThan: () => $ZodCheckLessThan, $ZodCheckLowerCase: () => $ZodCheckLowerCase, $ZodCheckMaxLength: () => $ZodCheckMaxLength, $ZodCheckMaxSize: () => $ZodCheckMaxSize, $ZodCheckMimeType: () => $ZodCheckMimeType, $ZodCheckMinLength: () => $ZodCheckMinLength, $ZodCheckMinSize: () => $ZodCheckMinSize, $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, $ZodCheckOverwrite: () => $ZodCheckOverwrite, $ZodCheckProperty: () => $ZodCheckProperty, $ZodCheckRegex: () => $ZodCheckRegex, $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, $ZodCheckStartsWith: () => $ZodCheckStartsWith, $ZodCheckStringFormat: () => $ZodCheckStringFormat, $ZodCheckUpperCase: () => $ZodCheckUpperCase, $ZodCodec: () => $ZodCodec, $ZodCustom: () => $ZodCustom, $ZodCustomStringFormat: () => $ZodCustomStringFormat, $ZodDate: () => $ZodDate, $ZodDefault: () => $ZodDefault, $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, $ZodE164: () => $ZodE164, $ZodEmail: () => $ZodEmail, $ZodEmoji: () => $ZodEmoji, $ZodEncodeError: () => $ZodEncodeError, $ZodEnum: () => $ZodEnum, $ZodError: () => $ZodError, $ZodExactOptional: () => $ZodExactOptional, $ZodFile: () => $ZodFile, $ZodFunction: () => $ZodFunction, $ZodGUID: () => $ZodGUID, $ZodIPv4: () => $ZodIPv4, $ZodIPv6: () => $ZodIPv6, $ZodISODate: () => $ZodISODate, $ZodISODateTime: () => $ZodISODateTime, $ZodISODuration: () => $ZodISODuration, $ZodISOTime: () => $ZodISOTime, $ZodIntersection: () => $ZodIntersection, $ZodJWT: () => $ZodJWT, $ZodKSUID: () => $ZodKSUID, $ZodLazy: () => $ZodLazy, $ZodLiteral: () => $ZodLiteral, $ZodMAC: () => $ZodMAC, $ZodMap: () => $ZodMap, $ZodNaN: () => $ZodNaN, $ZodNanoID: () => $ZodNanoID, $ZodNever: () => $ZodNever, $ZodNonOptional: () => $ZodNonOptional, $ZodNull: () => $ZodNull, $ZodNullable: () => $ZodNullable, $ZodNumber: () => $ZodNumber, $ZodNumberFormat: () => $ZodNumberFormat, $ZodObject: () => $ZodObject, $ZodObjectJIT: () => $ZodObjectJIT, $ZodOptional: () => $ZodOptional, $ZodPipe: () => $ZodPipe, $ZodPrefault: () => $ZodPrefault, $ZodPromise: () => $ZodPromise, $ZodReadonly: () => $ZodReadonly, $ZodRealError: () => $ZodRealError, $ZodRecord: () => $ZodRecord, $ZodRegistry: () => $ZodRegistry, $ZodSet: () => $ZodSet, $ZodString: () => $ZodString, $ZodStringFormat: () => $ZodStringFormat, $ZodSuccess: () => $ZodSuccess, $ZodSymbol: () => $ZodSymbol, $ZodTemplateLiteral: () => $ZodTemplateLiteral, $ZodTransform: () => $ZodTransform, $ZodTuple: () => $ZodTuple, $ZodType: () => $ZodType, $ZodULID: () => $ZodULID, $ZodURL: () => $ZodURL, $ZodUUID: () => $ZodUUID, $ZodUndefined: () => $ZodUndefined, $ZodUnion: () => $ZodUnion, $ZodUnknown: () => $ZodUnknown, $ZodVoid: () => $ZodVoid, $ZodXID: () => $ZodXID, $ZodXor: () => $ZodXor, $brand: () => $brand, $constructor: () => $constructor, $input: () => $input, $output: () => $output, Doc: () => Doc, JSONSchema: () => json_schema_exports, JSONSchemaGenerator: () => JSONSchemaGenerator, NEVER: () => NEVER, TimePrecision: () => TimePrecision, _any: () => _any, _array: () => _array, _base64: () => _base64, _base64url: () => _base64url, _bigint: () => _bigint, _boolean: () => _boolean, _catch: () => _catch, _check: () => _check, _cidrv4: () => _cidrv4, _cidrv6: () => _cidrv6, _coercedBigint: () => _coercedBigint, _coercedBoolean: () => _coercedBoolean, _coercedDate: () => _coercedDate, _coercedNumber: () => _coercedNumber, _coercedString: () => _coercedString, _cuid: () => _cuid, _cuid2: () => _cuid2, _custom: () => _custom, _date: () => _date, _decode: () => _decode, _decodeAsync: () => _decodeAsync, _default: () => _default, _discriminatedUnion: () => _discriminatedUnion, _e164: () => _e164, _email: () => _email, _emoji: () => _emoji2, _encode: () => _encode, _encodeAsync: () => _encodeAsync, _endsWith: () => _endsWith, _enum: () => _enum, _file: () => _file, _float32: () => _float32, _float64: () => _float64, _gt: () => _gt, _gte: () => _gte, _guid: () => _guid, _includes: () => _includes, _int: () => _int, _int32: () => _int32, _int64: () => _int64, _intersection: () => _intersection, _ipv4: () => _ipv4, _ipv6: () => _ipv6, _isoDate: () => _isoDate, _isoDateTime: () => _isoDateTime, _isoDuration: () => _isoDuration, _isoTime: () => _isoTime, _jwt: () => _jwt, _ksuid: () => _ksuid, _lazy: () => _lazy, _length: () => _length, _literal: () => _literal, _lowercase: () => _lowercase, _lt: () => _lt, _lte: () => _lte, _mac: () => _mac, _map: () => _map, _max: () => _lte, _maxLength: () => _maxLength, _maxSize: () => _maxSize, _mime: () => _mime, _min: () => _gte, _minLength: () => _minLength, _minSize: () => _minSize, _multipleOf: () => _multipleOf, _nan: () => _nan, _nanoid: () => _nanoid, _nativeEnum: () => _nativeEnum, _negative: () => _negative, _never: () => _never, _nonnegative: () => _nonnegative, _nonoptional: () => _nonoptional, _nonpositive: () => _nonpositive, _normalize: () => _normalize, _null: () => _null2, _nullable: () => _nullable, _number: () => _number, _optional: () => _optional, _overwrite: () => _overwrite, _parse: () => _parse, _parseAsync: () => _parseAsync, _pipe: () => _pipe, _positive: () => _positive, _promise: () => _promise, _property: () => _property, _readonly: () => _readonly, _record: () => _record, _refine: () => _refine, _regex: () => _regex, _safeDecode: () => _safeDecode, _safeDecodeAsync: () => _safeDecodeAsync, _safeEncode: () => _safeEncode, _safeEncodeAsync: () => _safeEncodeAsync, _safeParse: () => _safeParse, _safeParseAsync: () => _safeParseAsync, _set: () => _set, _size: () => _size, _slugify: () => _slugify, _startsWith: () => _startsWith, _string: () => _string, _stringFormat: () => _stringFormat, _stringbool: () => _stringbool, _success: () => _success, _superRefine: () => _superRefine, _symbol: () => _symbol, _templateLiteral: () => _templateLiteral, _toLowerCase: () => _toLowerCase, _toUpperCase: () => _toUpperCase, _transform: () => _transform, _trim: () => _trim, _tuple: () => _tuple, _uint32: () => _uint32, _uint64: () => _uint64, _ulid: () => _ulid, _undefined: () => _undefined2, _union: () => _union, _unknown: () => _unknown, _uppercase: () => _uppercase, _url: () => _url, _uuid: () => _uuid, _uuidv4: () => _uuidv4, _uuidv6: () => _uuidv6, _uuidv7: () => _uuidv7, _void: () => _void, _xid: () => _xid, _xor: () => _xor, clone: () => clone, config: () => config, createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, createToJSONSchemaMethod: () => createToJSONSchemaMethod, decode: () => decode, decodeAsync: () => decodeAsync, describe: () => describe, encode: () => encode, encodeAsync: () => encodeAsync, extractDefs: () => extractDefs, finalize: () => finalize, flattenError: () => flattenError, formatError: () => formatError, globalConfig: () => globalConfig, globalRegistry: () => globalRegistry, initializeContext: () => initializeContext, isValidBase64: () => isValidBase64, isValidBase64URL: () => isValidBase64URL, isValidJWT: () => isValidJWT, locales: () => locales_exports, meta: () => meta, parse: () => parse, parseAsync: () => parseAsync, prettifyError: () => prettifyError, process: () => process2, regexes: () => regexes_exports, registry: () => registry, safeDecode: () => safeDecode, safeDecodeAsync: () => safeDecodeAsync, safeEncode: () => safeEncode, safeEncodeAsync: () => safeEncodeAsync, safeParse: () => safeParse, safeParseAsync: () => safeParseAsync, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, treeifyError: () => treeifyError, util: () => util_exports, version: () => version }); // node_modules/zod/v4/core/core.js var NEVER = Object.freeze({ status: "aborted" }); // @__NO_SIDE_EFFECTS__ function $constructor(name, initializer3, params) { function init(inst, def) { if (!inst._zod) { Object.defineProperty(inst, "_zod", { value: { def, constr: _, traits: /* @__PURE__ */ new Set() }, enumerable: false }); } if (inst._zod.traits.has(name)) { return; } inst._zod.traits.add(name); initializer3(inst, def); const proto = _.prototype; const keys = Object.keys(proto); for (let i = 0; i < keys.length; i++) { const k = keys[i]; if (!(k in inst)) { inst[k] = proto[k].bind(inst); } } } const Parent = params?.Parent ?? Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name }); function _(def) { var _a2; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a2 = inst._zod).deferred ?? (_a2.deferred = []); for (const fn of inst._zod.deferred) { fn(); } return inst; } Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { if (params?.Parent && inst instanceof params.Parent) return true; return inst?._zod?.traits?.has(name); } }); Object.defineProperty(_, "name", { value: name }); return _; } var $brand = Symbol("zod_brand"); var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; var $ZodEncodeError = class extends Error { constructor(name) { super(`Encountered unidirectional transform during encode: ${name}`); this.name = "ZodEncodeError"; } }; var globalConfig = {}; function config(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } // node_modules/zod/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, allowsEval: () => allowsEval, assert: () => assert, assertEqual: () => assertEqual, assertIs: () => assertIs, assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, base64ToUint8Array: () => base64ToUint8Array, base64urlToUint8Array: () => base64urlToUint8Array, cached: () => cached, captureStackTrace: () => captureStackTrace, cleanEnum: () => cleanEnum, cleanRegex: () => cleanRegex, clone: () => clone, cloneDef: () => cloneDef, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, esc: () => esc, escapeRegex: () => escapeRegex, extend: () => extend, finalizeIssue: () => finalizeIssue, floatSafeRemainder: () => floatSafeRemainder, getElementAtPath: () => getElementAtPath, getEnumValues: () => getEnumValues, getLengthableOrigin: () => getLengthableOrigin, getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, isObject: () => isObject, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, merge: () => merge, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, nullish: () => nullish, numKeys: () => numKeys, objectClone: () => objectClone, omit: () => omit, optionalKeys: () => optionalKeys, parsedType: () => parsedType, partial: () => partial, pick: () => pick, prefixIssues: () => prefixIssues, primitiveTypes: () => primitiveTypes, promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, required: () => required, safeExtend: () => safeExtend, shallowClone: () => shallowClone, slugify: () => slugify, stringifyPrimitive: () => stringifyPrimitive, uint8ArrayToBase64: () => uint8ArrayToBase64, uint8ArrayToBase64url: () => uint8ArrayToBase64url, uint8ArrayToHex: () => uint8ArrayToHex, unwrapMessage: () => unwrapMessage }); function assertEqual(val) { return val; } function assertNotEqual(val) { return val; } function assertIs(_arg) { } function assertNever(_x) { throw new Error("Unexpected value in exhaustive check"); } function assert(_) { } function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); return values; } function joinValues(array2, separator = "|") { return array2.map((val) => stringifyPrimitive(val)).join(separator); } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { const set2 = false; return { get value() { if (!set2) { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } throw new Error("cached value already set"); } }; } function nullish(input) { return input === null || input === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepString = step.toString(); let stepDecCount = (stepString.split(".")[1] || "").length; if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { const match = stepString.match(/\d?e-(\d?)/); if (match?.[1]) { stepDecCount = Number.parseInt(match[1]); } } const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / 10 ** decCount; } var EVALUATING = Symbol("evaluating"); function defineLazy(object3, key, getter) { let value = void 0; Object.defineProperty(object3, key, { get() { if (value === EVALUATING) { return void 0; } if (value === void 0) { value = EVALUATING; value = getter(); } return value; }, set(v) { Object.defineProperty(object3, key, { value: v // configurable: true, }); }, configurable: true }); } function objectClone(obj) { return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { const descriptors = Object.getOwnPropertyDescriptors(def); Object.assign(mergedDescriptors, descriptors); } return Object.defineProperties({}, mergedDescriptors); } function cloneDef(schema) { return mergeDefs(schema._zod.def); } function getElementAtPath(obj, path) { if (!path) return obj; return path.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key) => promisesObj[key]); return Promise.all(promises).then((results) => { const resolvedObj = {}; for (let i = 0; i < keys.length; i++) { resolvedObj[keys[i]] = results[i]; } return resolvedObj; }); } function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; for (let i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } function esc(str) { return JSON.stringify(str); } function slugify(input) { return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval = cached(() => { if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { return false; } try { const F = Function; new F(""); return true; } catch (_) { return false; } }); function isPlainObject(o) { if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; if (typeof ctor !== "function") return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function shallowClone(o) { if (isPlainObject(o)) return { ...o }; if (Array.isArray(o)) return [...o]; return o; } function numKeys(data) { let keyCount = 0; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { keyCount++; } } return keyCount; } var getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return "undefined"; case "string": return "string"; case "number": return Number.isNaN(data) ? "nan" : "number"; case "boolean": return "boolean"; case "function": return "function"; case "bigint": return "bigint"; case "symbol": return "symbol"; case "object": if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return "promise"; } if (typeof Map !== "undefined" && data instanceof Map) { return "map"; } if (typeof Set !== "undefined" && data instanceof Set) { return "set"; } if (typeof Date !== "undefined" && data instanceof Date) { return "date"; } if (typeof File !== "undefined" && data instanceof File) { return "file"; } return "object"; default: throw new Error(`Unknown data type: ${t}`); } }; var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function clone(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== void 0) { if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function createTransparentProxy(getter) { let target; return new Proxy({}, { get(_, prop, receiver) { target ?? (target = getter()); return Reflect.get(target, prop, receiver); }, set(_, prop, value, receiver) { target ?? (target = getter()); return Reflect.set(target, prop, value, receiver); }, has(_, prop) { target ?? (target = getter()); return Reflect.has(target, prop); }, deleteProperty(_, prop) { target ?? (target = getter()); return Reflect.deleteProperty(target, prop); }, ownKeys(_) { target ?? (target = getter()); return Reflect.ownKeys(target); }, getOwnPropertyDescriptor(_, prop) { target ?? (target = getter()); return Reflect.getOwnPropertyDescriptor(target, prop); }, defineProperty(_, prop, descriptor) { target ?? (target = getter()); return Reflect.defineProperty(target, prop, descriptor); } }); } function stringifyPrimitive(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } var NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; var BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick(schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".pick() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const newShape = {}; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; newShape[key] = currDef.shape[key]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function omit(schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".omit() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const newShape = { ...schema._zod.def.shape }; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } assignProp(this, "shape", newShape); return newShape; }, checks: [] }); return clone(schema, def); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { const existingShape = schema._zod.def.shape; for (const key in shape) { if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); } } } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; } }); return clone(schema, def); } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; } }); return clone(schema, def); } function merge(a, b) { const def = mergeDefs(a._zod.def, { get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; assignProp(this, "shape", _shape); return _shape; }, get catchall() { return b._zod.def.catchall; }, checks: [] // delete existing checks }); return clone(a, def); } function partial(Class2, schema, mask) { const currDef = schema._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error(".partial() cannot be used on object schemas containing refinements"); } const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in oldShape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } else { for (const key in oldShape) { shape[key] = Class2 ? new Class2({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } assignProp(this, "shape", shape); return shape; }, checks: [] }); return clone(schema, def); } function required(Class2, schema, mask) { const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = new Class2({ type: "nonoptional", innerType: oldShape[key] }); } } else { for (const key in oldShape) { shape[key] = new Class2({ type: "nonoptional", innerType: oldShape[key] }); } } assignProp(this, "shape", shape); return shape; } }); return clone(schema, def); } function aborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue !== true) { return true; } } return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a2; (_a2 = iss).path ?? (_a2.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue(iss, ctx, config2) { const full = { ...iss, path: iss.path ?? [] }; if (!iss.message) { const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; full.message = message; } delete full.inst; delete full.continue; if (!ctx?.reportInput) { delete full.input; } return full; } function getSizableOrigin(input) { if (input instanceof Set) return "set"; if (input instanceof Map) return "map"; if (input instanceof File) return "file"; return "unknown"; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function parsedType(data) { const t = typeof data; switch (t) { case "number": { return Number.isNaN(data) ? "nan" : "number"; } case "object": { if (data === null) { return "null"; } if (Array.isArray(data)) { return "array"; } const obj = data; if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { return obj.constructor.name; } } } return t; } function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst }; } return { ...iss }; } function cleanEnum(obj) { return Object.entries(obj).filter(([k, _]) => { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } function base64ToUint8Array(base643) { const binaryString = atob(base643); const bytes2 = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes2[i] = binaryString.charCodeAt(i); } return bytes2; } function uint8ArrayToBase64(bytes2) { let binaryString = ""; for (let i = 0; i < bytes2.length; i++) { binaryString += String.fromCharCode(bytes2[i]); } return btoa(binaryString); } function base64urlToUint8Array(base64url3) { const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); const padding = "=".repeat((4 - base643.length % 4) % 4); return base64ToUint8Array(base643 + padding); } function uint8ArrayToBase64url(bytes2) { return uint8ArrayToBase64(bytes2).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } function hexToUint8Array(hex3) { const cleanHex = hex3.replace(/^0x/, ""); if (cleanHex.length % 2 !== 0) { throw new Error("Invalid hex string length"); } const bytes2 = new Uint8Array(cleanHex.length / 2); for (let i = 0; i < cleanHex.length; i += 2) { bytes2[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); } return bytes2; } function uint8ArrayToHex(bytes2) { return Array.from(bytes2).map((b) => b.toString(16).padStart(2, "0")).join(""); } var Class = class { constructor(..._args) { } }; // node_modules/zod/v4/core/errors.js var initializer = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false }); Object.defineProperty(inst, "issues", { value: def, enumerable: false }); inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false }); }; var $ZodError = $constructor("$ZodError", initializer); var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); function flattenError(error48, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error48.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } function formatError(error48, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; const processError = (error49) => { for (const issue2 of error49.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues })); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }); } else if (issue2.path.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; let i = 0; while (i < issue2.path.length) { const el = issue2.path[i]; const terminal = i === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; i++; } } } }; processError(error48); return fieldErrors; } function treeifyError(error48, mapper = (issue2) => issue2.message) { const result = { errors: [] }; const processError = (error49, path = []) => { var _a2, _b; for (const issue2 of error49.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues }, issue2.path)); } else if (issue2.code === "invalid_key") { processError({ issues: issue2.issues }, issue2.path); } else if (issue2.code === "invalid_element") { processError({ issues: issue2.issues }, issue2.path); } else { const fullpath = [...path, ...issue2.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue2)); continue; } let curr = result; let i = 0; while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); (_a2 = curr.properties)[el] ?? (_a2[el] = { errors: [] }); curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue2)); } i++; } } } }; processError(error48); return result; } function toDotPath(_path) { const segs = []; const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); for (const seg of path) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); else { if (segs.length) segs.push("."); segs.push(seg); } } return segs.join(""); } function prettifyError(error48) { const lines = []; const issues = [...error48.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); for (const issue2 of issues) { lines.push(`\u2716 ${issue2.message}`); if (issue2.path?.length) lines.push(` \u2192 at ${toDotPath(issue2.path)}`); } return lines.join("\n"); } // node_modules/zod/v4/core/parse.js var _parse = (_Err) => (schema, value, _ctx, _params) => { const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, _params?.callee); throw e; } return result.value; }; var parse = /* @__PURE__ */ _parse($ZodRealError); var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, params?.callee); throw e; } return result.value; }; var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } return result.issues.length ? { success: false, error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; return result.issues.length ? { success: false, error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); var _encode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _parse(_Err)(schema, value, ctx); }; var encode = /* @__PURE__ */ _encode($ZodRealError); var _decode = (_Err) => (schema, value, _ctx) => { return _parse(_Err)(schema, value, _ctx); }; var decode = /* @__PURE__ */ _decode($ZodRealError); var _encodeAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _parseAsync(_Err)(schema, value, ctx); }; var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); var _decodeAsync = (_Err) => async (schema, value, _ctx) => { return _parseAsync(_Err)(schema, value, _ctx); }; var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); var _safeEncode = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _safeParse(_Err)(schema, value, ctx); }; var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); var _safeDecode = (_Err) => (schema, value, _ctx) => { return _safeParse(_Err)(schema, value, _ctx); }; var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _safeParseAsync(_Err)(schema, value, ctx); }; var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { return _safeParseAsync(_Err)(schema, value, _ctx); }; var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); // node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { base64: () => base64, base64url: () => base64url, bigint: () => bigint, boolean: () => boolean, browserEmail: () => browserEmail, cidrv4: () => cidrv4, cidrv6: () => cidrv6, cuid: () => cuid, cuid2: () => cuid2, date: () => date, datetime: () => datetime, domain: () => domain, duration: () => duration, e164: () => e164, email: () => email, emoji: () => emoji, extendedDuration: () => extendedDuration, guid: () => guid, hex: () => hex, hostname: () => hostname, html5Email: () => html5Email, idnEmail: () => idnEmail, integer: () => integer, ipv4: () => ipv4, ipv6: () => ipv6, ksuid: () => ksuid, lowercase: () => lowercase, mac: () => mac, md5_base64: () => md5_base64, md5_base64url: () => md5_base64url, md5_hex: () => md5_hex, nanoid: () => nanoid, null: () => _null, number: () => number, rfc5322Email: () => rfc5322Email, sha1_base64: () => sha1_base64, sha1_base64url: () => sha1_base64url, sha1_hex: () => sha1_hex, sha256_base64: () => sha256_base64, sha256_base64url: () => sha256_base64url, sha256_hex: () => sha256_hex, sha384_base64: () => sha384_base64, sha384_base64url: () => sha384_base64url, sha384_hex: () => sha384_hex, sha512_base64: () => sha512_base64, sha512_base64url: () => sha512_base64url, sha512_hex: () => sha512_hex, string: () => string, time: () => time, ulid: () => ulid, undefined: () => _undefined, unicodeEmail: () => unicodeEmail, uppercase: () => uppercase, uuid: () => uuid, uuid4: () => uuid4, uuid6: () => uuid6, uuid7: () => uuid7, xid: () => xid }); var cuid = /^[cC][^\s-]{8,}$/; var cuid2 = /^[0-9a-z]+$/; var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; var uuid = (version2) => { if (!version2) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; var uuid4 = /* @__PURE__ */ uuid(4); var uuid6 = /* @__PURE__ */ uuid(6); var uuid7 = /* @__PURE__ */ uuid(7); var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; var idnEmail = unicodeEmail; var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji() { return new RegExp(_emoji, "u"); } var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; var mac = (delimiter) => { const escapedDelim = escapeRegex(delimiter ?? ":"); return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); }; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url = /^[A-Za-z0-9_-]*$/; var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; var e164 = /^\+[1-9]\d{6,14}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); function timeSource(args) { const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; return regex; } function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { const time3 = timeSource({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); const timeRegex2 = `${time3}(?:${opts.join("|")})`; return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); } var string = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; var bigint = /^-?\d+n?$/; var integer = /^-?\d+$/; var number = /^-?\d+(?:\.\d+)?$/; var boolean = /^(?:true|false)$/i; var _null = /^null$/i; var _undefined = /^undefined$/i; var lowercase = /^[^A-Z]*$/; var uppercase = /^[^a-z]*$/; var hex = /^[0-9a-fA-F]*$/; function fixedBase64(bodyLength, padding) { return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); } function fixedBase64url(length) { return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); } var md5_hex = /^[0-9a-fA-F]{32}$/; var md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); var md5_base64url = /* @__PURE__ */ fixedBase64url(22); var sha1_hex = /^[0-9a-fA-F]{40}$/; var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); var sha1_base64url = /* @__PURE__ */ fixedBase64url(27); var sha256_hex = /^[0-9a-fA-F]{64}$/; var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); var sha256_base64url = /* @__PURE__ */ fixedBase64url(43); var sha384_hex = /^[0-9a-fA-F]{96}$/; var sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); var sha384_base64url = /* @__PURE__ */ fixedBase64url(64); var sha512_hex = /^[0-9a-fA-F]{128}$/; var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); // node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a2; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a2 = inst._zod).onattach ?? (_a2.onattach = []); }); var numericOriginMap = { number: "number", bigint: "bigint", object: "date" }; var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { var _a2; (_a2 = inst2._zod.bag).multipleOf ?? (_a2.multipleOf = def.value); }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ origin: typeof payload.value, code: "not_multiple_of", divisor: def.value, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { $ZodCheck.init(inst, def); def.format = def.format || "float64"; const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) { payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); } else { payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); } return; } } if (input < minimum) { payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "number", input, code: "too_big", maximum, inclusive: true, inst, continue: !def.abort }); } }; }); var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; }); inst._zod.check = (payload) => { const input = payload.value; if (input < minimum) { payload.issues.push({ origin: "bigint", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inclusive: true, inst, continue: !def.abort }); } }; }); var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { var _a2; $ZodCheck.init(inst, def); (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size <= def.maximum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { var _a2; $ZodCheck.init(inst, def); (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size >= def.minimum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { var _a2; $ZodCheck.init(inst, def); (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { const val = payload.value; return !nullish(val) && val.size !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.size; bag.maximum = def.size; bag.size = def.size; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size === def.size) return; const tooBig = size > def.size; payload.issues.push({ origin: getSizableOrigin(input), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { var _a2; $ZodCheck.init(inst, def); (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length <= def.maximum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_big", maximum: def.maximum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { var _a2; $ZodCheck.init(inst, def); (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length >= def.minimum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { var _a2; $ZodCheck.init(inst, def); (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.minimum = def.length; bag.maximum = def.length; bag.length = def.length; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length === def.length) return; const origin = getLengthableOrigin(input); const tooBig = length > def.length; payload.issues.push({ origin, ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, inclusive: true, exact: true, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { var _a2, _b; $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.format = def.format; if (def.pattern) { bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(def.pattern); } }); if (def.pattern) (_a2 = inst._zod).check ?? (_a2.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: def.format, input: payload.value, ...def.pattern ? { pattern: def.pattern.toString() } : {}, inst, continue: !def.abort }); }); else (_b = inst._zod).check ?? (_b.check = () => { }); }); var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { $ZodCheckStringFormat.init(inst, def); inst._zod.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "regex", input: payload.value, pattern: def.pattern.toString(), inst, continue: !def.abort }); }; }); var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { def.pattern ?? (def.pattern = lowercase); $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { def.pattern ?? (def.pattern = uppercase); $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { $ZodCheck.init(inst, def); const escapedRegex = escapeRegex(def.includes); const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); def.pattern = pattern; inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.includes(def.includes, def.position)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: def.includes, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.startsWith(def.prefix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: def.prefix, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); def.pattern ?? (def.pattern = pattern); inst._zod.onattach.push((inst2) => { const bag = inst2._zod.bag; bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { if (payload.value.endsWith(def.suffix)) return; payload.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: def.suffix, input: payload.value, inst, continue: !def.abort }); }; }); function handleCheckPropertyResult(result, payload, property) { if (result.issues.length) { payload.issues.push(...prefixIssues(property, result.issues)); } } var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { const result = def.schema._zod.run({ value: payload.value[def.property], issues: [] }, {}); if (result instanceof Promise) { return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); } handleCheckPropertyResult(result, payload, def.property); return; }; }); var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { $ZodCheck.init(inst, def); const mimeSet = new Set(def.mime); inst._zod.onattach.push((inst2) => { inst2._zod.bag.mime = def.mime; }); inst._zod.check = (payload) => { if (mimeSet.has(payload.value.type)) return; payload.issues.push({ code: "invalid_value", values: def.mime, input: payload.value.type, inst, continue: !def.abort }); }; }); var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); // node_modules/zod/v4/core/doc.js var Doc = class { constructor(args = []) { this.content = []; this.indent = 0; if (this) this.args = args; } indented(fn) { this.indent += 1; fn(this); this.indent -= 1; } write(arg) { if (typeof arg === "function") { arg(this, { execution: "sync" }); arg(this, { execution: "async" }); return; } const content = arg; const lines = content.split("\n").filter((x) => x); const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); for (const line of dedented) { this.content.push(line); } } compile() { const F = Function; const args = this?.args; const content = this?.content ?? [``]; const lines = [...content.map((x) => ` ${x}`)]; return new F(...args, lines.join("\n")); } }; // node_modules/zod/v4/core/versions.js var version = { major: 4, minor: 3, patch: 6 }; // node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { var _a2; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; const checks = [...inst._zod.def.checks ?? []]; if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); } } if (checks.length === 0) { (_a2 = inst._zod).deferred ?? (_a2.deferred = []); inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks2, ctx) => { let isAborted2 = aborted(payload); let asyncResult; for (const ch of checks2) { if (ch._zod.def.when) { const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted2) { continue; } const currLen = payload.issues.length; const _ = ch._zod.check(payload); if (_ instanceof Promise && ctx?.async === false) { throw new $ZodAsyncError(); } if (asyncResult || _ instanceof Promise) { asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { await _; const nextLen = payload.issues.length; if (nextLen === currLen) return; if (!isAborted2) isAborted2 = aborted(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted2) isAborted2 = aborted(payload, currLen); } } if (asyncResult) { return asyncResult.then(() => { return payload; }); } return payload; }; const handleCanaryResult = (canary, payload, ctx) => { if (aborted(canary)) { canary.aborted = true; return canary; } const checkResult = runChecks(payload, checks, ctx); if (checkResult instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); } return inst._zod.parse(checkResult, ctx); }; inst._zod.run = (payload, ctx) => { if (ctx.skipChecks) { return inst._zod.parse(payload, ctx); } if (ctx.direction === "backward") { const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); if (canary instanceof Promise) { return canary.then((canary2) => { return handleCanaryResult(canary2, payload, ctx); }); } return handleCanaryResult(canary, payload, ctx); } const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return result.then((result2) => runChecks(result2, checks, ctx)); } return runChecks(result, checks, ctx); }; } defineLazy(inst, "~standard", () => ({ validate: (value) => { try { const r = safeParse(inst, value); return r.success ? { value: r.data } : { issues: r.error?.issues }; } catch (_) { return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } }, vendor: "zod", version: 1 })); }); var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_2) { } if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { $ZodCheckStringFormat.init(inst, def); $ZodString.init(inst, def); }); var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { def.pattern ?? (def.pattern = guid); $ZodStringFormat.init(inst, def); }); var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { if (def.version) { const versionMap = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }; const v = versionMap[def.version]; if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); def.pattern ?? (def.pattern = uuid(v)); } else def.pattern ?? (def.pattern = uuid()); $ZodStringFormat.init(inst, def); }); var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { def.pattern ?? (def.pattern = email); $ZodStringFormat.init(inst, def); }); var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { const trimmed = payload.value.trim(); const url2 = new URL(trimmed); if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url2.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: def.hostname.source, input: payload.value, inst, continue: !def.abort }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort }); } } if (def.normalize) { payload.value = url2.href; } else { payload.value = trimmed; } return; } catch (_) { payload.issues.push({ code: "invalid_format", format: "url", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { def.pattern ?? (def.pattern = emoji()); $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { def.pattern ?? (def.pattern = nanoid); $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { def.pattern ?? (def.pattern = cuid); $ZodStringFormat.init(inst, def); }); var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { def.pattern ?? (def.pattern = cuid2); $ZodStringFormat.init(inst, def); }); var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { def.pattern ?? (def.pattern = ulid); $ZodStringFormat.init(inst, def); }); var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { def.pattern ?? (def.pattern = xid); $ZodStringFormat.init(inst, def); }); var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { def.pattern ?? (def.pattern = ksuid); $ZodStringFormat.init(inst, def); }); var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { def.pattern ?? (def.pattern = datetime(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { def.pattern ?? (def.pattern = date); $ZodStringFormat.init(inst, def); }); var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { def.pattern ?? (def.pattern = time(def)); $ZodStringFormat.init(inst, def); }); var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { def.pattern ?? (def.pattern = duration); $ZodStringFormat.init(inst, def); }); var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { def.pattern ?? (def.pattern = ipv4); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `ipv4`; }); var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { def.pattern ?? (def.pattern = ipv6); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); } catch { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort }); } }; }); var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { def.pattern ?? (def.pattern = mac(def.delimiter)); $ZodStringFormat.init(inst, def); inst._zod.bag.format = `mac`; }); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { def.pattern ?? (def.pattern = cidrv4); $ZodStringFormat.init(inst, def); }); var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { def.pattern ?? (def.pattern = cidrv6); $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { const parts = payload.value.split("/"); try { if (parts.length !== 2) throw new Error(); const [address, prefix] = parts; if (!prefix) throw new Error(); const prefixNum = Number(prefix); if (`${prefixNum}` !== prefix) throw new Error(); if (prefixNum < 0 || prefixNum > 128) throw new Error(); new URL(`http://[${address}]`); } catch { payload.issues.push({ code: "invalid_format", format: "cidrv6", input: payload.value, inst, continue: !def.abort }); } }; }); function isValidBase64(data) { if (data === "") return true; if (data.length % 4 !== 0) return false; try { atob(data); return true; } catch { return false; } } var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { def.pattern ?? (def.pattern = base64); $ZodStringFormat.init(inst, def); inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort }); }; }); function isValidBase64URL(data) { if (!base64url.test(data)) return false; const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { def.pattern ?? (def.pattern = base64url); $ZodStringFormat.init(inst, def); inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64url", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { def.pattern ?? (def.pattern = e164); $ZodStringFormat.init(inst, def); }); function isValidJWT(token, algorithm = null) { try { const tokensParts = token.split("."); if (tokensParts.length !== 3) return false; const [header] = tokensParts; if (!header) return false; const parsedHeader = JSON.parse(atob(header)); if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; if (!parsedHeader.alg) return false; if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; } catch { return false; } } var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (isValidJWT(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", format: "jwt", input: payload.value, inst, continue: !def.abort }); }; }); var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (def.fn(payload.value)) return; payload.issues.push({ code: "invalid_format", format: def.format, input: payload.value, inst, continue: !def.abort }); }; }); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = inst._zod.bag.pattern ?? number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...received ? { received } : {} }); return payload; }; }); var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); }); var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = boolean; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_) { } const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst }); return payload; }; }); var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = bigint; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = BigInt(payload.value); } catch (_) { } if (typeof payload.value === "bigint") return payload; payload.issues.push({ expected: "bigint", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { $ZodCheckBigIntFormat.init(inst, def); $ZodBigInt.init(inst, def); }); var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", input, inst }); return payload; }; }); var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _undefined; inst._zod.values = /* @__PURE__ */ new Set([void 0]); inst._zod.optin = "optional"; inst._zod.optout = "optional"; inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", input, inst }); return payload; }; }); var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _null; inst._zod.values = /* @__PURE__ */ new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst }); return payload; }; }); var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.issues.push({ expected: "never", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", input, inst }); return payload; }; }); var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (def.coerce) { try { payload.value = new Date(payload.value); } catch (_err) { } } const input = payload.value; const isDate = input instanceof Date; const isValidDate = isDate && !Number.isNaN(input.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", input, ...isDate ? { received: "Invalid Date" } : {}, inst }); return payload; }; }); function handleArrayResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst }); return payload; } payload.value = Array(input.length); const proms = []; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); } else { handleArrayResult(result, payload, i); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); function handlePropertyResult(result, final, key, input, isOptionalOut) { if (result.issues.length) { if (isOptionalOut && !(key in input)) { return; } final.issues.push(...prefixIssues(key, result.issues)); } if (result.value === void 0) { if (key in input) { final.value[key] = void 0; } } else { final.value[key] = result.value; } } function normalizeDef(def) { const keys = Object.keys(def.shape); for (const k of keys) { if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } const okeys = optionalKeys(def.shape); return { ...def, keys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } function handleCatchall(proms, input, payload, ctx, def, inst) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; const isOptionalOut = _catchall.optout === "optional"; for (const key in input) { if (keySet.has(key)) continue; if (t === "never") { unrecognized.push(key); continue; } const r = _catchall.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); } else { handlePropertyResult(r, payload, key, input, isOptionalOut); } } if (unrecognized.length) { payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, input, inst }); } if (!proms.length) return payload; return Promise.all(proms).then(() => { return payload; }); } var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc = Object.getOwnPropertyDescriptor(def, "shape"); if (!desc?.get) { const sh = def.shape; Object.defineProperty(def, "shape", { get: () => { const newSh = { ...sh }; Object.defineProperty(def, "shape", { value: newSh }); return newSh; } }); } const _normalized = cached(() => normalizeDef(def)); defineLazy(inst._zod, "propValues", () => { const shape = def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); for (const v of field.values) propValues[key].add(v); } } return propValues; }); const isObject2 = isObject; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } payload.value = {}; const proms = []; const shape = value.shape; for (const key of value.keys) { const el = shape[key]; const isOptionalOut = el._zod.optout === "optional"; const r = el._zod.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) { proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalOut))); } else { handlePropertyResult(r, payload, key, input, isOptionalOut); } } if (!catchall) { return proms.length ? Promise.all(proms).then(() => payload) : payload; } return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); }; }); var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { $ZodObject.init(inst, def); const superParse = inst._zod.parse; const _normalized = cached(() => normalizeDef(def)); const generateFastpass = (shape) => { const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key) => { const k = esc(key); return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; }; doc.write(`const input = payload.value;`); const ids = /* @__PURE__ */ Object.create(null); let counter = 0; for (const key of normalized.keys) { ids[key] = `key_${counter++}`; } doc.write(`const newResult = {};`); for (const key of normalized.keys) { const id = ids[key]; const k = esc(key); const schema = shape[key]; const isOptionalOut = schema?._zod?.optout === "optional"; doc.write(`const ${id} = ${parseStr(key)};`); if (isOptionalOut) { doc.write(` if (${id}.issues.length) { if (${k} in input) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } } if (${id}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { newResult[${k}] = ${id}.value; } `); } else { doc.write(` if (${id}.issues.length) { payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (${id}.value === undefined) { if (${k} in input) { newResult[${k}] = undefined; } } else { newResult[${k}] = ${id}.value; } `); } } doc.write(`payload.value = newResult;`); doc.write(`return payload;`); const fn = doc.compile(); return (payload, ctx) => fn(shape, payload, ctx); }; let fastpass; const isObject2 = isObject; const jit = !globalConfig.jitless; const allowsEval2 = allowsEval; const fastEnabled = jit && allowsEval2.value; const catchall = def.catchall; let value; inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { if (!fastpass) fastpass = generateFastpass(def.shape); payload = fastpass(payload, ctx); if (!catchall) return payload; return handleCatchall([], input, payload, ctx, value, inst); } return superParse(payload, ctx); }; }); function handleUnionResults(results, final, inst, ctx) { for (const result of results) { if (result.issues.length === 0) { final.value = result.value; return final; } } const nonaborted = results.filter((r) => !aborted(r)); if (nonaborted.length === 1) { final.value = nonaborted[0].value; return nonaborted[0]; } final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); return final; } var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); defineLazy(inst._zod, "values", () => { if (def.options.every((o) => o._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } return void 0; }); defineLazy(inst._zod, "pattern", () => { if (def.options.every((o) => o._zod.pattern)) { const patterns = def.options.map((o) => o._zod.pattern); return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } return void 0; }); const single = def.options.length === 1; const first = def.options[0]._zod.run; inst._zod.parse = (payload, ctx) => { if (single) { return first(payload, ctx); } let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { if (result.issues.length === 0) return result; results.push(result); } } if (!async) return handleUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleUnionResults(results2, payload, inst, ctx); }); }; }); function handleExclusiveUnionResults(results, final, inst, ctx) { const successes = results.filter((r) => r.issues.length === 0); if (successes.length === 1) { final.value = successes[0].value; return final; } if (successes.length === 0) { final.issues.push({ code: "invalid_union", input: final.value, inst, errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); } else { final.issues.push({ code: "invalid_union", input: final.value, inst, errors: [], inclusive: false }); } return final; } var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { $ZodUnion.init(inst, def); def.inclusive = false; const single = def.options.length === 1; const first = def.options[0]._zod.run; inst._zod.parse = (payload, ctx) => { if (single) { return first(payload, ctx); } let async = false; const results = []; for (const option of def.options) { const result = option._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) { results.push(result); async = true; } else { results.push(result); } } if (!async) return handleExclusiveUnionResults(results, payload, inst, ctx); return Promise.all(results).then((results2) => { return handleExclusiveUnionResults(results2, payload, inst, ctx); }); }; }); var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; defineLazy(inst._zod, "propValues", () => { const propValues = {}; for (const option of def.options) { const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); for (const [k, v] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); for (const val of v) { propValues[k].add(val); } } } return propValues; }); const disc = cached(() => { const opts = def.options; const map2 = /* @__PURE__ */ new Map(); for (const o of opts) { const values = o._zod.propValues?.[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); for (const v of values) { if (map2.has(v)) { throw new Error(`Duplicate discriminator value "${String(v)}"`); } map2.set(v, o); } } return map2; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isObject(input)) { payload.issues.push({ code: "invalid_type", expected: "object", input, inst }); return payload; } const opt = disc.value.get(input?.[def.discriminator]); if (opt) { return opt._zod.run(payload, ctx); } if (def.unionFallback) { return _super(payload, ctx); } payload.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", discriminator: def.discriminator, input, path: [def.discriminator], inst }); return payload; }; }); var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; const left = def.left._zod.run({ value: input, issues: [] }, ctx); const right = def.right._zod.run({ value: input, issues: [] }, ctx); const async = left instanceof Promise || right instanceof Promise; if (async) { return Promise.all([left, right]).then(([left2, right2]) => { return handleIntersectionResults(payload, left2, right2); }); } return handleIntersectionResults(payload, left, right); }; }); function mergeValues(a, b) { if (a === b) { return { valid: true, data: a }; } if (a instanceof Date && b instanceof Date && +a === +b) { return { valid: true, data: a }; } if (isPlainObject(a) && isPlainObject(b)) { const bKeys = Object.keys(b); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [key, ...sharedValue.mergeErrorPath] }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return { valid: false, mergeErrorPath: [] }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false, mergeErrorPath: [index, ...sharedValue.mergeErrorPath] }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } return { valid: false, mergeErrorPath: [] }; } function handleIntersectionResults(result, left, right) { const unrecKeys = /* @__PURE__ */ new Map(); let unrecIssue; for (const iss of left.issues) { if (iss.code === "unrecognized_keys") { unrecIssue ?? (unrecIssue = iss); for (const k of iss.keys) { if (!unrecKeys.has(k)) unrecKeys.set(k, {}); unrecKeys.get(k).l = true; } } else { result.issues.push(iss); } } for (const iss of right.issues) { if (iss.code === "unrecognized_keys") { for (const k of iss.keys) { if (!unrecKeys.has(k)) unrecKeys.set(k, {}); unrecKeys.get(k).r = true; } } else { result.issues.push(iss); } } const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); if (bothKeys.length && unrecIssue) { result.issues.push({ ...unrecIssue, keys: bothKeys }); } if (aborted(result)) return result; const merged = mergeValues(left.value, right.value); if (!merged.valid) { throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); } result.value = merged.data; return result; } var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { $ZodType.init(inst, def); const items = def.items; inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ input, inst, expected: "tuple", code: "invalid_type" }); return payload; } payload.value = []; const proms = []; const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; if (!def.rest) { const tooBig = input.length > items.length; const tooSmall = input.length < optStart - 1; if (tooBig || tooSmall) { payload.issues.push({ ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, input, inst, origin: "array" }); return payload; } } let i = -1; for (const item of items) { i++; if (i >= input.length) { if (i >= optStart) continue; } const result = item._zod.run({ value: input[i], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); } else { handleTupleResult(result, payload, i); } } if (def.rest) { const rest = input.slice(items.length); for (const el of rest) { i++; const result = def.rest._zod.run({ value: el, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleTupleResult(result2, payload, i))); } else { handleTupleResult(result, payload, i); } } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleTupleResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); } final.value[index] = result.value; } var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isPlainObject(input)) { payload.issues.push({ expected: "record", code: "invalid_type", input, inst }); return payload; } const proms = []; const values = def.keyType._zod.values; if (values) { payload.value = {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[key] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[key] = result.value; } } } let unrecognized; for (const key in input) { if (!recordKeys.has(key)) { unrecognized = unrecognized ?? []; unrecognized.push(key); } } if (unrecognized && unrecognized.length > 0) { payload.issues.push({ code: "unrecognized_keys", input, inst, keys: unrecognized }); } } else { payload.value = {}; for (const key of Reflect.ownKeys(input)) { if (key === "__proto__") continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; if (checkNumericKey) { const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); if (retryResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } if (retryResult.issues.length === 0) { keyResult = retryResult; } } if (keyResult.issues.length) { if (def.mode === "loose") { payload.value[key] = input[key]; } else { payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); } continue; } const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { if (result2.issues.length) { payload.issues.push(...prefixIssues(key, result2.issues)); } payload.value[keyResult.value] = result2.value; })); } else { if (result.issues.length) { payload.issues.push(...prefixIssues(key, result.issues)); } payload.value[keyResult.value] = result.value; } } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; }; }); var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Map)) { payload.issues.push({ expected: "map", code: "invalid_type", input, inst }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Map(); for (const [key, value] of input) { const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); if (keyResult instanceof Promise || valueResult instanceof Promise) { proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); })); } else { handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { if (keyResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, keyResult.issues)); } else { final.issues.push({ code: "invalid_key", origin: "map", input, inst, issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } if (valueResult.issues.length) { if (propertyKeyTypes.has(typeof key)) { final.issues.push(...prefixIssues(key, valueResult.issues)); } else { final.issues.push({ origin: "map", code: "invalid_element", input, inst, key, issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) }); } } final.value.set(keyResult.value, valueResult.value); } var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!(input instanceof Set)) { payload.issues.push({ input, inst, expected: "set", code: "invalid_type" }); return payload; } const proms = []; payload.value = /* @__PURE__ */ new Set(); for (const item of input) { const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => handleSetResult(result2, payload))); } else handleSetResult(result, payload); } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); function handleSetResult(result, final) { if (result.issues.length) { final.issues.push(...result.issues); } final.value.add(result.value); } var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); const valuesSet = new Set(values); inst._zod.values = valuesSet; inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (valuesSet.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values, input, inst }); return payload; }; }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); if (def.values.length === 0) { throw new Error("Cannot create literal schema with no valid values"); } const values = new Set(def.values); inst._zod.values = values; inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (values.has(input)) { return payload; } payload.issues.push({ code: "invalid_value", values: def.values, input, inst }); return payload; }; }); var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input instanceof File) return payload; payload.issues.push({ expected: "file", code: "invalid_type", input, inst }); return payload; }; }); var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } const _out = def.transform(payload.value, payload); if (ctx.async) { const output = _out instanceof Promise ? _out : Promise.resolve(_out); return output.then((output2) => { payload.value = output2; return payload; }); } if (_out instanceof Promise) { throw new $ZodAsyncError(); } payload.value = _out; return payload; }; }); function handleOptionalResult(result, input) { if (result.issues.length && input === void 0) { return { issues: [], value: void 0 }; } return result; } var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; inst._zod.optout = "optional"; defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; }); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value)); return handleOptionalResult(result, payload.value); } if (payload.value === void 0) { return payload; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { $ZodOptional.init(inst, def); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); inst._zod.parse = (payload, ctx) => { return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "pattern", () => { const pattern = def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); defineLazy(inst._zod, "values", () => { return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; return payload; } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleDefaultResult(result2, def)); } return handleDefaultResult(result, def); }; }); function handleDefaultResult(payload, def) { if (payload.value === void 0) { payload.value = def.defaultValue; } return payload; } var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } if (payload.value === void 0) { payload.value = def.defaultValue; } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => { const v = def.innerType._zod.values; return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => handleNonOptionalResult(result2, inst)); } return handleNonOptionalResult(result, inst); }; }); function handleNonOptionalResult(payload, inst) { if (!payload.issues.length && payload.value === void 0) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: payload.value, inst }); } return payload; } var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { throw new $ZodEncodeError("ZodSuccess"); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.issues.length === 0; return payload; }); } payload.value = result.issues.length === 0; return payload; }; }); var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { payload.value = result2.value; if (result2.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value }); payload.issues = []; } return payload; }); } payload.value = result.value; if (result.issues.length) { payload.value = def.catchValue({ ...payload, error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, input: payload.value }); payload.issues = []; } return payload; }; }); var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { payload.issues.push({ input: payload.value, inst, expected: "nan", code: "invalid_type" }); return payload; } return payload; }; }); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handlePipeResult(right2, def.in, ctx)); } return handlePipeResult(right, def.in, ctx); } const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handlePipeResult(left2, def.out, ctx)); } return handlePipeResult(left, def.out, ctx); }; }); function handlePipeResult(left, next, ctx) { if (left.issues.length) { left.aborted = true; return left; } return next._zod.run({ value: left.value, issues: left.issues }, ctx); } var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { const direction = ctx.direction || "forward"; if (direction === "forward") { const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { return left.then((left2) => handleCodecAResult(left2, def, ctx)); } return handleCodecAResult(left, def, ctx); } else { const right = def.out._zod.run(payload, ctx); if (right instanceof Promise) { return right.then((right2) => handleCodecAResult(right2, def, ctx)); } return handleCodecAResult(right, def, ctx); } }; }); function handleCodecAResult(result, def, ctx) { if (result.issues.length) { result.aborted = true; return result; } const direction = ctx.direction || "forward"; if (direction === "forward") { const transformed = def.transform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); } return handleCodecTxResult(result, transformed, def.out, ctx); } else { const transformed = def.reverseTransform(result.value, result); if (transformed instanceof Promise) { return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); } return handleCodecTxResult(result, transformed, def.in, ctx); } } function handleCodecTxResult(left, value, nextSchema, ctx) { if (left.issues.length) { left.aborted = true; return left; } return nextSchema._zod.run({ value, issues: left.issues }, ctx); } var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy(inst._zod, "values", () => def.innerType._zod.values); defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); inst._zod.parse = (payload, ctx) => { if (ctx.direction === "backward") { return def.innerType._zod.run(payload, ctx); } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then(handleReadonlyResult); } return handleReadonlyResult(result); }; }); function handleReadonlyResult(payload) { payload.value = Object.freeze(payload.value); return payload; } var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { $ZodType.init(inst, def); const regexParts = []; for (const part of def.parts) { if (typeof part === "object" && part !== null) { if (!part._zod.pattern) { throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); } const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; if (!source) throw new Error(`Invalid template literal part: ${part._zod.traits}`); const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; regexParts.push(source.slice(start, end)); } else if (part === null || primitiveTypes.has(typeof part)) { regexParts.push(escapeRegex(`${part}`)); } else { throw new Error(`Invalid template literal part: ${part}`); } } inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "string") { payload.issues.push({ input: payload.value, inst, expected: "string", code: "invalid_type" }); return payload; } inst._zod.pattern.lastIndex = 0; if (!inst._zod.pattern.test(payload.value)) { payload.issues.push({ input: payload.value, inst, code: "invalid_format", format: def.format ?? "template_literal", pattern: inst._zod.pattern.source }); return payload; } return payload; }; }); var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { $ZodType.init(inst, def); inst._def = def; inst._zod.def = def; inst.implement = (func) => { if (typeof func !== "function") { throw new Error("implement() must be called with a function"); } return function(...args) { const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return parse(inst._def.output, result); } return result; }; }; inst.implementAsync = (func) => { if (typeof func !== "function") { throw new Error("implementAsync() must be called with a function"); } return async function(...args) { const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; const result = await Reflect.apply(func, this, parsedArgs); if (inst._def.output) { return await parseAsync(inst._def.output, result); } return result; }; }; inst._zod.parse = (payload, _ctx) => { if (typeof payload.value !== "function") { payload.issues.push({ code: "invalid_type", expected: "function", input: payload.value, inst }); return payload; } const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; if (hasPromiseOutput) { payload.value = inst.implementAsync(payload.value); } else { payload.value = inst.implement(payload.value); } return payload; }; inst.input = (...args) => { const F = inst.constructor; if (Array.isArray(args[0])) { return new F({ type: "function", input: new $ZodTuple({ type: "tuple", items: args[0], rest: args[1] }), output: inst._def.output }); } return new F({ type: "function", input: args[0], output: inst._def.output }); }; inst.output = (output) => { const F = inst.constructor; return new F({ type: "function", input: inst._def.input, output }); }; return inst; }); var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); }; }); var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "innerType", () => def.getter()); defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); inst._zod.parse = (payload, ctx) => { const inner = inst._zod.innerType; return inner._zod.run(payload, ctx); }; }); var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { $ZodCheck.init(inst, def); $ZodType.init(inst, def); inst._zod.parse = (payload, _) => { return payload; }; inst._zod.check = (payload) => { const input = payload.value; const r = def.fn(input); if (r instanceof Promise) { return r.then((r2) => handleRefineResult(r2, payload, input, inst)); } handleRefineResult(r, payload, input, inst); return; }; }); function handleRefineResult(result, payload, input, inst) { if (!result) { const _iss = { code: "custom", input, inst, // incorporates params.error into issue reporting path: [...inst._zod.def.path ?? []], // incorporates params.error into issue reporting continue: !inst._zod.def.abort // params: inst._zod.def.params, }; if (inst._zod.def.params) _iss.params = inst._zod.def.params; payload.issues.push(issue(_iss)); } } // node_modules/zod/v4/locales/index.js var locales_exports = {}; __export(locales_exports, { ar: () => ar_default, az: () => az_default, be: () => be_default, bg: () => bg_default, ca: () => ca_default, cs: () => cs_default, da: () => da_default, de: () => de_default, en: () => en_default, eo: () => eo_default, es: () => es_default, fa: () => fa_default, fi: () => fi_default, fr: () => fr_default, frCA: () => fr_CA_default, he: () => he_default, hu: () => hu_default, hy: () => hy_default, id: () => id_default, is: () => is_default, it: () => it_default, ja: () => ja_default, ka: () => ka_default, kh: () => kh_default, km: () => km_default, ko: () => ko_default, lt: () => lt_default, mk: () => mk_default, ms: () => ms_default, nl: () => nl_default, no: () => no_default, ota: () => ota_default, pl: () => pl_default, ps: () => ps_default, pt: () => pt_default, ru: () => ru_default, sl: () => sl_default, sv: () => sv_default, ta: () => ta_default, th: () => th_default, tr: () => tr_default, ua: () => ua_default, uk: () => uk_default, ur: () => ur_default, uz: () => uz_default, vi: () => vi_default, yo: () => yo_default, zhCN: () => zh_CN_default, zhTW: () => zh_TW_default }); // node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0645\u062F\u062E\u0644", email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", url: "\u0631\u0627\u0628\u0637", emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; } return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; if (_issue.format === "ends_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; if (_issue.format === "regex") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; } case "not_multiple_of": return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; case "unrecognized_keys": return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; case "invalid_union": return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; case "invalid_element": return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; default: return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; } }; }; function ar_default() { return { localeError: error() }; } // node_modules/zod/v4/locales/az.js var error2 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, set: { unit: "element", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; } return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; if (_issue.format === "ends_with") return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; if (_issue.format === "includes") return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; if (_issue.format === "regex") return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; case "unrecognized_keys": return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; case "invalid_union": return "Yanl\u0131\u015F d\u0259y\u0259r"; case "invalid_element": return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; default: return `Yanl\u0131\u015F d\u0259y\u0259r`; } }; }; function az_default() { return { localeError: error2() }; } // node_modules/zod/v4/locales/be.js function getBelarusianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error3 = () => { const Sizable = { string: { unit: { one: "\u0441\u0456\u043C\u0432\u0430\u043B", few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u044B", many: "\u0431\u0430\u0439\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0443\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0430\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0447\u0430\u0441", duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u043B\u0456\u043A", array: "\u043C\u0430\u0441\u0456\u045E" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; } return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; case "invalid_element": return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; default: return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; } }; }; function be_default() { return { localeError: error3() }; } // node_modules/zod/v4/locales/bg.js var error4 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0445\u043E\u0434", email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", json_string: "JSON \u043D\u0438\u0437", e164: "E.164 \u043D\u043E\u043C\u0435\u0440", jwt: "JWT", template_literal: "\u0432\u0445\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0438\u0432" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; } return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; if (_issue.format === "emoji") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "datetime") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "date") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; if (_issue.format === "time") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; if (_issue.format === "duration") invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; case "invalid_element": return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; default: return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; } }; }; function bg_default() { return { localeError: error4() }; } // node_modules/zod/v4/locales/ca.js var error5 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entrada", email: "adre\xE7a electr\xF2nica", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; } return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; case "too_big": { const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; const sizing = getSizing(issue2.origin); if (sizing) return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; const sizing = getSizing(issue2.origin); if (sizing) { return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; if (_issue.format === "includes") return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; if (_issue.format === "regex") return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; case "unrecognized_keys": return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Clau inv\xE0lida a ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE0lida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general case "invalid_element": return `Element inv\xE0lid a ${issue2.origin}`; default: return `Entrada inv\xE0lida`; } }; }; function ca_default() { return { localeError: error5() }; } // node_modules/zod/v4/locales/cs.js var error6 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, set: { unit: "prvk\u016F", verb: "m\xEDt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "regul\xE1rn\xED v\xFDraz", email: "e-mailov\xE1 adresa", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "datum a \u010Das ve form\xE1tu ISO", date: "datum ve form\xE1tu ISO", time: "\u010Das ve form\xE1tu ISO", duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", jwt: "JWT", template_literal: "vstup" }; const TypeDictionary = { nan: "NaN", number: "\u010D\xEDslo", string: "\u0159et\u011Bzec", function: "funkce", array: "pole" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; } return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; } return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; if (_issue.format === "includes") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; if (_issue.format === "regex") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; case "unrecognized_keys": return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; case "invalid_union": return "Neplatn\xFD vstup"; case "invalid_element": return `Neplatn\xE1 hodnota v ${issue2.origin}`; default: return `Neplatn\xFD vstup`; } }; }; function cs_default() { return { localeError: error6() }; } // node_modules/zod/v4/locales/da.js var error7 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, array: { unit: "elementer", verb: "indeholdt" }, set: { unit: "elementer", verb: "indeholdt" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "e-mailadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkesl\xE6t", date: "ISO-dato", time: "ISO-klokkesl\xE6t", duration: "ISO-varighed", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodet streng", base64url: "base64url-kodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", string: "streng", number: "tal", boolean: "boolean", array: "liste", object: "objekt", set: "s\xE6t", file: "fil" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; } return `Ugyldigt input: forventede ${expected}, fik ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) { return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ugyldig streng: skal starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: skal ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: skal indeholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8gle i ${issue2.origin}`; case "invalid_union": return "Ugyldigt input: matcher ingen af de tilladte typer"; case "invalid_element": return `Ugyldig v\xE6rdi i ${issue2.origin}`; default: return `Ugyldigt input`; } }; }; function da_default() { return { localeError: error7() }; } // node_modules/zod/v4/locales/de.js var error8 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "Eingabe", email: "E-Mail-Adresse", url: "URL", emoji: "Emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" }; const TypeDictionary = { nan: "NaN", number: "Zahl", array: "Array" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; } return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; } return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; if (_issue.format === "ends_with") return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; if (_issue.format === "includes") return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; if (_issue.format === "regex") return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; case "invalid_union": return "Ung\xFCltige Eingabe"; case "invalid_element": return `Ung\xFCltiger Wert in ${issue2.origin}`; default: return `Ung\xFCltige Eingabe`; } }; }; function de_default() { return { localeError: error8() }; } // node_modules/zod/v4/locales/en.js var error9 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, array: { unit: "items", verb: "to have" }, set: { unit: "items", verb: "to have" }, map: { unit: "entries", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", mac: "MAC address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { // Compatibility: "nan" -> "NaN" for display nan: "NaN" // All other type names omitted - they fall back to raw values via ?? operator }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; return `Invalid input: expected ${expected}, received ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Invalid string: must start with "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`; if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`; if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Invalid number: must be a multiple of ${issue2.divisor}`; case "unrecognized_keys": return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Invalid key in ${issue2.origin}`; case "invalid_union": return "Invalid input"; case "invalid_element": return `Invalid value in ${issue2.origin}`; default: return `Invalid input`; } }; }; function en_default() { return { localeError: error9() }; } // node_modules/zod/v4/locales/eo.js var error10 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emo\u011Dio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" }; const TypeDictionary = { nan: "NaN", number: "nombro", array: "tabelo", null: "senvalora" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; } return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; if (_issue.format === "includes") return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; if (_issue.format === "regex") return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; case "unrecognized_keys": return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nevalida \u015Dlosilo en ${issue2.origin}`; case "invalid_union": return "Nevalida enigo"; case "invalid_element": return `Nevalida valoro en ${issue2.origin}`; default: return `Nevalida enigo`; } }; }; function eo_default() { return { localeError: error10() }; } // node_modules/zod/v4/locales/es.js var error11 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entrada", email: "direcci\xF3n de correo electr\xF3nico", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN", string: "texto", number: "n\xFAmero", boolean: "booleano", array: "arreglo", object: "objeto", set: "conjunto", file: "archivo", date: "fecha", bigint: "n\xFAmero grande", symbol: "s\xEDmbolo", undefined: "indefinido", null: "nulo", function: "funci\xF3n", map: "mapa", record: "registro", tuple: "tupla", enum: "enumeraci\xF3n", union: "uni\xF3n", literal: "literal", promise: "promesa", void: "vac\xEDo", never: "nunca", unknown: "desconocido", any: "cualquiera" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; } return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const origin = TypeDictionary[issue2.origin] ?? issue2.origin; if (sizing) { return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; if (_issue.format === "includes") return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; default: return `Entrada inv\xE1lida`; } }; }; function es_default() { return { localeError: error11() }; } // node_modules/zod/v4/locales/fa.js var error12 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0648\u0631\u0648\u062F\u06CC", email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", url: "URL", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" }; const TypeDictionary = { nan: "NaN", number: "\u0639\u062F\u062F", array: "\u0622\u0631\u0627\u06CC\u0647" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; } return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; } case "invalid_value": if (issue2.values.length === 1) { return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; } return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; } return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; } if (_issue.format === "ends_with") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; } if (_issue.format === "includes") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; } if (_issue.format === "regex") { return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; } return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } case "not_multiple_of": return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; case "unrecognized_keys": return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; case "invalid_union": return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; case "invalid_element": return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; default: return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; } }; }; function fa_default() { return { localeError: error12() }; } // node_modules/zod/v4/locales/fi.js var error13 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "s\xE4\xE4nn\xF6llinen lauseke", email: "s\xE4hk\xF6postiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; } return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); } return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); } return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; if (_issue.format === "includes") return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; if (_issue.format === "regex") { return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; } return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return "Virheellinen avain tietueessa"; case "invalid_union": return "Virheellinen unioni"; case "invalid_element": return "Virheellinen arvo joukossa"; default: return `Virheellinen sy\xF6te`; } }; }; function fi_default() { return { localeError: error13() }; } // node_modules/zod/v4/locales/fr.js var error14 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entr\xE9e", email: "adresse e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { nan: "NaN", number: "nombre", array: "tableau" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; } return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; } case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_default() { return { localeError: error14() }; } // node_modules/zod/v4/locales/fr-CA.js var error15 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "entr\xE9e", email: "adresse courriel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; } return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u2264" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u2265" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; if (_issue.format === "includes") return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; if (_issue.format === "regex") return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; } case "not_multiple_of": return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; case "unrecognized_keys": return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Cl\xE9 invalide dans ${issue2.origin}`; case "invalid_union": return "Entr\xE9e invalide"; case "invalid_element": return `Valeur invalide dans ${issue2.origin}`; default: return `Entr\xE9e invalide`; } }; }; function fr_CA_default() { return { localeError: error15() }; } // node_modules/zod/v4/locales/he.js var error16 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, bigint: { label: "BigInt", gender: "m" }, date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, promise: { label: "Promise", gender: "m" }, NaN: { label: "NaN", gender: "m" }, unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, value: { label: "\u05E2\u05E8\u05DA", gender: "m" } }; const Sizable = { string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } // no unit }; const typeEntry = (t) => t ? TypeNames[t] : void 0; const typeLabel = (t) => { const e = typeEntry(t); if (e) return e.label; return t ?? TypeNames.unknown.label; }; const withDefinite = (t) => `\u05D4${typeLabel(t)}`; const verbFor = (t) => { const e = typeEntry(t); const gender = e?.gender ?? "m"; return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; }; const getSizing = (origin) => { if (!origin) return null; return Sizable[origin] ?? null; }; const FormatDictionary = { regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, uuid: { label: "UUID", gender: "m" }, nanoid: { label: "nanoid", gender: "m" }, guid: { label: "GUID", gender: "m" }, cuid: { label: "cuid", gender: "m" }, cuid2: { label: "cuid2", gender: "m" }, ulid: { label: "ULID", gender: "m" }, xid: { label: "XID", gender: "m" }, ksuid: { label: "KSUID", gender: "m" }, datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, jwt: { label: "JWT", gender: "m" }, ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expectedKey = issue2.expected; const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; } return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; } case "invalid_value": { if (issue2.values.length === 1) { return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; } const stringified = issue2.values.map((v) => stringifyPrimitive(v)); if (issue2.values.length === 2) { return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; } const lastValue = stringified[stringified.length - 1]; const restValues = stringified.slice(0, -1).join(", "); return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; } case "too_big": { const sizing = getSizing(issue2.origin); const subject = withDefinite(issue2.origin ?? "value"); if (issue2.origin === "string") { return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); } if (issue2.origin === "number") { const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; } if (issue2.origin === "array" || issue2.origin === "set") { const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); } const adj = issue2.inclusive ? "<=" : "<"; const be = verbFor(issue2.origin ?? "value"); if (sizing?.unit) { return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; } return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const sizing = getSizing(issue2.origin); const subject = withDefinite(issue2.origin ?? "value"); if (issue2.origin === "string") { return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); } if (issue2.origin === "number") { const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; } if (issue2.origin === "array" || issue2.origin === "set") { const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; if (issue2.minimum === 1 && issue2.inclusive) { const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; } const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); } const adj = issue2.inclusive ? ">=" : ">"; const be = verbFor(issue2.origin ?? "value"); if (sizing?.unit) { return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; if (_issue.format === "regex") return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; const nounEntry = FormatDictionary[_issue.format]; const noun = nounEntry?.label ?? _issue.format; const gender = nounEntry?.gender ?? "m"; const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; return `${noun} \u05DC\u05D0 ${adjective}`; } case "not_multiple_of": return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; case "unrecognized_keys": return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": { return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; } case "invalid_union": return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; case "invalid_element": { const place = withDefinite(issue2.origin ?? "array"); return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; } default: return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; } }; }; function he_default() { return { localeError: error16() }; } // node_modules/zod/v4/locales/hu.js var error17 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "bemenet", email: "email c\xEDm", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO id\u0151b\xE9lyeg", date: "ISO d\xE1tum", time: "ISO id\u0151", duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", jwt: "JWT", template_literal: "bemenet" }; const TypeDictionary = { nan: "NaN", number: "sz\xE1m", array: "t\xF6mb" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; } return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; if (_issue.format === "ends_with") return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; if (_issue.format === "includes") return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; if (_issue.format === "regex") return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; case "unrecognized_keys": return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; case "invalid_union": return "\xC9rv\xE9nytelen bemenet"; case "invalid_element": return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; default: return `\xC9rv\xE9nytelen bemenet`; } }; }; function hu_default() { return { localeError: error17() }; } // node_modules/zod/v4/locales/hy.js function getArmenianPlural(count, one, many) { return Math.abs(count) === 1 ? one : many; } function withDefiniteArticle(word) { if (!word) return ""; const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; const lastChar = word[word.length - 1]; return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); } var error18 = () => { const Sizable = { string: { unit: { one: "\u0576\u0577\u0561\u0576", many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, file: { unit: { one: "\u0562\u0561\u0575\u0569", many: "\u0562\u0561\u0575\u0569\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, array: { unit: { one: "\u057F\u0561\u0580\u0580", many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" }, set: { unit: { one: "\u057F\u0561\u0580\u0580", many: "\u057F\u0561\u0580\u0580\u0565\u0580" }, verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0574\u0578\u0582\u057F\u0584", email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", url: "URL", emoji: "\u0567\u0574\u0578\u057B\u056B", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", time: "ISO \u056A\u0561\u0574", duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", json_string: "JSON \u057F\u0578\u0572", e164: "E.164 \u0570\u0561\u0574\u0561\u0580", jwt: "JWT", template_literal: "\u0574\u0578\u0582\u057F\u0584" }; const TypeDictionary = { nan: "NaN", number: "\u0569\u056B\u057E", array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; } return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; if (_issue.format === "ends_with") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; if (_issue.format === "includes") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; if (_issue.format === "regex") return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; case "unrecognized_keys": return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; case "invalid_union": return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; case "invalid_element": return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; default: return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; } }; }; function hy_default() { return { localeError: error18() }; } // node_modules/zod/v4/locales/id.js var error19 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "alamat email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; } return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak valid: harus menyertakan "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak valid: harus sesuai pola ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; } case "not_multiple_of": return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak valid di ${issue2.origin}`; case "invalid_union": return "Input tidak valid"; case "invalid_element": return `Nilai tidak valid di ${issue2.origin}`; default: return `Input tidak valid`; } }; }; function id_default() { return { localeError: error19() }; } // node_modules/zod/v4/locales/is.js var error20 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, array: { unit: "hluti", verb: "a\xF0 hafa" }, set: { unit: "hluti", verb: "a\xF0 hafa" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "gildi", email: "netfang", url: "vefsl\xF3\xF0", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dagsetning og t\xEDmi", date: "ISO dagsetning", time: "ISO t\xEDmi", duration: "ISO t\xEDmalengd", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded strengur", base64url: "base64url-encoded strengur", json_string: "JSON strengur", e164: "E.164 t\xF6lugildi", jwt: "JWT", template_literal: "gildi" }; const TypeDictionary = { nan: "NaN", number: "n\xFAmer", array: "fylki" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; } return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; } case "invalid_value": if (issue2.values.length === 1) return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; if (_issue.format === "includes") return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; if (_issue.format === "regex") return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; case "unrecognized_keys": return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Rangur lykill \xED ${issue2.origin}`; case "invalid_union": return "Rangt gildi"; case "invalid_element": return `Rangt gildi \xED ${issue2.origin}`; default: return `Rangt gildi`; } }; }; function is_default() { return { localeError: error20() }; } // node_modules/zod/v4/locales/it.js var error21 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "indirizzo email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "numero", array: "vettore" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; } return `Input non valido: atteso ${expected}, ricevuto ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Stringa non valida: deve terminare con "${_issue.suffix}"`; if (_issue.format === "includes") return `Stringa non valida: deve includere "${_issue.includes}"`; if (_issue.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; case "unrecognized_keys": return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chiave non valida in ${issue2.origin}`; case "invalid_union": return "Input non valido"; case "invalid_element": return `Valore non valido in ${issue2.origin}`; default: return `Input non valido`; } }; }; function it_default() { return { localeError: error21() }; } // node_modules/zod/v4/locales/ja.js var error22 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u5165\u529B\u5024", email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", url: "URL", emoji: "\u7D75\u6587\u5B57", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u6642", date: "ISO\u65E5\u4ED8", time: "ISO\u6642\u523B", duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", jwt: "JWT", template_literal: "\u5165\u529B\u5024" }; const TypeDictionary = { nan: "NaN", number: "\u6570\u5024", array: "\u914D\u5217" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; } return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; } case "invalid_value": if (issue2.values.length === 1) return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "too_big": { const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "too_small": { const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; const sizing = getSizing(issue2.origin); if (sizing) return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "ends_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "includes") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; if (_issue.format === "regex") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; case "unrecognized_keys": return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; case "invalid_union": return "\u7121\u52B9\u306A\u5165\u529B"; case "invalid_element": return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; default: return `\u7121\u52B9\u306A\u5165\u529B`; } }; }; function ja_default() { return { localeError: error22() }; } // node_modules/zod/v4/locales/ka.js var error23 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", url: "URL", emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", time: "\u10D3\u10E0\u10DD", duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", jwt: "JWT", template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" }; const TypeDictionary = { nan: "NaN", number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; } return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; } if (_issue.format === "ends_with") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; if (_issue.format === "includes") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; if (_issue.format === "regex") return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; case "unrecognized_keys": return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; case "invalid_union": return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; case "invalid_element": return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; default: return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; } }; }; function ka_default() { return { localeError: error23() }; } // node_modules/zod/v4/locales/km.js var error24 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", url: "URL", emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", time: "\u1798\u17C9\u17C4\u1784 ISO", duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" }; const TypeDictionary = { nan: "NaN", number: "\u179B\u17C1\u1781", array: "\u17A2\u17B6\u179A\u17C1 (Array)", null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; } return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; if (_issue.format === "regex") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; case "unrecognized_keys": return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; case "invalid_union": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; case "invalid_element": return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; default: return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; } }; }; function km_default() { return { localeError: error24() }; } // node_modules/zod/v4/locales/kh.js function kh_default() { return km_default(); } // node_modules/zod/v4/locales/ko.js var error25 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, set: { unit: "\uAC1C", verb: "to have" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\uC785\uB825", email: "\uC774\uBA54\uC77C \uC8FC\uC18C", url: "URL", emoji: "\uC774\uBAA8\uC9C0", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", date: "ISO \uB0A0\uC9DC", time: "ISO \uC2DC\uAC04", duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", jwt: "JWT", template_literal: "\uC785\uB825" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; } return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; } case "invalid_value": if (issue2.values.length === 1) return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "too_big": { const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; } case "too_small": { const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; const sizing = getSizing(issue2.origin); const unit = sizing?.unit ?? "\uC694\uC18C"; if (sizing) { return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; } return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; } if (_issue.format === "ends_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "includes") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; if (_issue.format === "regex") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; case "unrecognized_keys": return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; case "invalid_union": return `\uC798\uBABB\uB41C \uC785\uB825`; case "invalid_element": return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; default: return `\uC798\uBABB\uB41C \uC785\uB825`; } }; }; function ko_default() { return { localeError: error25() }; } // node_modules/zod/v4/locales/lt.js var capitalizeFirstCharacter = (text) => { return text.charAt(0).toUpperCase() + text.slice(1); }; function getUnitTypeFromNumber(number4) { const abs = Math.abs(number4); const last = abs % 10; const last2 = abs % 100; if (last2 >= 11 && last2 <= 19 || last === 0) return "many"; if (last === 1) return "one"; return "few"; } var error26 = () => { const Sizable = { string: { unit: { one: "simbolis", few: "simboliai", many: "simboli\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" }, bigger: { inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" } } }, file: { unit: { one: "baitas", few: "baitai", many: "bait\u0173" }, verb: { smaller: { inclusive: "turi b\u016Bti ne didesnis kaip", notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" }, bigger: { inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", notInclusive: "turi b\u016Bti didesnis kaip" } } }, array: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } }, set: { unit: { one: "element\u0105", few: "elementus", many: "element\u0173" }, verb: { smaller: { inclusive: "turi tur\u0117ti ne daugiau kaip", notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" }, bigger: { inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", notInclusive: "turi tur\u0117ti daugiau kaip" } } } }; function getSizing(origin, unitType, inclusive, targetShouldBe) { const result = Sizable[origin] ?? null; if (result === null) return result; return { unit: result.unit[unitType], verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] }; } const FormatDictionary = { regex: "\u012Fvestis", email: "el. pa\u0161to adresas", url: "URL", emoji: "jaustukas", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO data ir laikas", date: "ISO data", time: "ISO laikas", duration: "ISO trukm\u0117", ipv4: "IPv4 adresas", ipv6: "IPv6 adresas", cidrv4: "IPv4 tinklo prefiksas (CIDR)", cidrv6: "IPv6 tinklo prefiksas (CIDR)", base64: "base64 u\u017Ekoduota eilut\u0117", base64url: "base64url u\u017Ekoduota eilut\u0117", json_string: "JSON eilut\u0117", e164: "E.164 numeris", jwt: "JWT", template_literal: "\u012Fvestis" }; const TypeDictionary = { nan: "NaN", number: "skai\u010Dius", bigint: "sveikasis skai\u010Dius", string: "eilut\u0117", boolean: "login\u0117 reik\u0161m\u0117", undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", function: "funkcija", symbol: "simbolis", array: "masyvas", object: "objektas", null: "nulin\u0117 reik\u0161m\u0117" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; } return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; } case "invalid_value": if (issue2.values.length === 1) return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; case "too_big": { const origin = TypeDictionary[issue2.origin] ?? issue2.origin; const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); if (sizing?.verb) return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; } case "too_small": { const origin = TypeDictionary[issue2.origin] ?? issue2.origin; const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); if (sizing?.verb) return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; if (_issue.format === "includes") return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; if (_issue.format === "regex") return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; case "unrecognized_keys": return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return "Rastas klaidingas raktas"; case "invalid_union": return "Klaidinga \u012Fvestis"; case "invalid_element": { const origin = TypeDictionary[issue2.origin] ?? issue2.origin; return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; } default: return "Klaidinga \u012Fvestis"; } }; }; function lt_default() { return { localeError: error26() }; } // node_modules/zod/v4/locales/mk.js var error27 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u043D\u0435\u0441", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", url: "URL", emoji: "\u0435\u043C\u043E\u045F\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0443\u043C", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" }; const TypeDictionary = { nan: "NaN", number: "\u0431\u0440\u043E\u0458", array: "\u043D\u0438\u0437\u0430" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; } return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; case "invalid_union": return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; case "invalid_element": return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; default: return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; } }; }; function mk_default() { return { localeError: error27() }; } // node_modules/zod/v4/locales/ms.js var error28 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "alamat e-mel", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "nombor" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; } return `Input tidak sah: dijangka ${expected}, diterima ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; if (_issue.format === "ends_with") return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; if (_issue.format === "includes") return `String tidak sah: mesti mengandungi "${_issue.includes}"`; if (_issue.format === "regex") return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; } case "not_multiple_of": return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; case "unrecognized_keys": return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kunci tidak sah dalam ${issue2.origin}`; case "invalid_union": return "Input tidak sah"; case "invalid_element": return `Nilai tidak sah dalam ${issue2.origin}`; default: return `Input tidak sah`; } }; }; function ms_default() { return { localeError: error28() }; } // node_modules/zod/v4/locales/nl.js var error29 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, array: { unit: "elementen", verb: "heeft" }, set: { unit: "elementen", verb: "heeft" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "invoer", email: "emailadres", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" }; const TypeDictionary = { nan: "NaN", number: "getal" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; } return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; if (sizing) return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; if (sizing) { return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; } return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; } if (_issue.format === "ends_with") return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; if (_issue.format === "includes") return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; if (_issue.format === "regex") return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; case "unrecognized_keys": return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ongeldige key in ${issue2.origin}`; case "invalid_union": return "Ongeldige invoer"; case "invalid_element": return `Ongeldige waarde in ${issue2.origin}`; default: return `Ongeldige invoer`; } }; }; function nl_default() { return { localeError: error29() }; } // node_modules/zod/v4/locales/no.js var error30 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, set: { unit: "elementer", verb: "\xE5 inneholde" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "input", email: "e-postadresse", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "tall", array: "liste" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; } return `Ugyldig input: forventet ${expected}, fikk ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; if (_issue.format === "regex") return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ugyldig n\xF8kkel i ${issue2.origin}`; case "invalid_union": return "Ugyldig input"; case "invalid_element": return `Ugyldig verdi i ${issue2.origin}`; default: return `Ugyldig input`; } }; }; function no_default() { return { localeError: error30() }; } // node_modules/zod/v4/locales/ota.js var error31 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "giren", email: "epostag\xE2h", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO heng\xE2m\u0131", date: "ISO tarihi", time: "ISO zaman\u0131", duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "giren" }; const TypeDictionary = { nan: "NaN", number: "numara", array: "saf", null: "gayb" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; } return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; } return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; if (_issue.format === "ends_with") return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; if (_issue.format === "includes") return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; if (_issue.format === "regex") return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; case "invalid_union": return "Giren tan\u0131namad\u0131."; case "invalid_element": return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; default: return `K\u0131ymet tan\u0131namad\u0131.`; } }; }; function ota_default() { return { localeError: error31() }; } // node_modules/zod/v4/locales/ps.js var error32 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0648\u0631\u0648\u062F\u064A", email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", date: "\u0646\u06D0\u067C\u0647", time: "\u0648\u062E\u062A", duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" }; const TypeDictionary = { nan: "NaN", number: "\u0639\u062F\u062F", array: "\u0627\u0631\u06D0" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; } return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; } case "invalid_value": if (issue2.values.length === 1) { return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; } return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; } return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; } if (_issue.format === "ends_with") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; } if (_issue.format === "includes") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; } if (_issue.format === "regex") { return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; } return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; } case "not_multiple_of": return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; case "unrecognized_keys": return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; case "invalid_union": return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; case "invalid_element": return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; default: return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; } }; }; function ps_default() { return { localeError: error32() }; } // node_modules/zod/v4/locales/pl.js var error33 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, set: { unit: "element\xF3w", verb: "mie\u0107" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "wyra\u017Cenie", email: "adres email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wej\u015Bcie" }; const TypeDictionary = { nan: "NaN", number: "liczba", array: "tablica" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; } return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; } return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; if (_issue.format === "includes") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; if (_issue.format === "regex") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; case "unrecognized_keys": return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Nieprawid\u0142owy klucz w ${issue2.origin}`; case "invalid_union": return "Nieprawid\u0142owe dane wej\u015Bciowe"; case "invalid_element": return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; default: return `Nieprawid\u0142owe dane wej\u015Bciowe`; } }; }; function pl_default() { return { localeError: error33() }; } // node_modules/zod/v4/locales/pt.js var error34 = () => { const Sizable = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "padr\xE3o", email: "endere\xE7o de e-mail", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "dura\xE7\xE3o ISO", ipv4: "endere\xE7o IPv4", ipv6: "endere\xE7o IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" }; const TypeDictionary = { nan: "NaN", number: "n\xFAmero", null: "nulo" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; } return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; if (_issue.format === "includes") return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; if (_issue.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; } case "not_multiple_of": return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; case "unrecognized_keys": return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Chave inv\xE1lida em ${issue2.origin}`; case "invalid_union": return "Entrada inv\xE1lida"; case "invalid_element": return `Valor inv\xE1lido em ${issue2.origin}`; default: return `Campo inv\xE1lido`; } }; }; function pt_default() { return { localeError: error34() }; } // node_modules/zod/v4/locales/ru.js function getRussianPlural(count, one, few, many) { const absCount = Math.abs(count); const lastDigit = absCount % 10; const lastTwoDigits = absCount % 100; if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { return many; } if (lastDigit === 1) { return one; } if (lastDigit >= 2 && lastDigit <= 4) { return few; } return many; } var error35 = () => { const Sizable = { string: { unit: { one: "\u0441\u0438\u043C\u0432\u043E\u043B", few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u0430", many: "\u0431\u0430\u0439\u0442" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u044F", duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0441\u0438\u0432" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; } return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { const maxValue = Number(issue2.maximum); const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { const minValue = Number(issue2.minimum); const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; } return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; case "invalid_element": return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; default: return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; } }; }; function ru_default() { return { localeError: error35() }; } // node_modules/zod/v4/locales/sl.js var error36 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "vnos", email: "e-po\u0161tni naslov", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datum in \u010Das", date: "ISO datum", time: "ISO \u010Das", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", jwt: "JWT", template_literal: "vnos" }; const TypeDictionary = { nan: "NaN", number: "\u0161tevilo", array: "tabela" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; } return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; if (_issue.format === "includes") return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; if (_issue.format === "regex") return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; case "unrecognized_keys": return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Neveljaven klju\u010D v ${issue2.origin}`; case "invalid_union": return "Neveljaven vnos"; case "invalid_element": return `Neveljavna vrednost v ${issue2.origin}`; default: return "Neveljaven vnos"; } }; }; function sl_default() { return { localeError: error36() }; } // node_modules/zod/v4/locales/sv.js var error37 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, set: { unit: "objekt", verb: "att inneh\xE5lla" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "regulj\xE4rt uttryck", email: "e-postadress", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" }; const TypeDictionary = { nan: "NaN", number: "antal", array: "lista" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; } return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; } return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; if (_issue.format === "includes") return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; if (_issue.format === "regex") return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; case "unrecognized_keys": return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; case "invalid_union": return "Ogiltig input"; case "invalid_element": return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; default: return `Ogiltig input`; } }; }; function sv_default() { return { localeError: error37() }; } // node_modules/zod/v4/locales/ta.js var error38 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", jwt: "JWT", template_literal: "input" }; const TypeDictionary = { nan: "NaN", number: "\u0B8E\u0BA3\u0BCD", array: "\u0B85\u0BA3\u0BBF", null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; } return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "ends_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "includes") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; if (_issue.format === "regex") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; case "unrecognized_keys": return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; case "invalid_union": return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; case "invalid_element": return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; default: return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; } }; }; function ta_default() { return { localeError: error38() }; } // node_modules/zod/v4/locales/th.js var error39 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", url: "URL", emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" }; const TypeDictionary = { nan: "NaN", number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; } return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; } if (_issue.format === "ends_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; if (_issue.format === "regex") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; case "unrecognized_keys": return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; case "invalid_union": return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; case "invalid_element": return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; default: return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; } }; }; function th_default() { return { localeError: error39() }; } // node_modules/zod/v4/locales/tr.js var error40 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "girdi", email: "e-posta adresi", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "\u015Eablon dizesi" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; } return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; if (_issue.format === "ends_with") return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; if (_issue.format === "includes") return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; if (_issue.format === "regex") return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; case "unrecognized_keys": return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; case "invalid_union": return "Ge\xE7ersiz de\u011Fer"; case "invalid_element": return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; default: return `Ge\xE7ersiz de\u011Fer`; } }; }; function tr_default() { return { localeError: error40() }; } // node_modules/zod/v4/locales/uk.js var error41 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", date: "\u0434\u0430\u0442\u0430 ISO", time: "\u0447\u0430\u0441 ISO", duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" }; const TypeDictionary = { nan: "NaN", number: "\u0447\u0438\u0441\u043B\u043E", array: "\u043C\u0430\u0441\u0438\u0432" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; } return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; if (_issue.format === "includes") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; if (_issue.format === "regex") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; case "unrecognized_keys": return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; case "invalid_union": return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; case "invalid_element": return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; default: return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; } }; }; function uk_default() { return { localeError: error41() }; } // node_modules/zod/v4/locales/ua.js function ua_default() { return uk_default(); } // node_modules/zod/v4/locales/ur.js var error42 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0627\u0646 \u067E\u0679", email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" }; const TypeDictionary = { nan: "NaN", number: "\u0646\u0645\u0628\u0631", array: "\u0622\u0631\u06D2", null: "\u0646\u0644" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; } return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; } case "invalid_value": if (issue2.values.length === 1) return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; } return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; } if (_issue.format === "ends_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "includes") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; if (_issue.format === "regex") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; case "unrecognized_keys": return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; case "invalid_key": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; case "invalid_union": return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; case "invalid_element": return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; default: return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; } }; }; function ur_default() { return { localeError: error42() }; } // node_modules/zod/v4/locales/uz.js var error43 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, array: { unit: "element", verb: "bo\u2018lishi kerak" }, set: { unit: "element", verb: "bo\u2018lishi kerak" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "kirish", email: "elektron pochta manzili", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO sana va vaqti", date: "ISO sana", time: "ISO vaqt", duration: "ISO davomiylik", ipv4: "IPv4 manzil", ipv6: "IPv6 manzil", mac: "MAC manzil", cidrv4: "IPv4 diapazon", cidrv6: "IPv6 diapazon", base64: "base64 kodlangan satr", base64url: "base64url kodlangan satr", json_string: "JSON satr", e164: "E.164 raqam", jwt: "JWT", template_literal: "kirish" }; const TypeDictionary = { nan: "NaN", number: "raqam", array: "massiv" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; } return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; } return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; if (_issue.format === "ends_with") return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; if (_issue.format === "includes") return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; if (_issue.format === "regex") return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; case "unrecognized_keys": return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; case "invalid_union": return "Noto\u2018g\u2018ri kirish"; case "invalid_element": return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; default: return `Noto\u2018g\u2018ri kirish`; } }; }; function uz_default() { return { localeError: error43() }; } // node_modules/zod/v4/locales/vi.js var error44 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u0111\u1EA7u v\xE0o", email: "\u0111\u1ECBa ch\u1EC9 email", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ng\xE0y gi\u1EDD ISO", date: "ng\xE0y ISO", time: "gi\u1EDD ISO", duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" }; const TypeDictionary = { nan: "NaN", number: "s\u1ED1", array: "m\u1EA3ng" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; } return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; if (_issue.format === "ends_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; if (_issue.format === "includes") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; if (_issue.format === "regex") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; } case "not_multiple_of": return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; case "unrecognized_keys": return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; case "invalid_union": return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; case "invalid_element": return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; default: return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; } }; }; function vi_default() { return { localeError: error44() }; } // node_modules/zod/v4/locales/zh-CN.js var error45 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, set: { unit: "\u9879", verb: "\u5305\u542B" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u8F93\u5165", email: "\u7535\u5B50\u90AE\u4EF6", url: "URL", emoji: "\u8868\u60C5\u7B26\u53F7", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u671F\u65F6\u95F4", date: "ISO\u65E5\u671F", time: "ISO\u65F6\u95F4", duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", jwt: "JWT", template_literal: "\u8F93\u5165" }; const TypeDictionary = { nan: "NaN", number: "\u6570\u5B57", array: "\u6570\u7EC4", null: "\u7A7A\u503C(null)" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; } return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; if (_issue.format === "ends_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; if (_issue.format === "includes") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; case "unrecognized_keys": return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; case "invalid_union": return "\u65E0\u6548\u8F93\u5165"; case "invalid_element": return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; default: return `\u65E0\u6548\u8F93\u5165`; } }; }; function zh_CN_default() { return { localeError: error45() }; } // node_modules/zod/v4/locales/zh-TW.js var error46 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u8F38\u5165", email: "\u90F5\u4EF6\u5730\u5740", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u65E5\u671F\u6642\u9593", date: "ISO \u65E5\u671F", time: "ISO \u6642\u9593", duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", jwt: "JWT", template_literal: "\u8F38\u5165" }; const TypeDictionary = { nan: "NaN" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; } return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) { return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") { return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; } if (_issue.format === "ends_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; if (_issue.format === "includes") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; if (_issue.format === "regex") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; case "unrecognized_keys": return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; case "invalid_key": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; case "invalid_union": return "\u7121\u6548\u7684\u8F38\u5165\u503C"; case "invalid_element": return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; default: return `\u7121\u6548\u7684\u8F38\u5165\u503C`; } }; }; function zh_TW_default() { return { localeError: error46() }; } // node_modules/zod/v4/locales/yo.js var error47 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, array: { unit: "nkan", verb: "n\xED" }, set: { unit: "nkan", verb: "n\xED" } }; function getSizing(origin) { return Sizable[origin] ?? null; } const FormatDictionary = { regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\xE0k\xF3k\xF2 ISO", date: "\u1ECDj\u1ECD\u0301 ISO", time: "\xE0k\xF3k\xF2 ISO", duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", cidrv4: "\xE0gb\xE8gb\xE8 IPv4", cidrv6: "\xE0gb\xE8gb\xE8 IPv6", base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", e164: "n\u1ECD\u0301mb\xE0 E.164", jwt: "JWT", template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" }; const TypeDictionary = { nan: "NaN", number: "n\u1ECD\u0301mb\xE0", array: "akop\u1ECD" }; return (issue2) => { switch (issue2.code) { case "invalid_type": { const expected = TypeDictionary[issue2.expected] ?? issue2.expected; const receivedType = parsedType(issue2.input); const received = TypeDictionary[receivedType] ?? receivedType; if (/^[A-Z]/.test(issue2.expected)) { return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; } return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; } case "invalid_value": if (issue2.values.length === 1) return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; case "too_big": { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; const sizing = getSizing(issue2.origin); if (sizing) return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; } case "invalid_format": { const _issue = issue2; if (_issue.format === "starts_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; if (_issue.format === "ends_with") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; if (_issue.format === "includes") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; if (_issue.format === "regex") return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; } case "not_multiple_of": return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; case "unrecognized_keys": return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; case "invalid_key": return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; case "invalid_union": return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; case "invalid_element": return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; default: return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; } }; }; function yo_default() { return { localeError: error47() }; } // node_modules/zod/v4/core/registries.js var _a; var $output = Symbol("ZodOutput"); var $input = Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); } add(schema, ..._meta) { const meta3 = _meta[0]; this._map.set(schema, meta3); if (meta3 && typeof meta3 === "object" && "id" in meta3) { this._idmap.set(meta3.id, schema); } return this; } clear() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); return this; } remove(schema) { const meta3 = this._map.get(schema); if (meta3 && typeof meta3 === "object" && "id" in meta3) { this._idmap.delete(meta3.id); } this._map.delete(schema); return this; } get(schema) { const p = schema._zod.parent; if (p) { const pm = { ...this.get(p) ?? {} }; delete pm.id; const f = { ...pm, ...this._map.get(schema) }; return Object.keys(f).length ? f : void 0; } return this._map.get(schema); } has(schema) { return this._map.has(schema); } }; function registry() { return new $ZodRegistry(); } (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); var globalRegistry = globalThis.__zod_globalRegistry; // node_modules/zod/v4/core/api.js // @__NO_SIDE_EFFECTS__ function _string(Class2, params) { return new Class2({ type: "string", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedString(Class2, params) { return new Class2({ type: "string", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _email(Class2, params) { return new Class2({ type: "string", format: "email", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _guid(Class2, params) { return new Class2({ type: "string", format: "guid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuid(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv4(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv6(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uuidv7(Class2, params) { return new Class2({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _url(Class2, params) { return new Class2({ type: "string", format: "url", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _emoji2(Class2, params) { return new Class2({ type: "string", format: "emoji", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nanoid(Class2, params) { return new Class2({ type: "string", format: "nanoid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cuid(Class2, params) { return new Class2({ type: "string", format: "cuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cuid2(Class2, params) { return new Class2({ type: "string", format: "cuid2", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ulid(Class2, params) { return new Class2({ type: "string", format: "ulid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _xid(Class2, params) { return new Class2({ type: "string", format: "xid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ksuid(Class2, params) { return new Class2({ type: "string", format: "ksuid", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ipv4(Class2, params) { return new Class2({ type: "string", format: "ipv4", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _ipv6(Class2, params) { return new Class2({ type: "string", format: "ipv6", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _mac(Class2, params) { return new Class2({ type: "string", format: "mac", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cidrv4(Class2, params) { return new Class2({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _cidrv6(Class2, params) { return new Class2({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _base64(Class2, params) { return new Class2({ type: "string", format: "base64", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _base64url(Class2, params) { return new Class2({ type: "string", format: "base64url", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _e164(Class2, params) { return new Class2({ type: "string", format: "e164", check: "string_format", abort: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", format: "jwt", check: "string_format", abort: false, ...normalizeParams(params) }); } var TimePrecision = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 }; // @__NO_SIDE_EFFECTS__ function _isoDateTime(Class2, params) { return new Class2({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoDate(Class2, params) { return new Class2({ type: "string", format: "date", check: "string_format", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoTime(Class2, params) { return new Class2({ type: "string", format: "time", check: "string_format", precision: null, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _isoDuration(Class2, params) { return new Class2({ type: "string", format: "duration", check: "string_format", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _number(Class2, params) { return new Class2({ type: "number", checks: [], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedNumber(Class2, params) { return new Class2({ type: "number", coerce: true, checks: [], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "safeint", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _float32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "float32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _float64(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "float64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "int32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uint32(Class2, params) { return new Class2({ type: "number", check: "number_format", abort: false, format: "uint32", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _boolean(Class2, params) { return new Class2({ type: "boolean", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedBoolean(Class2, params) { return new Class2({ type: "boolean", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _bigint(Class2, params) { return new Class2({ type: "bigint", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedBigint(Class2, params) { return new Class2({ type: "bigint", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _int64(Class2, params) { return new Class2({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uint64(Class2, params) { return new Class2({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _symbol(Class2, params) { return new Class2({ type: "symbol", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _undefined2(Class2, params) { return new Class2({ type: "undefined", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _null2(Class2, params) { return new Class2({ type: "null", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _any(Class2) { return new Class2({ type: "any" }); } // @__NO_SIDE_EFFECTS__ function _unknown(Class2) { return new Class2({ type: "unknown" }); } // @__NO_SIDE_EFFECTS__ function _never(Class2, params) { return new Class2({ type: "never", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _void(Class2, params) { return new Class2({ type: "void", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _date(Class2, params) { return new Class2({ type: "date", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _coercedDate(Class2, params) { return new Class2({ type: "date", coerce: true, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nan(Class2, params) { return new Class2({ type: "nan", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _lt(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: false }); } // @__NO_SIDE_EFFECTS__ function _lte(value, params) { return new $ZodCheckLessThan({ check: "less_than", ...normalizeParams(params), value, inclusive: true }); } // @__NO_SIDE_EFFECTS__ function _gt(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: false }); } // @__NO_SIDE_EFFECTS__ function _gte(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: true }); } // @__NO_SIDE_EFFECTS__ function _positive(params) { return /* @__PURE__ */ _gt(0, params); } // @__NO_SIDE_EFFECTS__ function _negative(params) { return /* @__PURE__ */ _lt(0, params); } // @__NO_SIDE_EFFECTS__ function _nonpositive(params) { return /* @__PURE__ */ _lte(0, params); } // @__NO_SIDE_EFFECTS__ function _nonnegative(params) { return /* @__PURE__ */ _gte(0, params); } // @__NO_SIDE_EFFECTS__ function _multipleOf(value, params) { return new $ZodCheckMultipleOf({ check: "multiple_of", ...normalizeParams(params), value }); } // @__NO_SIDE_EFFECTS__ function _maxSize(maximum, params) { return new $ZodCheckMaxSize({ check: "max_size", ...normalizeParams(params), maximum }); } // @__NO_SIDE_EFFECTS__ function _minSize(minimum, params) { return new $ZodCheckMinSize({ check: "min_size", ...normalizeParams(params), minimum }); } // @__NO_SIDE_EFFECTS__ function _size(size, params) { return new $ZodCheckSizeEquals({ check: "size_equals", ...normalizeParams(params), size }); } // @__NO_SIDE_EFFECTS__ function _maxLength(maximum, params) { const ch = new $ZodCheckMaxLength({ check: "max_length", ...normalizeParams(params), maximum }); return ch; } // @__NO_SIDE_EFFECTS__ function _minLength(minimum, params) { return new $ZodCheckMinLength({ check: "min_length", ...normalizeParams(params), minimum }); } // @__NO_SIDE_EFFECTS__ function _length(length, params) { return new $ZodCheckLengthEquals({ check: "length_equals", ...normalizeParams(params), length }); } // @__NO_SIDE_EFFECTS__ function _regex(pattern, params) { return new $ZodCheckRegex({ check: "string_format", format: "regex", ...normalizeParams(params), pattern }); } // @__NO_SIDE_EFFECTS__ function _lowercase(params) { return new $ZodCheckLowerCase({ check: "string_format", format: "lowercase", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _uppercase(params) { return new $ZodCheckUpperCase({ check: "string_format", format: "uppercase", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _includes(includes, params) { return new $ZodCheckIncludes({ check: "string_format", format: "includes", ...normalizeParams(params), includes }); } // @__NO_SIDE_EFFECTS__ function _startsWith(prefix, params) { return new $ZodCheckStartsWith({ check: "string_format", format: "starts_with", ...normalizeParams(params), prefix }); } // @__NO_SIDE_EFFECTS__ function _endsWith(suffix, params) { return new $ZodCheckEndsWith({ check: "string_format", format: "ends_with", ...normalizeParams(params), suffix }); } // @__NO_SIDE_EFFECTS__ function _property(property, schema, params) { return new $ZodCheckProperty({ check: "property", property, schema, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _mime(types, params) { return new $ZodCheckMimeType({ check: "mime_type", mime: types, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _overwrite(tx) { return new $ZodCheckOverwrite({ check: "overwrite", tx }); } // @__NO_SIDE_EFFECTS__ function _normalize(form) { return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); } // @__NO_SIDE_EFFECTS__ function _trim() { return /* @__PURE__ */ _overwrite((input) => input.trim()); } // @__NO_SIDE_EFFECTS__ function _toLowerCase() { return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); } // @__NO_SIDE_EFFECTS__ function _toUpperCase() { return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); } // @__NO_SIDE_EFFECTS__ function _slugify() { return /* @__PURE__ */ _overwrite((input) => slugify(input)); } // @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { return new Class2({ type: "array", element, // get element() { // return element; // }, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _union(Class2, options, params) { return new Class2({ type: "union", options, ...normalizeParams(params) }); } function _xor(Class2, options, params) { return new Class2({ type: "union", options, inclusive: false, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _discriminatedUnion(Class2, discriminator, options, params) { return new Class2({ type: "union", options, discriminator, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _intersection(Class2, left, right) { return new Class2({ type: "intersection", left, right }); } // @__NO_SIDE_EFFECTS__ function _tuple(Class2, items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new Class2({ type: "tuple", items, rest, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _record(Class2, keyType, valueType, params) { return new Class2({ type: "record", keyType, valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _map(Class2, keyType, valueType, params) { return new Class2({ type: "map", keyType, valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _set(Class2, valueType, params) { return new Class2({ type: "set", valueType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _enum(Class2, values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new Class2({ type: "enum", entries, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _nativeEnum(Class2, entries, params) { return new Class2({ type: "enum", entries, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _literal(Class2, value, params) { return new Class2({ type: "literal", values: Array.isArray(value) ? value : [value], ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _file(Class2, params) { return new Class2({ type: "file", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _transform(Class2, fn) { return new Class2({ type: "transform", transform: fn }); } // @__NO_SIDE_EFFECTS__ function _optional(Class2, innerType) { return new Class2({ type: "optional", innerType }); } // @__NO_SIDE_EFFECTS__ function _nullable(Class2, innerType) { return new Class2({ type: "nullable", innerType }); } // @__NO_SIDE_EFFECTS__ function _default(Class2, innerType, defaultValue) { return new Class2({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); } }); } // @__NO_SIDE_EFFECTS__ function _nonoptional(Class2, innerType, params) { return new Class2({ type: "nonoptional", innerType, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _success(Class2, innerType) { return new Class2({ type: "success", innerType }); } // @__NO_SIDE_EFFECTS__ function _catch(Class2, innerType, catchValue) { return new Class2({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } // @__NO_SIDE_EFFECTS__ function _pipe(Class2, in_, out) { return new Class2({ type: "pipe", in: in_, out }); } // @__NO_SIDE_EFFECTS__ function _readonly(Class2, innerType) { return new Class2({ type: "readonly", innerType }); } // @__NO_SIDE_EFFECTS__ function _templateLiteral(Class2, parts, params) { return new Class2({ type: "template_literal", parts, ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _lazy(Class2, getter) { return new Class2({ type: "lazy", getter }); } // @__NO_SIDE_EFFECTS__ function _promise(Class2, innerType) { return new Class2({ type: "promise", innerType }); } // @__NO_SIDE_EFFECTS__ function _custom(Class2, fn, _params) { const norm = normalizeParams(_params); norm.abort ?? (norm.abort = true); const schema = new Class2({ type: "custom", check: "custom", fn, ...norm }); return schema; } // @__NO_SIDE_EFFECTS__ function _refine(Class2, fn, _params) { const schema = new Class2({ type: "custom", check: "custom", fn, ...normalizeParams(_params) }); return schema; } // @__NO_SIDE_EFFECTS__ function _superRefine(fn) { const ch = /* @__PURE__ */ _check((payload) => { payload.addIssue = (issue2) => { if (typeof issue2 === "string") { payload.issues.push(issue(issue2, payload.value, ch._zod.def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = ch); _issue.continue ?? (_issue.continue = !ch._zod.def.abort); payload.issues.push(issue(_issue)); } }; return fn(payload.value, payload); }); return ch; } // @__NO_SIDE_EFFECTS__ function _check(fn, params) { const ch = new $ZodCheck({ check: "custom", ...normalizeParams(params) }); ch._zod.check = fn; return ch; } // @__NO_SIDE_EFFECTS__ function describe(description) { const ch = new $ZodCheck({ check: "describe" }); ch._zod.onattach = [ (inst) => { const existing = globalRegistry.get(inst) ?? {}; globalRegistry.add(inst, { ...existing, description }); } ]; ch._zod.check = () => { }; return ch; } // @__NO_SIDE_EFFECTS__ function meta(metadata) { const ch = new $ZodCheck({ check: "meta" }); ch._zod.onattach = [ (inst) => { const existing = globalRegistry.get(inst) ?? {}; globalRegistry.add(inst, { ...existing, ...metadata }); } ]; ch._zod.check = () => { }; return ch; } // @__NO_SIDE_EFFECTS__ function _stringbool(Classes, _params) { const params = normalizeParams(_params); let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; if (params.case !== "sensitive") { truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); } const truthySet = new Set(truthyArray); const falsySet = new Set(falsyArray); const _Codec = Classes.Codec ?? $ZodCodec; const _Boolean = Classes.Boolean ?? $ZodBoolean; const _String = Classes.String ?? $ZodString; const stringSchema = new _String({ type: "string", error: params.error }); const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); const codec2 = new _Codec({ type: "pipe", in: stringSchema, out: booleanSchema, transform: ((input, payload) => { let data = input; if (params.case !== "sensitive") data = data.toLowerCase(); if (truthySet.has(data)) { return true; } else if (falsySet.has(data)) { return false; } else { payload.issues.push({ code: "invalid_value", expected: "stringbool", values: [...truthySet, ...falsySet], input: payload.value, inst: codec2, continue: false }); return {}; } }), reverseTransform: ((input, _payload) => { if (input === true) { return truthyArray[0] || "true"; } else { return falsyArray[0] || "false"; } }), error: params.error }); return codec2; } // @__NO_SIDE_EFFECTS__ function _stringFormat(Class2, format, fnOrRegex, _params = {}) { const params = normalizeParams(_params); const def = { ...normalizeParams(_params), check: "string_format", type: "string", format, fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), ...params }; if (fnOrRegex instanceof RegExp) { def.pattern = fnOrRegex; } const inst = new Class2(def); return inst; } // node_modules/zod/v4/core/to-json-schema.js function initializeContext(params) { let target = params?.target ?? "draft-2020-12"; if (target === "draft-4") target = "draft-04"; if (target === "draft-7") target = "draft-07"; return { processors: params.processors ?? {}, metadataRegistry: params?.metadata ?? globalRegistry, target, unrepresentable: params?.unrepresentable ?? "throw", override: params?.override ?? (() => { }), io: params?.io ?? "output", counter: 0, seen: /* @__PURE__ */ new Map(), cycles: params?.cycles ?? "ref", reused: params?.reused ?? "inline", external: params?.external ?? void 0 }; } function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { var _a2; const def = schema._zod.def; const seen = ctx.seen.get(schema); if (seen) { seen.count++; const isCycle = _params.schemaPath.includes(schema); if (isCycle) { seen.cycle = _params.path; } return seen.schema; } const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; ctx.seen.set(schema, result); const overrideSchema = schema._zod.toJSONSchema?.(); if (overrideSchema) { result.schema = overrideSchema; } else { const params = { ..._params, schemaPath: [..._params.schemaPath, schema], path: _params.path }; if (schema._zod.processJSONSchema) { schema._zod.processJSONSchema(ctx, result.schema, params); } else { const _json = result.schema; const processor = ctx.processors[def.type]; if (!processor) { throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); } processor(schema, ctx, _json, params); } const parent = schema._zod.parent; if (parent) { if (!result.ref) result.ref = parent; process2(parent, ctx, params); ctx.seen.get(parent).isParent = true; } } const meta3 = ctx.metadataRegistry.get(schema); if (meta3) Object.assign(result.schema, meta3); if (ctx.io === "input" && isTransforming(schema)) { delete result.schema.examples; delete result.schema.default; } if (ctx.io === "input" && result.schema._prefault) (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault); delete result.schema._prefault; const _result = ctx.seen.get(schema); return _result.schema; } function extractDefs(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const idToSchema = /* @__PURE__ */ new Map(); for (const entry of ctx.seen.entries()) { const id = ctx.metadataRegistry.get(entry[0])?.id; if (id) { const existing = idToSchema.get(id); if (existing && existing !== entry[0]) { throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); } idToSchema.set(id, entry[0]); } } const makeURI = (entry) => { const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; if (ctx.external) { const externalId = ctx.external.registry.get(entry[0])?.id; const uriGenerator = ctx.external.uri ?? ((id2) => id2); if (externalId) { return { ref: uriGenerator(externalId) }; } const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; entry[1].defId = id; return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } if (entry[1] === root) { return { ref: "#" }; } const uriPrefix = `#`; const defUriPrefix = `${uriPrefix}/${defsSegment}/`; const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; return { defId, ref: defUriPrefix + defId }; }; const extractToDef = (entry) => { if (entry[1].schema.$ref) { return; } const seen = entry[1]; const { ref, defId } = makeURI(entry); seen.def = { ...seen.schema }; if (defId) seen.defId = defId; const schema2 = seen.schema; for (const key in schema2) { delete schema2[key]; } schema2.$ref = ref; }; if (ctx.cycles === "throw") { for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (seen.cycle) { throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); } } } for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (schema === entry[0]) { extractToDef(entry); continue; } if (ctx.external) { const ext = ctx.external.registry.get(entry[0])?.id; if (schema !== entry[0] && ext) { extractToDef(entry); continue; } } const id = ctx.metadataRegistry.get(entry[0])?.id; if (id) { extractToDef(entry); continue; } if (seen.cycle) { extractToDef(entry); continue; } if (seen.count > 1) { if (ctx.reused === "ref") { extractToDef(entry); continue; } } } } function finalize(ctx, schema) { const root = ctx.seen.get(schema); if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); const flattenRef = (zodSchema) => { const seen = ctx.seen.get(zodSchema); if (seen.ref === null) return; const schema2 = seen.def ?? seen.schema; const _cached = { ...schema2 }; const ref = seen.ref; seen.ref = null; if (ref) { flattenRef(ref); const refSeen = ctx.seen.get(ref); const refSchema = refSeen.schema; if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { schema2.allOf = schema2.allOf ?? []; schema2.allOf.push(refSchema); } else { Object.assign(schema2, refSchema); } Object.assign(schema2, _cached); const isParentRef = zodSchema._zod.parent === ref; if (isParentRef) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (!(key in _cached)) { delete schema2[key]; } } } if (refSchema.$ref && refSeen.def) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { delete schema2[key]; } } } } const parent = zodSchema._zod.parent; if (parent && parent !== ref) { flattenRef(parent); const parentSeen = ctx.seen.get(parent); if (parentSeen?.schema.$ref) { schema2.$ref = parentSeen.schema.$ref; if (parentSeen.def) { for (const key in schema2) { if (key === "$ref" || key === "allOf") continue; if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { delete schema2[key]; } } } } } ctx.override({ zodSchema, jsonSchema: schema2, path: seen.path ?? [] }); }; for (const entry of [...ctx.seen.entries()].reverse()) { flattenRef(entry[0]); } const result = {}; if (ctx.target === "draft-2020-12") { result.$schema = "https://json-schema.org/draft/2020-12/schema"; } else if (ctx.target === "draft-07") { result.$schema = "http://json-schema.org/draft-07/schema#"; } else if (ctx.target === "draft-04") { result.$schema = "http://json-schema.org/draft-04/schema#"; } else if (ctx.target === "openapi-3.0") { } else { } if (ctx.external?.uri) { const id = ctx.external.registry.get(schema)?.id; if (!id) throw new Error("Schema is missing an `id` property"); result.$id = ctx.external.uri(id); } Object.assign(result, root.def ?? root.schema); const defs = ctx.external?.defs ?? {}; for (const entry of ctx.seen.entries()) { const seen = entry[1]; if (seen.def && seen.defId) { defs[seen.defId] = seen.def; } } if (ctx.external) { } else { if (Object.keys(defs).length > 0) { if (ctx.target === "draft-2020-12") { result.$defs = defs; } else { result.definitions = defs; } } } try { const finalized = JSON.parse(JSON.stringify(result)); Object.defineProperty(finalized, "~standard", { value: { ...schema["~standard"], jsonSchema: { input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) } }, enumerable: false, writable: false }); return finalized; } catch (_err) { throw new Error("Error converting schema to JSON."); } } function isTransforming(_schema, _ctx) { const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; if (ctx.seen.has(_schema)) return false; ctx.seen.add(_schema); const def = _schema._zod.def; if (def.type === "transform") return true; if (def.type === "array") return isTransforming(def.element, ctx); if (def.type === "set") return isTransforming(def.valueType, ctx); if (def.type === "lazy") return isTransforming(def.getter(), ctx); if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { return isTransforming(def.innerType, ctx); } if (def.type === "intersection") { return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); } if (def.type === "record" || def.type === "map") { return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } if (def.type === "pipe") { return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); } if (def.type === "object") { for (const key in def.shape) { if (isTransforming(def.shape[key], ctx)) return true; } return false; } if (def.type === "union") { for (const option of def.options) { if (isTransforming(option, ctx)) return true; } return false; } if (def.type === "tuple") { for (const item of def.items) { if (isTransforming(item, ctx)) return true; } if (def.rest && isTransforming(def.rest, ctx)) return true; return false; } return false; } var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { const ctx = initializeContext({ ...params, processors }); process2(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { const { libraryOptions, target } = params ?? {}; const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); process2(schema, ctx); extractDefs(ctx, schema); return finalize(ctx, schema); }; // node_modules/zod/v4/core/json-schema-processors.js var formatMap = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" // do not set }; var stringProcessor = (schema, ctx, _json, _params) => { const json2 = _json; json2.type = "string"; const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; if (typeof minimum === "number") json2.minLength = minimum; if (typeof maximum === "number") json2.maxLength = maximum; if (format) { json2.format = formatMap[format] ?? format; if (json2.format === "") delete json2.format; if (format === "time") { delete json2.format; } } if (contentEncoding) json2.contentEncoding = contentEncoding; if (patterns && patterns.size > 0) { const regexes = [...patterns]; if (regexes.length === 1) json2.pattern = regexes[0].source; else if (regexes.length > 1) { json2.allOf = [ ...regexes.map((regex) => ({ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, pattern: regex.source })) ]; } } }; var numberProcessor = (schema, ctx, _json, _params) => { const json2 = _json; const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; if (typeof format === "string" && format.includes("int")) json2.type = "integer"; else json2.type = "number"; if (typeof exclusiveMinimum === "number") { if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { json2.minimum = exclusiveMinimum; json2.exclusiveMinimum = true; } else { json2.exclusiveMinimum = exclusiveMinimum; } } if (typeof minimum === "number") { json2.minimum = minimum; if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { if (exclusiveMinimum >= minimum) delete json2.minimum; else delete json2.exclusiveMinimum; } } if (typeof exclusiveMaximum === "number") { if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { json2.maximum = exclusiveMaximum; json2.exclusiveMaximum = true; } else { json2.exclusiveMaximum = exclusiveMaximum; } } if (typeof maximum === "number") { json2.maximum = maximum; if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { if (exclusiveMaximum <= maximum) delete json2.maximum; else delete json2.exclusiveMaximum; } } if (typeof multipleOf === "number") json2.multipleOf = multipleOf; }; var booleanProcessor = (_schema, _ctx, json2, _params) => { json2.type = "boolean"; }; var bigintProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("BigInt cannot be represented in JSON Schema"); } }; var symbolProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Symbols cannot be represented in JSON Schema"); } }; var nullProcessor = (_schema, ctx, json2, _params) => { if (ctx.target === "openapi-3.0") { json2.type = "string"; json2.nullable = true; json2.enum = [null]; } else { json2.type = "null"; } }; var undefinedProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Undefined cannot be represented in JSON Schema"); } }; var voidProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Void cannot be represented in JSON Schema"); } }; var neverProcessor = (_schema, _ctx, json2, _params) => { json2.not = {}; }; var anyProcessor = (_schema, _ctx, _json, _params) => { }; var unknownProcessor = (_schema, _ctx, _json, _params) => { }; var dateProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Date cannot be represented in JSON Schema"); } }; var enumProcessor = (schema, _ctx, json2, _params) => { const def = schema._zod.def; const values = getEnumValues(def.entries); if (values.every((v) => typeof v === "number")) json2.type = "number"; if (values.every((v) => typeof v === "string")) json2.type = "string"; json2.enum = values; }; var literalProcessor = (schema, ctx, json2, _params) => { const def = schema._zod.def; const vals = []; for (const val of def.values) { if (val === void 0) { if (ctx.unrepresentable === "throw") { throw new Error("Literal `undefined` cannot be represented in JSON Schema"); } else { } } else if (typeof val === "bigint") { if (ctx.unrepresentable === "throw") { throw new Error("BigInt literals cannot be represented in JSON Schema"); } else { vals.push(Number(val)); } } else { vals.push(val); } } if (vals.length === 0) { } else if (vals.length === 1) { const val = vals[0]; json2.type = val === null ? "null" : typeof val; if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { json2.enum = [val]; } else { json2.const = val; } } else { if (vals.every((v) => typeof v === "number")) json2.type = "number"; if (vals.every((v) => typeof v === "string")) json2.type = "string"; if (vals.every((v) => typeof v === "boolean")) json2.type = "boolean"; if (vals.every((v) => v === null)) json2.type = "null"; json2.enum = vals; } }; var nanProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("NaN cannot be represented in JSON Schema"); } }; var templateLiteralProcessor = (schema, _ctx, json2, _params) => { const _json = json2; const pattern = schema._zod.pattern; if (!pattern) throw new Error("Pattern not found in template literal"); _json.type = "string"; _json.pattern = pattern.source; }; var fileProcessor = (schema, _ctx, json2, _params) => { const _json = json2; const file2 = { type: "string", format: "binary", contentEncoding: "binary" }; const { minimum, maximum, mime: mime2 } = schema._zod.bag; if (minimum !== void 0) file2.minLength = minimum; if (maximum !== void 0) file2.maxLength = maximum; if (mime2) { if (mime2.length === 1) { file2.contentMediaType = mime2[0]; Object.assign(_json, file2); } else { Object.assign(_json, file2); _json.anyOf = mime2.map((m) => ({ contentMediaType: m })); } } else { Object.assign(_json, file2); } }; var successProcessor = (_schema, _ctx, json2, _params) => { json2.type = "boolean"; }; var customProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Custom types cannot be represented in JSON Schema"); } }; var functionProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Function types cannot be represented in JSON Schema"); } }; var transformProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Transforms cannot be represented in JSON Schema"); } }; var mapProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Map cannot be represented in JSON Schema"); } }; var setProcessor = (_schema, ctx, _json, _params) => { if (ctx.unrepresentable === "throw") { throw new Error("Set cannot be represented in JSON Schema"); } }; var arrayProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json2.minItems = minimum; if (typeof maximum === "number") json2.maxItems = maximum; json2.type = "array"; json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); }; var objectProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; json2.type = "object"; json2.properties = {}; const shape = def.shape; for (const key in shape) { json2.properties[key] = process2(shape[key], ctx, { ...params, path: [...params.path, "properties", key] }); } const allKeys = new Set(Object.keys(shape)); const requiredKeys = new Set([...allKeys].filter((key) => { const v = def.shape[key]._zod; if (ctx.io === "input") { return v.optin === void 0; } else { return v.optout === void 0; } })); if (requiredKeys.size > 0) { json2.required = Array.from(requiredKeys); } if (def.catchall?._zod.def.type === "never") { json2.additionalProperties = false; } else if (!def.catchall) { if (ctx.io === "output") json2.additionalProperties = false; } else if (def.catchall) { json2.additionalProperties = process2(def.catchall, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } }; var unionProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; const isExclusive = def.inclusive === false; const options = def.options.map((x, i) => process2(x, ctx, { ...params, path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] })); if (isExclusive) { json2.oneOf = options; } else { json2.anyOf = options; } }; var intersectionProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; const a = process2(def.left, ctx, { ...params, path: [...params.path, "allOf", 0] }); const b = process2(def.right, ctx, { ...params, path: [...params.path, "allOf", 1] }); const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; const allOf = [ ...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b] ]; json2.allOf = allOf; }; var tupleProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; json2.type = "array"; const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; const prefixItems = def.items.map((x, i) => process2(x, ctx, { ...params, path: [...params.path, prefixPath, i] })); const rest = def.rest ? process2(def.rest, ctx, { ...params, path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] }) : null; if (ctx.target === "draft-2020-12") { json2.prefixItems = prefixItems; if (rest) { json2.items = rest; } } else if (ctx.target === "openapi-3.0") { json2.items = { anyOf: prefixItems }; if (rest) { json2.items.anyOf.push(rest); } json2.minItems = prefixItems.length; if (!rest) { json2.maxItems = prefixItems.length; } } else { json2.items = prefixItems; if (rest) { json2.additionalItems = rest; } } const { minimum, maximum } = schema._zod.bag; if (typeof minimum === "number") json2.minItems = minimum; if (typeof maximum === "number") json2.maxItems = maximum; }; var recordProcessor = (schema, ctx, _json, params) => { const json2 = _json; const def = schema._zod.def; json2.type = "object"; const keyType = def.keyType; const keyBag = keyType._zod.bag; const patterns = keyBag?.patterns; if (def.mode === "loose" && patterns && patterns.size > 0) { const valueSchema = process2(def.valueType, ctx, { ...params, path: [...params.path, "patternProperties", "*"] }); json2.patternProperties = {}; for (const pattern of patterns) { json2.patternProperties[pattern.source] = valueSchema; } } else { if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { json2.propertyNames = process2(def.keyType, ctx, { ...params, path: [...params.path, "propertyNames"] }); } json2.additionalProperties = process2(def.valueType, ctx, { ...params, path: [...params.path, "additionalProperties"] }); } const keyValues = keyType._zod.values; if (keyValues) { const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); if (validKeyValues.length > 0) { json2.required = validKeyValues; } } }; var nullableProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; const inner = process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); if (ctx.target === "openapi-3.0") { seen.ref = def.innerType; json2.nullable = true; } else { json2.anyOf = [inner, { type: "null" }]; } }; var nonoptionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var defaultProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json2.default = JSON.parse(JSON.stringify(def.defaultValue)); }; var prefaultProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; if (ctx.io === "input") json2._prefault = JSON.parse(JSON.stringify(def.defaultValue)); }; var catchProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; let catchValue; try { catchValue = def.catchValue(void 0); } catch { throw new Error("Dynamic catch values are not supported in JSON Schema"); } json2.default = catchValue; }; var pipeProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; process2(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var readonlyProcessor = (schema, ctx, json2, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; json2.readOnly = true; }; var promiseProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var optionalProcessor = (schema, ctx, _json, params) => { const def = schema._zod.def; process2(def.innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = def.innerType; }; var lazyProcessor = (schema, ctx, _json, params) => { const innerType = schema._zod.innerType; process2(innerType, ctx, params); const seen = ctx.seen.get(schema); seen.ref = innerType; }; var allProcessors = { string: stringProcessor, number: numberProcessor, boolean: booleanProcessor, bigint: bigintProcessor, symbol: symbolProcessor, null: nullProcessor, undefined: undefinedProcessor, void: voidProcessor, never: neverProcessor, any: anyProcessor, unknown: unknownProcessor, date: dateProcessor, enum: enumProcessor, literal: literalProcessor, nan: nanProcessor, template_literal: templateLiteralProcessor, file: fileProcessor, success: successProcessor, custom: customProcessor, function: functionProcessor, transform: transformProcessor, map: mapProcessor, set: setProcessor, array: arrayProcessor, object: objectProcessor, union: unionProcessor, intersection: intersectionProcessor, tuple: tupleProcessor, record: recordProcessor, nullable: nullableProcessor, nonoptional: nonoptionalProcessor, default: defaultProcessor, prefault: prefaultProcessor, catch: catchProcessor, pipe: pipeProcessor, readonly: readonlyProcessor, promise: promiseProcessor, optional: optionalProcessor, lazy: lazyProcessor }; function toJSONSchema(input, params) { if ("_idmap" in input) { const registry2 = input; const ctx2 = initializeContext({ ...params, processors: allProcessors }); const defs = {}; for (const entry of registry2._idmap.entries()) { const [_, schema] = entry; process2(schema, ctx2); } const schemas = {}; const external = { registry: registry2, uri: params?.uri, defs }; ctx2.external = external; for (const entry of registry2._idmap.entries()) { const [key, schema] = entry; extractDefs(ctx2, schema); schemas[key] = finalize(ctx2, schema); } if (Object.keys(defs).length > 0) { const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; schemas.__shared = { [defsSegment]: defs }; } return { schemas }; } const ctx = initializeContext({ ...params, processors: allProcessors }); process2(input, ctx); extractDefs(ctx, input); return finalize(ctx, input); } // node_modules/zod/v4/core/json-schema-generator.js var JSONSchemaGenerator = class { /** @deprecated Access via ctx instead */ get metadataRegistry() { return this.ctx.metadataRegistry; } /** @deprecated Access via ctx instead */ get target() { return this.ctx.target; } /** @deprecated Access via ctx instead */ get unrepresentable() { return this.ctx.unrepresentable; } /** @deprecated Access via ctx instead */ get override() { return this.ctx.override; } /** @deprecated Access via ctx instead */ get io() { return this.ctx.io; } /** @deprecated Access via ctx instead */ get counter() { return this.ctx.counter; } set counter(value) { this.ctx.counter = value; } /** @deprecated Access via ctx instead */ get seen() { return this.ctx.seen; } constructor(params) { let normalizedTarget = params?.target ?? "draft-2020-12"; if (normalizedTarget === "draft-4") normalizedTarget = "draft-04"; if (normalizedTarget === "draft-7") normalizedTarget = "draft-07"; this.ctx = initializeContext({ processors: allProcessors, target: normalizedTarget, ...params?.metadata && { metadata: params.metadata }, ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, ...params?.override && { override: params.override }, ...params?.io && { io: params.io } }); } /** * Process a schema to prepare it for JSON Schema generation. * This must be called before emit(). */ process(schema, _params = { path: [], schemaPath: [] }) { return process2(schema, this.ctx, _params); } /** * Emit the final JSON Schema after processing. * Must call process() first. */ emit(schema, _params) { if (_params) { if (_params.cycles) this.ctx.cycles = _params.cycles; if (_params.reused) this.ctx.reused = _params.reused; if (_params.external) this.ctx.external = _params.external; } extractDefs(this.ctx, schema); const result = finalize(this.ctx, schema); const { "~standard": _, ...plainResult } = result; return plainResult; } }; // node_modules/zod/v4/core/json-schema.js var json_schema_exports = {}; // node_modules/zod/v4/classic/schemas.js var schemas_exports2 = {}; __export(schemas_exports2, { ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBase64: () => ZodBase64, ZodBase64URL: () => ZodBase64URL, ZodBigInt: () => ZodBigInt, ZodBigIntFormat: () => ZodBigIntFormat, ZodBoolean: () => ZodBoolean, ZodCIDRv4: () => ZodCIDRv4, ZodCIDRv6: () => ZodCIDRv6, ZodCUID: () => ZodCUID, ZodCUID2: () => ZodCUID2, ZodCatch: () => ZodCatch, ZodCodec: () => ZodCodec, ZodCustom: () => ZodCustom, ZodCustomStringFormat: () => ZodCustomStringFormat, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodE164: () => ZodE164, ZodEmail: () => ZodEmail, ZodEmoji: () => ZodEmoji, ZodEnum: () => ZodEnum, ZodExactOptional: () => ZodExactOptional, ZodFile: () => ZodFile, ZodFunction: () => ZodFunction, ZodGUID: () => ZodGUID, ZodIPv4: () => ZodIPv4, ZodIPv6: () => ZodIPv6, ZodIntersection: () => ZodIntersection, ZodJWT: () => ZodJWT, ZodKSUID: () => ZodKSUID, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMAC: () => ZodMAC, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNanoID: () => ZodNanoID, ZodNever: () => ZodNever, ZodNonOptional: () => ZodNonOptional, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodNumberFormat: () => ZodNumberFormat, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodPipe: () => ZodPipe, ZodPrefault: () => ZodPrefault, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRecord: () => ZodRecord, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodStringFormat: () => ZodStringFormat, ZodSuccess: () => ZodSuccess, ZodSymbol: () => ZodSymbol, ZodTemplateLiteral: () => ZodTemplateLiteral, ZodTransform: () => ZodTransform, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodULID: () => ZodULID, ZodURL: () => ZodURL, ZodUUID: () => ZodUUID, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, ZodXID: () => ZodXID, ZodXor: () => ZodXor, _ZodString: () => _ZodString, _default: () => _default2, _function: () => _function, any: () => any, array: () => array, base64: () => base642, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, catch: () => _catch2, check: () => check, cidrv4: () => cidrv42, cidrv6: () => cidrv62, codec: () => codec, cuid: () => cuid3, cuid2: () => cuid22, custom: () => custom, date: () => date3, describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, email: () => email2, emoji: () => emoji2, enum: () => _enum2, exactOptional: () => exactOptional, file: () => file, float32: () => float32, float64: () => float64, function: () => _function, guid: () => guid2, hash: () => hash, hex: () => hex2, hostname: () => hostname2, httpUrl: () => httpUrl, instanceof: () => _instanceof, int: () => int, int32: () => int32, int64: () => int64, intersection: () => intersection, ipv4: () => ipv42, ipv6: () => ipv62, json: () => json, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, lazy: () => lazy, literal: () => literal, looseObject: () => looseObject, looseRecord: () => looseRecord, mac: () => mac2, map: () => map, meta: () => meta2, nan: () => nan, nanoid: () => nanoid2, nativeEnum: () => nativeEnum, never: () => never, nonoptional: () => nonoptional, null: () => _null3, nullable: () => nullable, nullish: () => nullish2, number: () => number2, object: () => object, optional: () => optional, partialRecord: () => partialRecord, pipe: () => pipe, prefault: () => prefault, preprocess: () => preprocess, promise: () => promise, readonly: () => readonly, record: () => record, refine: () => refine, set: () => set, strictObject: () => strictObject, string: () => string2, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, superRefine: () => superRefine, symbol: () => symbol, templateLiteral: () => templateLiteral, transform: () => transform, tuple: () => tuple, uint32: () => uint32, uint64: () => uint64, ulid: () => ulid2, undefined: () => _undefined3, union: () => union, unknown: () => unknown, url: () => url, uuid: () => uuid2, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, void: () => _void2, xid: () => xid2, xor: () => xor }); // node_modules/zod/v4/classic/checks.js var checks_exports2 = {}; __export(checks_exports2, { endsWith: () => _endsWith, gt: () => _gt, gte: () => _gte, includes: () => _includes, length: () => _length, lowercase: () => _lowercase, lt: () => _lt, lte: () => _lte, maxLength: () => _maxLength, maxSize: () => _maxSize, mime: () => _mime, minLength: () => _minLength, minSize: () => _minSize, multipleOf: () => _multipleOf, negative: () => _negative, nonnegative: () => _nonnegative, nonpositive: () => _nonpositive, normalize: () => _normalize, overwrite: () => _overwrite, positive: () => _positive, property: () => _property, regex: () => _regex, size: () => _size, slugify: () => _slugify, startsWith: () => _startsWith, toLowerCase: () => _toLowerCase, toUpperCase: () => _toUpperCase, trim: () => _trim, uppercase: () => _uppercase }); // node_modules/zod/v4/classic/iso.js var iso_exports = {}; __export(iso_exports, { ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, ZodISODuration: () => ZodISODuration, ZodISOTime: () => ZodISOTime, date: () => date2, datetime: () => datetime2, duration: () => duration2, time: () => time2 }); var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { $ZodISODateTime.init(inst, def); ZodStringFormat.init(inst, def); }); function datetime2(params) { return _isoDateTime(ZodISODateTime, params); } var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { $ZodISODate.init(inst, def); ZodStringFormat.init(inst, def); }); function date2(params) { return _isoDate(ZodISODate, params); } var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { $ZodISOTime.init(inst, def); ZodStringFormat.init(inst, def); }); function time2(params) { return _isoTime(ZodISOTime, params); } var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { $ZodISODuration.init(inst, def); ZodStringFormat.init(inst, def); }); function duration2(params) { return _isoDuration(ZodISODuration, params); } // node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError(inst, mapper) // enumerable: false, }, flatten: { value: (mapper) => flattenError(inst, mapper) // enumerable: false, }, addIssue: { value: (issue2) => { inst.issues.push(issue2); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, addIssues: { value: (issues2) => { inst.issues.push(...issues2); inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); } // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; } // enumerable: false, } }); }; var ZodError = $constructor("ZodError", initializer2); var ZodRealError = $constructor("ZodError", initializer2, { Parent: Error }); // node_modules/zod/v4/classic/parse.js var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); var encode2 = /* @__PURE__ */ _encode(ZodRealError); var decode2 = /* @__PURE__ */ _decode(ZodRealError); var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); // node_modules/zod/v4/classic/schemas.js var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); Object.assign(inst["~standard"], { jsonSchema: { input: createStandardJSONSchemaMethod(inst, "input"), output: createStandardJSONSchemaMethod(inst, "output") } }); inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; inst.type = def.type; Object.defineProperty(inst, "_def", { value: def }); inst.check = (...checks) => { return inst.clone(util_exports.mergeDefs(def, { checks: [ ...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) ] }), { parent: true }); }; inst.with = inst.check; inst.clone = (def2, params) => clone(inst, def2, params); inst.brand = () => inst; inst.register = ((reg, meta3) => { reg.add(inst, meta3); return inst; }); inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse2(inst, data, params); inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); inst.spa = inst.safeParseAsync; inst.encode = (data, params) => encode2(inst, data, params); inst.decode = (data, params) => decode2(inst, data, params); inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); inst.safeEncode = (data, params) => safeEncode2(inst, data, params); inst.safeDecode = (data, params) => safeDecode2(inst, data, params); inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); inst.refine = (check2, params) => inst.check(refine(check2, params)); inst.superRefine = (refinement) => inst.check(superRefine(refinement)); inst.overwrite = (fn) => inst.check(_overwrite(fn)); inst.optional = () => optional(inst); inst.exactOptional = () => exactOptional(inst); inst.nullable = () => nullable(inst); inst.nullish = () => optional(nullable(inst)); inst.nonoptional = (params) => nonoptional(inst, params); inst.array = () => array(inst); inst.or = (arg) => union([inst, arg]); inst.and = (arg) => intersection(inst, arg); inst.transform = (tx) => pipe(inst, transform(tx)); inst.default = (def2) => _default2(inst, def2); inst.prefault = (def2) => prefault(inst, def2); inst.catch = (params) => _catch2(inst, params); inst.pipe = (target) => pipe(inst, target); inst.readonly = () => readonly(inst); inst.describe = (description) => { const cl = inst.clone(); globalRegistry.add(cl, { description }); return cl; }; Object.defineProperty(inst, "description", { get() { return globalRegistry.get(inst)?.description; }, configurable: true }); inst.meta = (...args) => { if (args.length === 0) { return globalRegistry.get(inst); } const cl = inst.clone(); globalRegistry.add(cl, args[0]); return cl; }; inst.isOptional = () => inst.safeParse(void 0).success; inst.isNullable = () => inst.safeParse(null).success; inst.apply = (fn) => fn(inst); return inst; }); var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { $ZodString.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); const bag = inst._zod.bag; inst.format = bag.format ?? null; inst.minLength = bag.minimum ?? null; inst.maxLength = bag.maximum ?? null; inst.regex = (...args) => inst.check(_regex(...args)); inst.includes = (...args) => inst.check(_includes(...args)); inst.startsWith = (...args) => inst.check(_startsWith(...args)); inst.endsWith = (...args) => inst.check(_endsWith(...args)); inst.min = (...args) => inst.check(_minLength(...args)); inst.max = (...args) => inst.check(_maxLength(...args)); inst.length = (...args) => inst.check(_length(...args)); inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); inst.lowercase = (params) => inst.check(_lowercase(params)); inst.uppercase = (params) => inst.check(_uppercase(params)); inst.trim = () => inst.check(_trim()); inst.normalize = (...args) => inst.check(_normalize(...args)); inst.toLowerCase = () => inst.check(_toLowerCase()); inst.toUpperCase = () => inst.check(_toUpperCase()); inst.slugify = () => inst.check(_slugify()); }); var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); _ZodString.init(inst, def); inst.email = (params) => inst.check(_email(ZodEmail, params)); inst.url = (params) => inst.check(_url(ZodURL, params)); inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); inst.guid = (params) => inst.check(_guid(ZodGUID, params)); inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); inst.xid = (params) => inst.check(_xid(ZodXID, params)); inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); inst.e164 = (params) => inst.check(_e164(ZodE164, params)); inst.datetime = (params) => inst.check(datetime2(params)); inst.date = (params) => inst.check(date2(params)); inst.time = (params) => inst.check(time2(params)); inst.duration = (params) => inst.check(duration2(params)); }); function string2(params) { return _string(ZodString, params); } var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { $ZodStringFormat.init(inst, def); _ZodString.init(inst, def); }); var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); function email2(params) { return _email(ZodEmail, params); } var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { $ZodGUID.init(inst, def); ZodStringFormat.init(inst, def); }); function guid2(params) { return _guid(ZodGUID, params); } var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); function uuid2(params) { return _uuid(ZodUUID, params); } function uuidv4(params) { return _uuidv4(ZodUUID, params); } function uuidv6(params) { return _uuidv6(ZodUUID, params); } function uuidv7(params) { return _uuidv7(ZodUUID, params); } var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); function url(params) { return _url(ZodURL, params); } function httpUrl(params) { return _url(ZodURL, { protocol: /^https?$/, hostname: regexes_exports.domain, ...util_exports.normalizeParams(params) }); } var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { $ZodEmoji.init(inst, def); ZodStringFormat.init(inst, def); }); function emoji2(params) { return _emoji2(ZodEmoji, params); } var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { $ZodNanoID.init(inst, def); ZodStringFormat.init(inst, def); }); function nanoid2(params) { return _nanoid(ZodNanoID, params); } var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { $ZodCUID.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid3(params) { return _cuid(ZodCUID, params); } var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { $ZodCUID2.init(inst, def); ZodStringFormat.init(inst, def); }); function cuid22(params) { return _cuid2(ZodCUID2, params); } var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { $ZodULID.init(inst, def); ZodStringFormat.init(inst, def); }); function ulid2(params) { return _ulid(ZodULID, params); } var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { $ZodXID.init(inst, def); ZodStringFormat.init(inst, def); }); function xid2(params) { return _xid(ZodXID, params); } var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { $ZodKSUID.init(inst, def); ZodStringFormat.init(inst, def); }); function ksuid2(params) { return _ksuid(ZodKSUID, params); } var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { $ZodIPv4.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv42(params) { return _ipv4(ZodIPv4, params); } var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { $ZodMAC.init(inst, def); ZodStringFormat.init(inst, def); }); function mac2(params) { return _mac(ZodMAC, params); } var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { $ZodIPv6.init(inst, def); ZodStringFormat.init(inst, def); }); function ipv62(params) { return _ipv6(ZodIPv6, params); } var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { $ZodCIDRv4.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv42(params) { return _cidrv4(ZodCIDRv4, params); } var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { $ZodCIDRv6.init(inst, def); ZodStringFormat.init(inst, def); }); function cidrv62(params) { return _cidrv6(ZodCIDRv6, params); } var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); function base642(params) { return _base64(ZodBase64, params); } var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { $ZodBase64URL.init(inst, def); ZodStringFormat.init(inst, def); }); function base64url2(params) { return _base64url(ZodBase64URL, params); } var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { $ZodE164.init(inst, def); ZodStringFormat.init(inst, def); }); function e1642(params) { return _e164(ZodE164, params); } var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); }); function jwt(params) { return _jwt(ZodJWT, params); } var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { $ZodCustomStringFormat.init(inst, def); ZodStringFormat.init(inst, def); }); function stringFormat(format, fnOrRegex, _params = {}) { return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); } function hostname2(_params) { return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); } function hex2(_params) { return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); } function hash(alg, params) { const enc = params?.enc ?? "hex"; const format = `${alg}_${enc}`; const regex = regexes_exports[format]; if (!regex) throw new Error(`Unrecognized hash format: ${format}`); return _stringFormat(ZodCustomStringFormat, format, regex, params); } var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { $ZodNumber.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.int = (params) => inst.check(int(params)); inst.safe = (params) => inst.check(int(params)); inst.positive = (params) => inst.check(_gt(0, params)); inst.nonnegative = (params) => inst.check(_gte(0, params)); inst.negative = (params) => inst.check(_lt(0, params)); inst.nonpositive = (params) => inst.check(_lte(0, params)); inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); inst.step = (value, params) => inst.check(_multipleOf(value, params)); inst.finite = () => inst; const bag = inst._zod.bag; inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); inst.isFinite = true; inst.format = bag.format ?? null; }); function number2(params) { return _number(ZodNumber, params); } var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); ZodNumber.init(inst, def); }); function int(params) { return _int(ZodNumberFormat, params); } function float32(params) { return _float32(ZodNumberFormat, params); } function float64(params) { return _float64(ZodNumberFormat, params); } function int32(params) { return _int32(ZodNumberFormat, params); } function uint32(params) { return _uint32(ZodNumberFormat, params); } var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); }); function boolean2(params) { return _boolean(ZodBoolean, params); } var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { $ZodBigInt.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); inst.lt = (value, params) => inst.check(_lt(value, params)); inst.lte = (value, params) => inst.check(_lte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); inst.positive = (params) => inst.check(_gt(BigInt(0), params)); inst.negative = (params) => inst.check(_lt(BigInt(0), params)); inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); const bag = inst._zod.bag; inst.minValue = bag.minimum ?? null; inst.maxValue = bag.maximum ?? null; inst.format = bag.format ?? null; }); function bigint2(params) { return _bigint(ZodBigInt, params); } var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { $ZodBigIntFormat.init(inst, def); ZodBigInt.init(inst, def); }); function int64(params) { return _int64(ZodBigIntFormat, params); } function uint64(params) { return _uint64(ZodBigIntFormat, params); } var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { $ZodSymbol.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); }); function symbol(params) { return _symbol(ZodSymbol, params); } var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { $ZodUndefined.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); }); function _undefined3(params) { return _undefined2(ZodUndefined, params); } var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); }); function _null3(params) { return _null2(ZodNull, params); } var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { $ZodAny.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); }); function any() { return _any(ZodAny); } var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); }); function unknown() { return _unknown(ZodUnknown); } var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); }); function never(params) { return _never(ZodNever, params); } var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { $ZodVoid.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); }); function _void2(params) { return _void(ZodVoid, params); } var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { $ZodDate.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); inst.min = (value, params) => inst.check(_gte(value, params)); inst.max = (value, params) => inst.check(_lte(value, params)); const c = inst._zod.bag; inst.minDate = c.minimum ? new Date(c.minimum) : null; inst.maxDate = c.maximum ? new Date(c.maximum) : null; }); function date3(params) { return _date(ZodDate, params); } var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); inst.element = def.element; inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); inst.nonempty = (params) => inst.check(_minLength(1, params)); inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); inst.length = (len, params) => inst.check(_length(len, params)); inst.unwrap = () => inst.element; }); function array(element, params) { return _array(ZodArray, element, params); } function keyof(schema) { const shape = schema._zod.def.shape; return _enum2(Object.keys(shape)); } var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { $ZodObjectJIT.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); util_exports.defineLazy(inst, "shape", () => { return def.shape; }); inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); inst.extend = (incoming) => { return util_exports.extend(inst, incoming); }; inst.safeExtend = (incoming) => { return util_exports.safeExtend(inst, incoming); }; inst.merge = (other) => util_exports.merge(inst, other); inst.pick = (mask) => util_exports.pick(inst, mask); inst.omit = (mask) => util_exports.omit(inst, mask); inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); }); function object(shape, params) { const def = { type: "object", shape: shape ?? {}, ...util_exports.normalizeParams(params) }; return new ZodObject(def); } function strictObject(shape, params) { return new ZodObject({ type: "object", shape, catchall: never(), ...util_exports.normalizeParams(params) }); } function looseObject(shape, params) { return new ZodObject({ type: "object", shape, catchall: unknown(), ...util_exports.normalizeParams(params) }); } var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); inst.options = def.options; }); function union(options, params) { return new ZodUnion({ type: "union", options, ...util_exports.normalizeParams(params) }); } var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { ZodUnion.init(inst, def); $ZodXor.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); inst.options = def.options; }); function xor(options, params) { return new ZodXor({ type: "union", options, inclusive: false, ...util_exports.normalizeParams(params) }); } var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { ZodUnion.init(inst, def); $ZodDiscriminatedUnion.init(inst, def); }); function discriminatedUnion(discriminator, options, params) { return new ZodDiscriminatedUnion({ type: "union", options, discriminator, ...util_exports.normalizeParams(params) }); } var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); }); function intersection(left, right) { return new ZodIntersection({ type: "intersection", left, right }); } var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { $ZodTuple.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); inst.rest = (rest) => inst.clone({ ...inst._zod.def, rest }); }); function tuple(items, _paramsOrRest, _params) { const hasRest = _paramsOrRest instanceof $ZodType; const params = hasRest ? _params : _paramsOrRest; const rest = hasRest ? _paramsOrRest : null; return new ZodTuple({ type: "tuple", items, rest, ...util_exports.normalizeParams(params) }); } var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); inst.keyType = def.keyType; inst.valueType = def.valueType; }); function record(keyType, valueType, params) { return new ZodRecord({ type: "record", keyType, valueType, ...util_exports.normalizeParams(params) }); } function partialRecord(keyType, valueType, params) { const k = clone(keyType); k._zod.values = void 0; return new ZodRecord({ type: "record", keyType: k, valueType, ...util_exports.normalizeParams(params) }); } function looseRecord(keyType, valueType, params) { return new ZodRecord({ type: "record", keyType, valueType, mode: "loose", ...util_exports.normalizeParams(params) }); } var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { $ZodMap.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); inst.keyType = def.keyType; inst.valueType = def.valueType; inst.min = (...args) => inst.check(_minSize(...args)); inst.nonempty = (params) => inst.check(_minSize(1, params)); inst.max = (...args) => inst.check(_maxSize(...args)); inst.size = (...args) => inst.check(_size(...args)); }); function map(keyType, valueType, params) { return new ZodMap({ type: "map", keyType, valueType, ...util_exports.normalizeParams(params) }); } var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { $ZodSet.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); inst.min = (...args) => inst.check(_minSize(...args)); inst.nonempty = (params) => inst.check(_minSize(1, params)); inst.max = (...args) => inst.check(_maxSize(...args)); inst.size = (...args) => inst.check(_size(...args)); }); function set(valueType, params) { return new ZodSet({ type: "set", valueType, ...util_exports.normalizeParams(params) }); } var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params); inst.enum = def.entries; inst.options = Object.values(def.entries); const keys = new Set(Object.keys(def.entries)); inst.extract = (values, params) => { const newEntries = {}; for (const value of values) { if (keys.has(value)) { newEntries[value] = def.entries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; inst.exclude = (values, params) => { const newEntries = { ...def.entries }; for (const value of values) { if (keys.has(value)) { delete newEntries[value]; } else throw new Error(`Key ${value} not found in enum`); } return new ZodEnum({ ...def, checks: [], ...util_exports.normalizeParams(params), entries: newEntries }); }; }); function _enum2(values, params) { const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; return new ZodEnum({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } function nativeEnum(entries, params) { return new ZodEnum({ type: "enum", entries, ...util_exports.normalizeParams(params) }); } var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params); inst.values = new Set(def.values); Object.defineProperty(inst, "value", { get() { if (def.values.length > 1) { throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); } return def.values[0]; } }); }); function literal(value, params) { return new ZodLiteral({ type: "literal", values: Array.isArray(value) ? value : [value], ...util_exports.normalizeParams(params) }); } var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { $ZodFile.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); inst.min = (size, params) => inst.check(_minSize(size, params)); inst.max = (size, params) => inst.check(_maxSize(size, params)); inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); }); function file(params) { return _file(ZodFile, params); } var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); inst._zod.parse = (payload, _ctx) => { if (_ctx.direction === "backward") { throw new $ZodEncodeError(inst.constructor.name); } payload.addIssue = (issue2) => { if (typeof issue2 === "string") { payload.issues.push(util_exports.issue(issue2, payload.value, def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; _issue.code ?? (_issue.code = "custom"); _issue.input ?? (_issue.input = payload.value); _issue.inst ?? (_issue.inst = inst); payload.issues.push(util_exports.issue(_issue)); } }; const output = def.transform(payload.value, payload); if (output instanceof Promise) { return output.then((output2) => { payload.value = output2; return payload; }); } payload.value = output; return payload; }; }); function transform(fn) { return new ZodTransform({ type: "transform", transform: fn }); } var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function optional(innerType) { return new ZodOptional({ type: "optional", innerType }); } var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { $ZodExactOptional.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function exactOptional(innerType) { return new ZodExactOptional({ type: "optional", innerType }); } var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function nullable(innerType) { return new ZodNullable({ type: "nullable", innerType }); } function nullish2(innerType) { return optional(nullable(innerType)); } var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); function _default2(innerType, defaultValue) { return new ZodDefault({ type: "default", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function prefault(innerType, defaultValue) { return new ZodPrefault({ type: "prefault", innerType, get defaultValue() { return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional(innerType, params) { return new ZodNonOptional({ type: "nonoptional", innerType, ...util_exports.normalizeParams(params) }); } var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { $ZodSuccess.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function success(innerType) { return new ZodSuccess({ type: "success", innerType }); } var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); function _catch2(innerType, catchValue) { return new ZodCatch({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { $ZodNaN.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); }); function nan(params) { return _nan(ZodNaN, params); } var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); inst.in = def.in; inst.out = def.out; }); function pipe(in_, out) { return new ZodPipe({ type: "pipe", in: in_, out // ...util.normalizeParams(params), }); } var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { ZodPipe.init(inst, def); $ZodCodec.init(inst, def); }); function codec(in_, out, params) { return new ZodCodec({ type: "pipe", in: in_, out, transform: params.decode, reverseTransform: params.encode }); } var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function readonly(innerType) { return new ZodReadonly({ type: "readonly", innerType }); } var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { $ZodTemplateLiteral.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); }); function templateLiteral(parts, params) { return new ZodTemplateLiteral({ type: "template_literal", parts, ...util_exports.normalizeParams(params) }); } var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { $ZodLazy.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.getter(); }); function lazy(getter) { return new ZodLazy({ type: "lazy", getter }); } var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { $ZodPromise.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function promise(innerType) { return new ZodPromise({ type: "promise", innerType }); } var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { $ZodFunction.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); }); function _function(params) { return new ZodFunction({ type: "function", input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), output: params?.output ?? unknown() }); } var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); ZodType.init(inst, def); inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); }); function check(fn) { const ch = new $ZodCheck({ check: "custom" // ...util.normalizeParams(params), }); ch._zod.check = fn; return ch; } function custom(fn, _params) { return _custom(ZodCustom, fn ?? (() => true), _params); } function refine(fn, _params = {}) { return _refine(ZodCustom, fn, _params); } function superRefine(fn) { return _superRefine(fn); } var describe2 = describe; var meta2 = meta; function _instanceof(cls, params = {}) { const inst = new ZodCustom({ type: "custom", check: "custom", fn: (data) => data instanceof cls, abort: true, ...util_exports.normalizeParams(params) }); inst._zod.bag.Class = cls; inst._zod.check = (payload) => { if (!(payload.value instanceof cls)) { payload.issues.push({ code: "invalid_type", expected: cls.name, input: payload.value, inst, path: [...inst._zod.def.path ?? []] }); } }; return inst; } var stringbool = (...args) => _stringbool({ Codec: ZodCodec, Boolean: ZodBoolean, String: ZodString }, ...args); function json(params) { const jsonSchema = lazy(() => { return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); }); return jsonSchema; } function preprocess(fn, schema) { return pipe(transform(fn), schema); } // node_modules/zod/v4/classic/compat.js var ZodIssueCode = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" }; function setErrorMap(map2) { config({ customError: map2 }); } function getErrorMap() { return config().customError; } var ZodFirstPartyTypeKind; /* @__PURE__ */ (function(ZodFirstPartyTypeKind3) { })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); // node_modules/zod/v4/classic/from-json-schema.js var z = { ...schemas_exports2, ...checks_exports2, iso: iso_exports }; var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ // Schema identification "$schema", "$ref", "$defs", "definitions", // Core schema keywords "$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor", // Type "type", "enum", "const", // Composition "anyOf", "oneOf", "allOf", "not", // Object "properties", "required", "additionalProperties", "patternProperties", "propertyNames", "minProperties", "maxProperties", // Array "items", "prefixItems", "additionalItems", "minItems", "maxItems", "uniqueItems", "contains", "minContains", "maxContains", // String "minLength", "maxLength", "pattern", "format", // Number "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", // Already handled metadata "description", "default", // Content "contentEncoding", "contentMediaType", "contentSchema", // Unsupported (error-throwing) "unevaluatedItems", "unevaluatedProperties", "if", "then", "else", "dependentSchemas", "dependentRequired", // OpenAPI "nullable", "readOnly" ]); function detectVersion(schema, defaultTarget) { const $schema = schema.$schema; if ($schema === "https://json-schema.org/draft/2020-12/schema") { return "draft-2020-12"; } if ($schema === "http://json-schema.org/draft-07/schema#") { return "draft-7"; } if ($schema === "http://json-schema.org/draft-04/schema#") { return "draft-4"; } return defaultTarget ?? "draft-2020-12"; } function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); } const path = ref.slice(1).split("/").filter(Boolean); if (path.length === 0) { return ctx.rootSchema; } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; if (path[0] === defsKey) { const key = path[1]; if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } return ctx.defs[key]; } throw new Error(`Reference not found: ${ref}`); } function convertBaseSchema(schema, ctx) { if (schema.not !== void 0) { if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { return z.never(); } throw new Error("not is not supported in Zod (except { not: {} } for never)"); } if (schema.unevaluatedItems !== void 0) { throw new Error("unevaluatedItems is not supported"); } if (schema.unevaluatedProperties !== void 0) { throw new Error("unevaluatedProperties is not supported"); } if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) { throw new Error("Conditional schemas (if/then/else) are not supported"); } if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) { throw new Error("dependentSchemas and dependentRequired are not supported"); } if (schema.$ref) { const refPath = schema.$ref; if (ctx.refs.has(refPath)) { return ctx.refs.get(refPath); } if (ctx.processing.has(refPath)) { return z.lazy(() => { if (!ctx.refs.has(refPath)) { throw new Error(`Circular reference not resolved: ${refPath}`); } return ctx.refs.get(refPath); }); } ctx.processing.add(refPath); const resolved = resolveRef(refPath, ctx); const zodSchema2 = convertSchema(resolved, ctx); ctx.refs.set(refPath, zodSchema2); ctx.processing.delete(refPath); return zodSchema2; } if (schema.enum !== void 0) { const enumValues = schema.enum; if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) { return z.null(); } if (enumValues.length === 0) { return z.never(); } if (enumValues.length === 1) { return z.literal(enumValues[0]); } if (enumValues.every((v) => typeof v === "string")) { return z.enum(enumValues); } const literalSchemas = enumValues.map((v) => z.literal(v)); if (literalSchemas.length < 2) { return literalSchemas[0]; } return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); } if (schema.const !== void 0) { return z.literal(schema.const); } const type = schema.type; if (Array.isArray(type)) { const typeSchemas = type.map((t) => { const typeSchema = { ...schema, type: t }; return convertBaseSchema(typeSchema, ctx); }); if (typeSchemas.length === 0) { return z.never(); } if (typeSchemas.length === 1) { return typeSchemas[0]; } return z.union(typeSchemas); } if (!type) { return z.any(); } let zodSchema; switch (type) { case "string": { let stringSchema = z.string(); if (schema.format) { const format = schema.format; if (format === "email") { stringSchema = stringSchema.check(z.email()); } else if (format === "uri" || format === "uri-reference") { stringSchema = stringSchema.check(z.url()); } else if (format === "uuid" || format === "guid") { stringSchema = stringSchema.check(z.uuid()); } else if (format === "date-time") { stringSchema = stringSchema.check(z.iso.datetime()); } else if (format === "date") { stringSchema = stringSchema.check(z.iso.date()); } else if (format === "time") { stringSchema = stringSchema.check(z.iso.time()); } else if (format === "duration") { stringSchema = stringSchema.check(z.iso.duration()); } else if (format === "ipv4") { stringSchema = stringSchema.check(z.ipv4()); } else if (format === "ipv6") { stringSchema = stringSchema.check(z.ipv6()); } else if (format === "mac") { stringSchema = stringSchema.check(z.mac()); } else if (format === "cidr") { stringSchema = stringSchema.check(z.cidrv4()); } else if (format === "cidr-v6") { stringSchema = stringSchema.check(z.cidrv6()); } else if (format === "base64") { stringSchema = stringSchema.check(z.base64()); } else if (format === "base64url") { stringSchema = stringSchema.check(z.base64url()); } else if (format === "e164") { stringSchema = stringSchema.check(z.e164()); } else if (format === "jwt") { stringSchema = stringSchema.check(z.jwt()); } else if (format === "emoji") { stringSchema = stringSchema.check(z.emoji()); } else if (format === "nanoid") { stringSchema = stringSchema.check(z.nanoid()); } else if (format === "cuid") { stringSchema = stringSchema.check(z.cuid()); } else if (format === "cuid2") { stringSchema = stringSchema.check(z.cuid2()); } else if (format === "ulid") { stringSchema = stringSchema.check(z.ulid()); } else if (format === "xid") { stringSchema = stringSchema.check(z.xid()); } else if (format === "ksuid") { stringSchema = stringSchema.check(z.ksuid()); } } if (typeof schema.minLength === "number") { stringSchema = stringSchema.min(schema.minLength); } if (typeof schema.maxLength === "number") { stringSchema = stringSchema.max(schema.maxLength); } if (schema.pattern) { stringSchema = stringSchema.regex(new RegExp(schema.pattern)); } zodSchema = stringSchema; break; } case "number": case "integer": { let numberSchema = type === "integer" ? z.number().int() : z.number(); if (typeof schema.minimum === "number") { numberSchema = numberSchema.min(schema.minimum); } if (typeof schema.maximum === "number") { numberSchema = numberSchema.max(schema.maximum); } if (typeof schema.exclusiveMinimum === "number") { numberSchema = numberSchema.gt(schema.exclusiveMinimum); } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { numberSchema = numberSchema.gt(schema.minimum); } if (typeof schema.exclusiveMaximum === "number") { numberSchema = numberSchema.lt(schema.exclusiveMaximum); } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { numberSchema = numberSchema.lt(schema.maximum); } if (typeof schema.multipleOf === "number") { numberSchema = numberSchema.multipleOf(schema.multipleOf); } zodSchema = numberSchema; break; } case "boolean": { zodSchema = z.boolean(); break; } case "null": { zodSchema = z.null(); break; } case "object": { const shape = {}; const properties = schema.properties || {}; const requiredSet = new Set(schema.required || []); for (const [key, propSchema] of Object.entries(properties)) { const propZodSchema = convertSchema(propSchema, ctx); shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); } if (schema.propertyNames) { const keySchema = convertSchema(schema.propertyNames, ctx); const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); if (Object.keys(shape).length === 0) { zodSchema = z.record(keySchema, valueSchema); break; } const objectSchema2 = z.object(shape).passthrough(); const recordSchema = z.looseRecord(keySchema, valueSchema); zodSchema = z.intersection(objectSchema2, recordSchema); break; } if (schema.patternProperties) { const patternProps = schema.patternProperties; const patternKeys = Object.keys(patternProps); const looseRecords = []; for (const pattern of patternKeys) { const patternValue = convertSchema(patternProps[pattern], ctx); const keySchema = z.string().regex(new RegExp(pattern)); looseRecords.push(z.looseRecord(keySchema, patternValue)); } const schemasToIntersect = []; if (Object.keys(shape).length > 0) { schemasToIntersect.push(z.object(shape).passthrough()); } schemasToIntersect.push(...looseRecords); if (schemasToIntersect.length === 0) { zodSchema = z.object({}).passthrough(); } else if (schemasToIntersect.length === 1) { zodSchema = schemasToIntersect[0]; } else { let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]); for (let i = 2; i < schemasToIntersect.length; i++) { result = z.intersection(result, schemasToIntersect[i]); } zodSchema = result; } break; } const objectSchema = z.object(shape); if (schema.additionalProperties === false) { zodSchema = objectSchema.strict(); } else if (typeof schema.additionalProperties === "object") { zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); } else { zodSchema = objectSchema.passthrough(); } break; } case "array": { const prefixItems = schema.prefixItems; const items = schema.items; if (prefixItems && Array.isArray(prefixItems)) { const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; if (rest) { zodSchema = z.tuple(tupleItems).rest(rest); } else { zodSchema = z.tuple(tupleItems); } if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } if (typeof schema.maxItems === "number") { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (Array.isArray(items)) { const tupleItems = items.map((item) => convertSchema(item, ctx)); const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; if (rest) { zodSchema = z.tuple(tupleItems).rest(rest); } else { zodSchema = z.tuple(tupleItems); } if (typeof schema.minItems === "number") { zodSchema = zodSchema.check(z.minLength(schema.minItems)); } if (typeof schema.maxItems === "number") { zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); } } else if (items !== void 0) { const element = convertSchema(items, ctx); let arraySchema = z.array(element); if (typeof schema.minItems === "number") { arraySchema = arraySchema.min(schema.minItems); } if (typeof schema.maxItems === "number") { arraySchema = arraySchema.max(schema.maxItems); } zodSchema = arraySchema; } else { zodSchema = z.array(z.any()); } break; } default: throw new Error(`Unsupported type: ${type}`); } if (schema.description) { zodSchema = zodSchema.describe(schema.description); } if (schema.default !== void 0) { zodSchema = zodSchema.default(schema.default); } return zodSchema; } function convertSchema(schema, ctx) { if (typeof schema === "boolean") { return schema ? z.any() : z.never(); } let baseSchema = convertBaseSchema(schema, ctx); const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0; if (schema.anyOf && Array.isArray(schema.anyOf)) { const options = schema.anyOf.map((s) => convertSchema(s, ctx)); const anyOfUnion = z.union(options); baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion; } if (schema.oneOf && Array.isArray(schema.oneOf)) { const options = schema.oneOf.map((s) => convertSchema(s, ctx)); const oneOfUnion = z.xor(options); baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion; } if (schema.allOf && Array.isArray(schema.allOf)) { if (schema.allOf.length === 0) { baseSchema = hasExplicitType ? baseSchema : z.any(); } else { let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); const startIdx = hasExplicitType ? 0 : 1; for (let i = startIdx; i < schema.allOf.length; i++) { result = z.intersection(result, convertSchema(schema.allOf[i], ctx)); } baseSchema = result; } } if (schema.nullable === true && ctx.version === "openapi-3.0") { baseSchema = z.nullable(baseSchema); } if (schema.readOnly === true) { baseSchema = z.readonly(baseSchema); } const extraMeta = {}; const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; for (const key of coreMetadataKeys) { if (key in schema) { extraMeta[key] = schema[key]; } } const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; for (const key of contentMetadataKeys) { if (key in schema) { extraMeta[key] = schema[key]; } } for (const key of Object.keys(schema)) { if (!RECOGNIZED_KEYS.has(key)) { extraMeta[key] = schema[key]; } } if (Object.keys(extraMeta).length > 0) { ctx.registry.add(baseSchema, extraMeta); } return baseSchema; } function fromJSONSchema(schema, params) { if (typeof schema === "boolean") { return schema ? z.any() : z.never(); } const version2 = detectVersion(schema, params?.defaultTarget); const defs = schema.$defs || schema.definitions || {}; const ctx = { version: version2, defs, refs: /* @__PURE__ */ new Map(), processing: /* @__PURE__ */ new Set(), rootSchema: schema, registry: params?.registry ?? globalRegistry }; return convertSchema(schema, ctx); } // node_modules/zod/v4/classic/coerce.js var coerce_exports = {}; __export(coerce_exports, { bigint: () => bigint3, boolean: () => boolean3, date: () => date4, number: () => number3, string: () => string3 }); function string3(params) { return _coercedString(ZodString, params); } function number3(params) { return _coercedNumber(ZodNumber, params); } function boolean3(params) { return _coercedBoolean(ZodBoolean, params); } function bigint3(params) { return _coercedBigint(ZodBigInt, params); } function date4(params) { return _coercedDate(ZodDate, params); } // node_modules/zod/v4/classic/external.js config(en_default()); // node_modules/zod/index.js var zod_default = external_exports; // node_modules/zod/v3/helpers/util.js var util; (function(util2) { util2.assertEqual = (_) => { }; function assertIs2(_arg) { } util2.assertIs = assertIs2; function assertNever2(_x) { throw new Error(); } util2.assertNever = assertNever2; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e) { return obj[e]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { const keys = []; for (const key in object3) { if (Object.prototype.hasOwnProperty.call(object3, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues2(array2, separator = " | ") { return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues2; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType2 = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; // node_modules/zod/v3/ZodError.js var ZodIssueCode2 = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var ZodError2 = class _ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue2) { return issue2.message; }; const fieldErrors = { _errors: [] }; const processError = (error48) => { for (const issue2 of error48.issues) { if (issue2.code === "invalid_union") { issue2.unionErrors.map(processError); } else if (issue2.code === "invalid_return_type") { processError(issue2.returnTypeError); } else if (issue2.code === "invalid_arguments") { processError(issue2.argumentsError); } else if (issue2.path.length === 0) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; let i = 0; while (i < issue2.path.length) { const el = issue2.path[i]; const terminal = i === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue2) => issue2.message) { const fieldErrors = /* @__PURE__ */ Object.create(null); const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { const firstEl = sub.path[0]; fieldErrors[firstEl] = fieldErrors[firstEl] || []; fieldErrors[firstEl].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError2.create = (issues) => { const error48 = new ZodError2(issues); return error48; }; // node_modules/zod/v3/locales/en.js var errorMap = (issue2, _ctx) => { let message; switch (issue2.code) { case ZodIssueCode2.invalid_type: if (issue2.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue2.expected}, received ${issue2.received}`; } break; case ZodIssueCode2.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode2.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; break; case ZodIssueCode2.invalid_union: message = `Invalid input`; break; case ZodIssueCode2.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; break; case ZodIssueCode2.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; break; case ZodIssueCode2.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode2.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode2.invalid_date: message = `Invalid date`; break; case ZodIssueCode2.invalid_string: if (typeof issue2.validation === "object") { if ("includes" in issue2.validation) { message = `Invalid input: must include "${issue2.validation.includes}"`; if (typeof issue2.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; } } else if ("startsWith" in issue2.validation) { message = `Invalid input: must start with "${issue2.validation.startsWith}"`; } else if ("endsWith" in issue2.validation) { message = `Invalid input: must end with "${issue2.validation.endsWith}"`; } else { util.assertNever(issue2.validation); } } else if (issue2.validation !== "regex") { message = `Invalid ${issue2.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode2.too_small: if (issue2.type === "array") message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; else if (issue2.type === "string") message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; else if (issue2.type === "number") message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; else if (issue2.type === "bigint") message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; else if (issue2.type === "date") message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode2.too_big: if (issue2.type === "array") message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; else if (issue2.type === "string") message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; else if (issue2.type === "number") message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; else if (issue2.type === "bigint") message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; else if (issue2.type === "date") message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode2.custom: message = `Invalid input`; break; case ZodIssueCode2.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode2.not_multiple_of: message = `Number must be a multiple of ${issue2.multipleOf}`; break; case ZodIssueCode2.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue2); } return { message }; }; var en_default2 = errorMap; // node_modules/zod/v3/errors.js var overrideErrorMap = en_default2; function getErrorMap2() { return overrideErrorMap; } // node_modules/zod/v3/helpers/parseUtil.js var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) { return { ...issueData, path: fullPath, message: issueData.message }; } let errorMessage = ""; const maps = errorMaps.filter((m) => !!m).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap2(); const issue2 = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === en_default2 ? void 0 : en_default2 // then global default map ].filter((x) => !!x) }); ctx.common.issues.push(issue2); } var ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value }); } return _ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } }; var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x) => x.status === "aborted"; var isDirty = (x) => x.status === "dirty"; var isValid = (x) => x.status === "valid"; var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; // node_modules/zod/v3/helpers/errorUtil.js var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); // node_modules/zod/v3/types.js var ParseInputLazyPath = class { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; var handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error48 = new ZodError2(ctx.common.issues); this._error = error48; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType2 = class { get description() { return this._def.description; } _getType(input) { return getParsedType2(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType2(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType2(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { const ctx = { common: { issues: [], async: params?.async ?? false, contextualErrorMap: params?.errorMap }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType2(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } "~validate"(data) { const ctx = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType2(data) }; if (!this["~standard"].async) { try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; } catch (err) { if (err?.message?.toLowerCase()?.includes("encountered")) { this["~standard"].async = true; } ctx.common = { issues: [], async: true }; } } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params?.errorMap, async: true }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType2(data) }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check2, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check2(val); const setError = () => ctx.addIssue({ code: ZodIssueCode2.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check2, refinementData) { return this._refinement((val, ctx) => { if (!check2(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind2.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data) }; } optional() { return ZodOptional2.create(this, this._def); } nullable() { return ZodNullable2.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray2.create(this); } promise() { return ZodPromise2.create(this, this._def); } or(option) { return ZodUnion2.create([this, option], this._def); } and(incoming) { return ZodIntersection2.create(this, incoming, this._def); } transform(transform2) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind2.ZodEffects, effect: { type: "transform", transform: transform2 } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault2({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind2.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind2.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch2({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind2.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly2.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[0-9a-z]+$/; var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; var nanoidRegex = /^[a-z0-9_-]{21}$/i; var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; var emojiRegex; var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; var dateRegex = new RegExp(`^${dateRegexSource}$`); function timeRegexSource(args) { let secondsRegexSource = `[0-5]\\d`; if (args.precision) { secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } else if (args.precision == null) { secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } const secondsQuantifier = args.precision ? "+" : "?"; return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } function isValidIP(ip, version2) { if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT2(jwt2, alg) { if (!jwtRegex.test(jwt2)) return false; try { const [header] = jwt2.split("."); if (!header) return false; const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base643)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && decoded?.typ !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version2) { if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { return true; } return false; } var ZodString2 = class _ZodString2 extends ZodType2 { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.length < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.length > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: check2.value, type: "string", inclusive: true, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "length") { const tooBig = input.data.length > check2.value; const tooSmall = input.data.length < check2.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: check2.value, type: "string", inclusive: true, exact: true, message: check2.message }); } status.dirty(); } } else if (check2.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "url") { try { new URL(input.data); } catch { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "regex") { check2.regex.lastIndex = 0; const testResult = check2.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "trim") { input.data = input.data.trim(); } else if (check2.kind === "includes") { if (!input.data.includes(check2.value, check2.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: { includes: check2.value, position: check2.position }, message: check2.message }); status.dirty(); } } else if (check2.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check2.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check2.kind === "startsWith") { if (!input.data.startsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: { startsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "endsWith") { if (!input.data.endsWith(check2.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: { endsWith: check2.value }, message: check2.message }); status.dirty(); } } else if (check2.kind === "datetime") { const regex = datetimeRegex(check2); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: "datetime", message: check2.message }); status.dirty(); } } else if (check2.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: "date", message: check2.message }); status.dirty(); } } else if (check2.kind === "time") { const regex = timeRegex(check2); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_string, validation: "time", message: check2.message }); status.dirty(); } } else if (check2.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "ip") { if (!isValidIP(input.data, check2.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "jwt") { if (!isValidJWT2(input.data, check2.alg)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "cidr") { if (!isValidCidr(input.data, check2.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else if (check2.kind === "base64url") { if (!base64urlRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode2.invalid_string, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } _regex(regex, validation, message) { return this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode2.invalid_string, ...errorUtil.errToObj(message) }); } _addCheck(check2) { return new _ZodString2({ ...this._def, checks: [...this._def.checks, check2] }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } nanoid(message) { return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } base64(message) { return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } base64url(message) { return this._addCheck({ kind: "base64url", ...errorUtil.errToObj(message) }); } jwt(options) { return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } cidr(options) { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof options?.precision === "undefined" ? null : options?.precision, offset: options?.offset ?? false, local: options?.local ?? false, ...errorUtil.errToObj(options?.message) }); } date(message) { return this._addCheck({ kind: "date", message }); } time(options) { if (typeof options === "string") { return this._addCheck({ kind: "time", precision: null, message: options }); } return this._addCheck({ kind: "time", precision: typeof options?.precision === "undefined" ? null : options?.precision, ...errorUtil.errToObj(options?.message) }); } duration(message) { return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options?.position, ...errorUtil.errToObj(options?.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message) }); } /** * Equivalent to `.min(1)` */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); } toLowerCase() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); } toUpperCase() { return new _ZodString2({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isCIDR() { return !!this._def.checks.find((ch) => ch.kind === "cidr"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get isBase64url() { return !!this._def.checks.find((ch) => ch.kind === "base64url"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodString2.create = (params) => { return new ZodString2({ checks: [], typeName: ZodFirstPartyTypeKind2.ZodString, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; function floatSafeRemainder2(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / 10 ** decCount; } var ZodNumber2 = class _ZodNumber extends ZodType2 { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check2 of this._def.checks) { if (check2.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: "integer", received: "float", message: check2.message }); status.dirty(); } } else if (check2.kind === "min") { const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: check2.value, type: "number", inclusive: check2.inclusive, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: check2.value, type: "number", inclusive: check2.inclusive, exact: false, message: check2.message }); status.dirty(); } } else if (check2.kind === "multipleOf") { if (floatSafeRemainder2(input.data, check2.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.not_multiple_of, multipleOf: check2.value, message: check2.message }); status.dirty(); } } else if (check2.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.not_finite, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check2) { return new _ZodNumber({ ...this._def, checks: [...this._def.checks, check2] }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message) }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message) }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } get isFinite() { let max = null; let min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } }; ZodNumber2.create = (params) => { return new ZodNumber2({ checks: [], typeName: ZodFirstPartyTypeKind2.ZodNumber, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodBigInt2 = class _ZodBigInt extends ZodType2 { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { try { input.data = BigInt(input.data); } catch { return this._getInvalidInput(input); } } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.bigint) { return this._getInvalidInput(input); } let ctx = void 0; const status = new ParseStatus(); for (const check2 of this._def.checks) { if (check2.kind === "min") { const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, type: "bigint", minimum: check2.value, inclusive: check2.inclusive, message: check2.message }); status.dirty(); } } else if (check2.kind === "max") { const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, type: "bigint", maximum: check2.value, inclusive: check2.inclusive, message: check2.message }); status.dirty(); } } else if (check2.kind === "multipleOf") { if (input.data % check2.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.not_multiple_of, multipleOf: check2.value, message: check2.message }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: input.data }; } _getInvalidInput(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType }); return INVALID; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new _ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check2) { return new _ZodBigInt({ ...this._def, checks: [...this._def.checks, check2] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodBigInt2.create = (params) => { return new ZodBigInt2({ checks: [], typeName: ZodFirstPartyTypeKind2.ZodBigInt, coerce: params?.coerce ?? false, ...processCreateParams(params) }); }; var ZodBoolean2 = class extends ZodType2 { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodBoolean2.create = (params) => { return new ZodBoolean2({ typeName: ZodFirstPartyTypeKind2.ZodBoolean, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodDate2 = class _ZodDate extends ZodType2 { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (Number.isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check2 of this._def.checks) { if (check2.kind === "min") { if (input.data.getTime() < check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_small, message: check2.message, inclusive: true, exact: false, minimum: check2.value, type: "date" }); status.dirty(); } } else if (check2.kind === "max") { if (input.data.getTime() > check2.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode2.too_big, message: check2.message, inclusive: true, exact: false, maximum: check2.value, type: "date" }); status.dirty(); } } else { util.assertNever(check2); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check2) { return new _ZodDate({ ...this._def, checks: [...this._def.checks, check2] }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message) }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message) }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } }; ZodDate2.create = (params) => { return new ZodDate2({ checks: [], coerce: params?.coerce || false, typeName: ZodFirstPartyTypeKind2.ZodDate, ...processCreateParams(params) }); }; var ZodSymbol2 = class extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodSymbol2.create = (params) => { return new ZodSymbol2({ typeName: ZodFirstPartyTypeKind2.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined2 = class extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodUndefined2.create = (params) => { return new ZodUndefined2({ typeName: ZodFirstPartyTypeKind2.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull2 = class extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodNull2.create = (params) => { return new ZodNull2({ typeName: ZodFirstPartyTypeKind2.ZodNull, ...processCreateParams(params) }); }; var ZodAny2 = class extends ZodType2 { constructor() { super(...arguments); this._any = true; } _parse(input) { return OK(input.data); } }; ZodAny2.create = (params) => { return new ZodAny2({ typeName: ZodFirstPartyTypeKind2.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown2 = class extends ZodType2 { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return OK(input.data); } }; ZodUnknown2.create = (params) => { return new ZodUnknown2({ typeName: ZodFirstPartyTypeKind2.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever2 = class extends ZodType2 { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType }); return INVALID; } }; ZodNever2.create = (params) => { return new ZodNever2({ typeName: ZodFirstPartyTypeKind2.ZodNever, ...processCreateParams(params) }); }; var ZodVoid2 = class extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodVoid2.create = (params) => { return new ZodVoid2({ typeName: ZodFirstPartyTypeKind2.ZodVoid, ...processCreateParams(params) }); }; var ZodArray2 = class _ZodArray extends ZodType2 { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, minimum: tooSmall ? def.exactLength.value : void 0, maximum: tooBig ? def.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: def.exactLength.message }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new _ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new _ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new _ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray2.create = (schema, params) => { return new ZodArray2({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind2.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema) { if (schema instanceof ZodObject2) { const newShape = {}; for (const key in schema.shape) { const fieldSchema = schema.shape[key]; newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema)); } return new ZodObject2({ ...schema._def, shape: () => newShape }); } else if (schema instanceof ZodArray2) { return new ZodArray2({ ...schema._def, type: deepPartialify(schema.element) }); } else if (schema instanceof ZodOptional2) { return ZodOptional2.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodNullable2) { return ZodNullable2.create(deepPartialify(schema.unwrap())); } else if (schema instanceof ZodTuple2) { return ZodTuple2.create(schema.items.map((item) => deepPartialify(item))); } else { return schema; } } var ZodObject2 = class _ZodObject extends ZodType2 { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever2) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode2.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse( new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new _ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue2, ctx) => { const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; if (issue2.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new _ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new _ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind2.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema) { return this.augment({ [key]: schema }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index) { return new _ZodObject({ ...this._def, catchall: index }); } pick(mask) { const shape = {}; for (const key of util.objectKeys(mask)) { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; for (const key of util.objectKeys(this.shape)) { if (!mask[key]) { shape[key] = this.shape[key]; } } return new _ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new _ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional2) { newField = newField._def.innerType; } newShape[key] = newField; } } return new _ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject2.create = (shape, params) => { return new ZodObject2({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever2.create(), typeName: ZodFirstPartyTypeKind2.ZodObject, ...processCreateParams(params) }); }; ZodObject2.strictCreate = (shape, params) => { return new ZodObject2({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever2.create(), typeName: ZodFirstPartyTypeKind2.ZodObject, ...processCreateParams(params) }); }; ZodObject2.lazycreate = (shape, params) => { return new ZodObject2({ shape, unknownKeys: "strip", catchall: ZodNever2.create(), typeName: ZodFirstPartyTypeKind2.ZodObject, ...processCreateParams(params) }); }; var ZodUnion2 = class extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError2(issues2)); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion2.create = (types, params) => { return new ZodUnion2({ options: types, typeName: ZodFirstPartyTypeKind2.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type) => { if (type instanceof ZodLazy2) { return getDiscriminator(type.schema); } else if (type instanceof ZodEffects) { return getDiscriminator(type.innerType()); } else if (type instanceof ZodLiteral2) { return [type.value]; } else if (type instanceof ZodEnum2) { return type.options; } else if (type instanceof ZodNativeEnum) { return util.objectValues(type.enum); } else if (type instanceof ZodDefault2) { return getDiscriminator(type._def.innerType); } else if (type instanceof ZodUndefined2) { return [void 0]; } else if (type instanceof ZodNull2) { return [null]; } else if (type instanceof ZodOptional2) { return [void 0, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable2) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly2) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch2) { return getDiscriminator(type._def.innerType); } else { return []; } }; var ZodDiscriminatedUnion2 = class _ZodDiscriminatedUnion extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new _ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; function mergeValues2(a, b) { const aType = getParsedType2(a); const bType = getParsedType2(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b); const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues2(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a.length !== b.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; const itemB = b[index]; const sharedValue = mergeValues2(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } var ZodIntersection2 = class extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues2(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; ZodIntersection2.create = (left, right, params) => { return new ZodIntersection2({ left, right, typeName: ZodFirstPartyTypeKind2.ZodIntersection, ...processCreateParams(params) }); }; var ZodTuple2 = class _ZodTuple extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x) => !!x); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new _ZodTuple({ ...this._def, rest }); } }; ZodTuple2.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple2({ items: schemas, typeName: ZodFirstPartyTypeKind2.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord2 = class _ZodRecord extends ZodType2 { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType2) { return new _ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind2.ZodRecord, ...processCreateParams(third) }); } return new _ZodRecord({ keyType: ZodString2.create(), valueType: first, typeName: ZodFirstPartyTypeKind2.ZodRecord, ...processCreateParams(second) }); } }; var ZodMap2 = class extends ZodType2 { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; ZodMap2.create = (keyType, valueType, params) => { return new ZodMap2({ valueType, keyType, typeName: ZodFirstPartyTypeKind2.ZodMap, ...processCreateParams(params) }); }; var ZodSet2 = class _ZodSet extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode2.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode2.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new _ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new _ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; ZodSet2.create = (valueType, params) => { return new ZodSet2({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind2.ZodSet, ...processCreateParams(params) }); }; var ZodFunction2 = class _ZodFunction extends ZodType2 { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error48) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), issueData: { code: ZodIssueCode2.invalid_arguments, argumentsError: error48 } }); } function makeReturnsIssue(returns, error48) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), issueData: { code: ZodIssueCode2.invalid_return_type, returnTypeError: error48 } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise2) { const me = this; return OK(async function(...args) { const error48 = new ZodError2([]); const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { error48.addIssue(makeArgsIssue(args, e)); throw error48; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { error48.addIssue(makeReturnsIssue(result, e)); throw error48; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new _ZodFunction({ ...this._def, args: ZodTuple2.create(items).rest(ZodUnknown2.create()) }); } returns(returnType) { return new _ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new _ZodFunction({ args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), returns: returns || ZodUnknown2.create(), typeName: ZodFirstPartyTypeKind2.ZodFunction, ...processCreateParams(params) }); } }; var ZodLazy2 = class extends ZodType2 { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy2.create = (getter, params) => { return new ZodLazy2({ getter, typeName: ZodFirstPartyTypeKind2.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral2 = class extends ZodType2 { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode2.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; ZodLiteral2.create = (value, params) => { return new ZodLiteral2({ value, typeName: ZodFirstPartyTypeKind2.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum2({ values, typeName: ZodFirstPartyTypeKind2.ZodEnum, ...processCreateParams(params) }); } var ZodEnum2 = class _ZodEnum extends ZodType2 { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode2.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(this._def.values); } if (!this._cache.has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode2.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values, newDef = this._def) { return _ZodEnum.create(values, { ...this._def, ...newDef }); } exclude(values, newDef = this._def) { return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef }); } }; ZodEnum2.create = createZodEnum; var ZodNativeEnum = class extends ZodType2 { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode2.invalid_type }); return INVALID; } if (!this._cache) { this._cache = new Set(util.getValidEnumValues(this._def.values)); } if (!this._cache.has(input.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode2.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } }; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise2 = class extends ZodType2 { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; ZodPromise2.create = (schema, params) => { return new ZodPromise2({ type: schema, typeName: ZodFirstPartyTypeKind2.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends ZodType2 { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base)) return INVALID; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return INVALID; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind2.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess2 }, typeName: ZodFirstPartyTypeKind2.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional2 = class extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional2.create = (type, params) => { return new ZodOptional2({ innerType: type, typeName: ZodFirstPartyTypeKind2.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable2 = class extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable2.create = (type, params) => { return new ZodNullable2({ innerType: type, typeName: ZodFirstPartyTypeKind2.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault2 = class extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } }; ZodDefault2.create = (type, params) => { return new ZodDefault2({ innerType: type, typeName: ZodFirstPartyTypeKind2.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; var ZodCatch2 = class extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError2(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError2(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch2.create = (type, params) => { return new ZodCatch2({ innerType: type, typeName: ZodFirstPartyTypeKind2.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; var ZodNaN2 = class extends ZodType2 { _parse(input) { const parsedType2 = this._getType(input); if (parsedType2 !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode2.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } }; ZodNaN2.create = (params) => { return new ZodNaN2({ typeName: ZodFirstPartyTypeKind2.ZodNaN, ...processCreateParams(params) }); }; var BRAND = Symbol("zod_brand"); var ZodBranded = class extends ZodType2 { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; var ZodPipeline = class _ZodPipeline extends ZodType2 { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a, b) { return new _ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind2.ZodPipeline }); } }; var ZodReadonly2 = class extends ZodType2 { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } }; ZodReadonly2.create = (type, params) => { return new ZodReadonly2({ innerType: type, typeName: ZodFirstPartyTypeKind2.ZodReadonly, ...processCreateParams(params) }); }; var late = { object: ZodObject2.lazycreate }; var ZodFirstPartyTypeKind2; (function(ZodFirstPartyTypeKind3) { ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); var stringType = ZodString2.create; var numberType = ZodNumber2.create; var nanType = ZodNaN2.create; var bigIntType = ZodBigInt2.create; var booleanType = ZodBoolean2.create; var dateType = ZodDate2.create; var symbolType = ZodSymbol2.create; var undefinedType = ZodUndefined2.create; var nullType = ZodNull2.create; var anyType = ZodAny2.create; var unknownType = ZodUnknown2.create; var neverType = ZodNever2.create; var voidType = ZodVoid2.create; var arrayType = ZodArray2.create; var objectType = ZodObject2.create; var strictObjectType = ZodObject2.strictCreate; var unionType = ZodUnion2.create; var discriminatedUnionType = ZodDiscriminatedUnion2.create; var intersectionType = ZodIntersection2.create; var tupleType = ZodTuple2.create; var recordType = ZodRecord2.create; var mapType = ZodMap2.create; var setType = ZodSet2.create; var functionType = ZodFunction2.create; var lazyType = ZodLazy2.create; var literalType = ZodLiteral2.create; var enumType = ZodEnum2.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise2.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional2.create; var nullableType = ZodNullable2.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js function isZ4Schema(s) { const schema = s; return !!schema._zod; } function safeParse3(schema, data) { if (isZ4Schema(schema)) { const result2 = safeParse(schema, data); return result2; } const v3Schema = schema; const result = v3Schema.safeParse(data); return result; } function getObjectShape(schema) { if (!schema) return void 0; let rawShape; if (isZ4Schema(schema)) { const v4Schema = schema; rawShape = v4Schema._zod?.def?.shape; } else { const v3Schema = schema; rawShape = v3Schema.shape; } if (!rawShape) return void 0; if (typeof rawShape === "function") { try { return rawShape(); } catch { return void 0; } } return rawShape; } function getLiteralValue(schema) { if (isZ4Schema(schema)) { const v4Schema = schema; const def2 = v4Schema._zod?.def; if (def2) { if (def2.value !== void 0) return def2.value; if (Array.isArray(def2.values) && def2.values.length > 0) { return def2.values[0]; } } } const v3Schema = schema; const def = v3Schema._def; if (def) { if (def.value !== void 0) return def.value; if (Array.isArray(def.values) && def.values.length > 0) { return def.values[0]; } } const directValue = schema.value; if (directValue !== void 0) return directValue; return void 0; } // node_modules/@modelcontextprotocol/sdk/dist/esm/types.js var LATEST_PROTOCOL_VERSION = "2025-11-25"; var DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"]; var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; var JSONRPC_VERSION = "2.0"; var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function")); var ProgressTokenSchema = union([string2(), number2().int()]); var CursorSchema = string2(); var TaskCreationParamsSchema = looseObject({ /** * Requested duration in milliseconds to retain task from creation. */ ttl: number2().optional(), /** * Time in milliseconds to wait between task status requests. */ pollInterval: number2().optional() }); var TaskMetadataSchema = object({ ttl: number2().optional() }); var RelatedTaskMetadataSchema = object({ taskId: string2() }); var RequestMetaSchema = looseObject({ /** * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. */ progressToken: ProgressTokenSchema.optional(), /** * If specified, this request is related to the provided task. */ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() }); var BaseRequestParamsSchema = object({ /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ _meta: RequestMetaSchema.optional() }); var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * If specified, the caller is requesting task-augmented execution for this request. * The request will return a CreateTaskResult immediately, and the actual result can be * retrieved later via tasks/result. * * Task augmentation is subject to capability negotiation - receivers MUST declare support * for task augmentation of specific request types in their capabilities. */ task: TaskMetadataSchema.optional() }); var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; var RequestSchema = object({ method: string2(), params: BaseRequestParamsSchema.loose().optional() }); var NotificationsParamsSchema = object({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); var NotificationSchema = object({ method: string2(), params: NotificationsParamsSchema.loose().optional() }); var ResultSchema = looseObject({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); var RequestIdSchema = union([string2(), number2().int()]); var JSONRPCRequestSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, ...RequestSchema.shape }).strict(); var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; var JSONRPCNotificationSchema = object({ jsonrpc: literal(JSONRPC_VERSION), ...NotificationSchema.shape }).strict(); var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; var JSONRPCResultResponseSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, result: ResultSchema }).strict(); var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; var ErrorCode; (function(ErrorCode2) { ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; })(ErrorCode || (ErrorCode = {})); var JSONRPCErrorResponseSchema = object({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema.optional(), error: object({ /** * The error type that occurred. */ code: number2().int(), /** * A short description of the error. The message SHOULD be limited to a concise single sentence. */ message: string2(), /** * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ data: unknown().optional() }) }).strict(); var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; var JSONRPCMessageSchema = union([ JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema ]); var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); var EmptyResultSchema = ResultSchema.strict(); var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the request to cancel. * * This MUST correspond to the ID of a request previously issued in the same direction. */ requestId: RequestIdSchema.optional(), /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. */ reason: string2().optional() }); var CancelledNotificationSchema = NotificationSchema.extend({ method: literal("notifications/cancelled"), params: CancelledNotificationParamsSchema }); var IconSchema = object({ /** * URL or data URI for the icon. */ src: string2(), /** * Optional MIME type for the icon. */ mimeType: string2().optional(), /** * Optional array of strings that specify sizes at which the icon can be used. * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. * * If not provided, the client should assume that the icon can be used at any size. */ sizes: array(string2()).optional(), /** * Optional specifier for the theme this icon is designed for. `light` indicates * the icon is designed to be used with a light background, and `dark` indicates * the icon is designed to be used with a dark background. * * If not provided, the client should assume the icon can be used with any theme. */ theme: _enum2(["light", "dark"]).optional() }); var IconsSchema = object({ /** * Optional set of sized icons that the client can display in a user interface. * * Clients that support rendering icons MUST support at least the following MIME types: * - `image/png` - PNG images (safe, universal compatibility) * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) * * Clients that support rendering icons SHOULD also support: * - `image/svg+xml` - SVG images (scalable but requires security precautions) * - `image/webp` - WebP images (modern, efficient format) */ icons: array(IconSchema).optional() }); var BaseMetadataSchema = object({ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ name: string2(), /** * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, * even by those unfamiliar with domain-specific terminology. * * If not provided, the name should be used for display (except for Tool, * where `annotations.title` should be given precedence over using `name`, * if present). */ title: string2().optional() }); var ImplementationSchema = BaseMetadataSchema.extend({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, version: string2(), /** * An optional URL of the website for this implementation. */ websiteUrl: string2().optional(), /** * An optional human-readable description of what this implementation does. * * This can be used by clients or servers to provide context about their purpose * and capabilities. For example, a server might describe the types of resources * or tools it provides, while a client might describe its intended use case. */ description: string2().optional() }); var FormElicitationCapabilitySchema = intersection(object({ applyDefaults: boolean2().optional() }), record(string2(), unknown())); var ElicitationCapabilitySchema = preprocess((value) => { if (value && typeof value === "object" && !Array.isArray(value)) { if (Object.keys(value).length === 0) { return { form: {} }; } } return value; }, intersection(object({ form: FormElicitationCapabilitySchema.optional(), url: AssertObjectSchema.optional() }), record(string2(), unknown()).optional())); var ClientTasksCapabilitySchema = looseObject({ /** * Present if the client supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the client supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for sampling requests. */ sampling: looseObject({ createMessage: AssertObjectSchema.optional() }).optional(), /** * Task support for elicitation requests. */ elicitation: looseObject({ create: AssertObjectSchema.optional() }).optional() }).optional() }); var ServerTasksCapabilitySchema = looseObject({ /** * Present if the server supports listing tasks. */ list: AssertObjectSchema.optional(), /** * Present if the server supports cancelling tasks. */ cancel: AssertObjectSchema.optional(), /** * Capabilities for task creation on specific request types. */ requests: looseObject({ /** * Task support for tool requests. */ tools: looseObject({ call: AssertObjectSchema.optional() }).optional() }).optional() }); var ClientCapabilitiesSchema = object({ /** * Experimental, non-standard capabilities that the client supports. */ experimental: record(string2(), AssertObjectSchema).optional(), /** * Present if the client supports sampling from an LLM. */ sampling: object({ /** * Present if the client supports context inclusion via includeContext parameter. * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). */ context: AssertObjectSchema.optional(), /** * Present if the client supports tool use via tools and toolChoice parameters. */ tools: AssertObjectSchema.optional() }).optional(), /** * Present if the client supports eliciting user input. */ elicitation: ElicitationCapabilitySchema.optional(), /** * Present if the client supports listing roots. */ roots: object({ /** * Whether the client supports issuing notifications for changes to the roots list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the client supports task creation. */ tasks: ClientTasksCapabilitySchema.optional(), /** * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(string2(), AssertObjectSchema).optional() }); var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. */ protocolVersion: string2(), capabilities: ClientCapabilitiesSchema, clientInfo: ImplementationSchema }); var InitializeRequestSchema = RequestSchema.extend({ method: literal("initialize"), params: InitializeRequestParamsSchema }); var isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; var ServerCapabilitiesSchema = object({ /** * Experimental, non-standard capabilities that the server supports. */ experimental: record(string2(), AssertObjectSchema).optional(), /** * Present if the server supports sending log messages to the client. */ logging: AssertObjectSchema.optional(), /** * Present if the server supports sending completions to the client. */ completions: AssertObjectSchema.optional(), /** * Present if the server offers any prompt templates. */ prompts: object({ /** * Whether this server supports issuing notifications for changes to the prompt list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server offers any resources to read. */ resources: object({ /** * Whether this server supports clients subscribing to resource updates. */ subscribe: boolean2().optional(), /** * Whether this server supports issuing notifications for changes to the resource list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server offers any tools to call. */ tools: object({ /** * Whether this server supports issuing notifications for changes to the tool list. */ listChanged: boolean2().optional() }).optional(), /** * Present if the server supports task creation. */ tasks: ServerTasksCapabilitySchema.optional(), /** * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). */ extensions: record(string2(), AssertObjectSchema).optional() }); var InitializeResultSchema = ResultSchema.extend({ /** * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. */ protocolVersion: string2(), capabilities: ServerCapabilitiesSchema, serverInfo: ImplementationSchema, /** * Instructions describing how to use the server and its features. * * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. */ instructions: string2().optional() }); var InitializedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/initialized"), params: NotificationsParamsSchema.optional() }); var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; var PingRequestSchema = RequestSchema.extend({ method: literal("ping"), params: BaseRequestParamsSchema.optional() }); var ProgressSchema = object({ /** * The progress thus far. This should increase every time progress is made, even if the total is unknown. */ progress: number2(), /** * Total number of items to process (or total progress required), if known. */ total: optional(number2()), /** * An optional message describing the current progress. */ message: optional(string2()) }); var ProgressNotificationParamsSchema = object({ ...NotificationsParamsSchema.shape, ...ProgressSchema.shape, /** * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. */ progressToken: ProgressTokenSchema }); var ProgressNotificationSchema = NotificationSchema.extend({ method: literal("notifications/progress"), params: ProgressNotificationParamsSchema }); var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * An opaque token representing the current pagination position. * If provided, the server should return results starting after this cursor. */ cursor: CursorSchema.optional() }); var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); var PaginatedResultSchema = ResultSchema.extend({ /** * An opaque token representing the pagination position after the last returned result. * If present, there may be more results available. */ nextCursor: CursorSchema.optional() }); var TaskStatusSchema = _enum2(["working", "input_required", "completed", "failed", "cancelled"]); var TaskSchema = object({ taskId: string2(), status: TaskStatusSchema, /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. */ ttl: union([number2(), _null3()]), /** * ISO 8601 timestamp when the task was created. */ createdAt: string2(), /** * ISO 8601 timestamp when the task was last updated. */ lastUpdatedAt: string2(), pollInterval: optional(number2()), /** * Optional diagnostic message for failed tasks or other status information. */ statusMessage: optional(string2()) }); var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); var TaskStatusNotificationSchema = NotificationSchema.extend({ method: literal("notifications/tasks/status"), params: TaskStatusNotificationParamsSchema }); var GetTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/get"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var GetTaskResultSchema = ResultSchema.merge(TaskSchema); var GetTaskPayloadRequestSchema = RequestSchema.extend({ method: literal("tasks/result"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var GetTaskPayloadResultSchema = ResultSchema.loose(); var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); var ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); var CancelTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/cancel"), params: BaseRequestParamsSchema.extend({ taskId: string2() }) }); var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); var ResourceContentsSchema = object({ /** * The URI of this resource. */ uri: string2(), /** * The MIME type of this resource, if known. */ mimeType: optional(string2()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var TextResourceContentsSchema = ResourceContentsSchema.extend({ /** * The text of the item. This must only be set if the item can actually be represented as text (not binary data). */ text: string2() }); var Base64Schema = string2().refine((val) => { try { atob(val); return true; } catch { return false; } }, { message: "Invalid Base64 string" }); var BlobResourceContentsSchema = ResourceContentsSchema.extend({ /** * A base64-encoded string representing the binary data of the item. */ blob: Base64Schema }); var RoleSchema = _enum2(["user", "assistant"]); var AnnotationsSchema = object({ /** * Intended audience(s) for the resource. */ audience: array(RoleSchema).optional(), /** * Importance hint for the resource, from 0 (least) to 1 (most). */ priority: number2().min(0).max(1).optional(), /** * ISO 8601 timestamp for the most recent modification. */ lastModified: iso_exports.datetime({ offset: true }).optional() }); var ResourceSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * The URI of this resource. */ uri: string2(), /** * A description of what this resource represents. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ description: optional(string2()), /** * The MIME type of this resource, if known. */ mimeType: optional(string2()), /** * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. * * This can be used by Hosts to display file sizes and estimate context window usage. */ size: optional(number2()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ResourceTemplateSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A URI template (according to RFC 6570) that can be used to construct resource URIs. */ uriTemplate: string2(), /** * A description of what this template is for. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ description: optional(string2()), /** * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. */ mimeType: optional(string2()), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); var ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. * * @format uri */ uri: string2() }); var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; var ReadResourceRequestSchema = RequestSchema.extend({ method: literal("resources/read"), params: ReadResourceRequestParamsSchema }); var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); var ResourceListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/list_changed"), params: NotificationsParamsSchema.optional() }); var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; var SubscribeRequestSchema = RequestSchema.extend({ method: literal("resources/subscribe"), params: SubscribeRequestParamsSchema }); var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; var UnsubscribeRequestSchema = RequestSchema.extend({ method: literal("resources/unsubscribe"), params: UnsubscribeRequestParamsSchema }); var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. */ uri: string2() }); var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/updated"), params: ResourceUpdatedNotificationParamsSchema }); var PromptArgumentSchema = object({ /** * The name of the argument. */ name: string2(), /** * A human-readable description of the argument. */ description: optional(string2()), /** * Whether this argument must be provided. */ required: optional(boolean2()) }); var PromptSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * An optional description of what this prompt provides */ description: optional(string2()), /** * A list of arguments to use for templating the prompt. */ arguments: optional(array(PromptArgumentSchema)), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: optional(looseObject({})) }); var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The name of the prompt or prompt template. */ name: string2(), /** * Arguments to use for templating the prompt. */ arguments: record(string2(), string2()).optional() }); var GetPromptRequestSchema = RequestSchema.extend({ method: literal("prompts/get"), params: GetPromptRequestParamsSchema }); var TextContentSchema = object({ type: literal("text"), /** * The text content of the message. */ text: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ImageContentSchema = object({ type: literal("image"), /** * The base64-encoded image data. */ data: Base64Schema, /** * The MIME type of the image. Different providers may support different image types. */ mimeType: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var AudioContentSchema = object({ type: literal("audio"), /** * The base64-encoded audio data. */ data: Base64Schema, /** * The MIME type of the audio. Different providers may support different audio types. */ mimeType: string2(), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ToolUseContentSchema = object({ type: literal("tool_use"), /** * The name of the tool to invoke. * Must match a tool name from the request's tools array. */ name: string2(), /** * Unique identifier for this tool call. * Used to correlate with ToolResultContent in subsequent messages. */ id: string2(), /** * Arguments to pass to the tool. * Must conform to the tool's inputSchema. */ input: record(string2(), unknown()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var EmbeddedResourceSchema = object({ type: literal("resource"), resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), /** * Optional annotations for the client. */ annotations: AnnotationsSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); var ContentBlockSchema = union([ TextContentSchema, ImageContentSchema, AudioContentSchema, ResourceLinkSchema, EmbeddedResourceSchema ]); var PromptMessageSchema = object({ role: RoleSchema, content: ContentBlockSchema }); var GetPromptResultSchema = ResultSchema.extend({ /** * An optional description for the prompt. */ description: string2().optional(), messages: array(PromptMessageSchema) }); var PromptListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/prompts/list_changed"), params: NotificationsParamsSchema.optional() }); var ToolAnnotationsSchema = object({ /** * A human-readable title for the tool. */ title: string2().optional(), /** * If true, the tool does not modify its environment. * * Default: false */ readOnlyHint: boolean2().optional(), /** * If true, the tool may perform destructive updates to its environment. * If false, the tool performs only additive updates. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: true */ destructiveHint: boolean2().optional(), /** * If true, calling the tool repeatedly with the same arguments * will have no additional effect on the its environment. * * (This property is meaningful only when `readOnlyHint == false`) * * Default: false */ idempotentHint: boolean2().optional(), /** * If true, this tool may interact with an "open world" of external * entities. If false, the tool's domain of interaction is closed. * For example, the world of a web search tool is open, whereas that * of a memory tool is not. * * Default: true */ openWorldHint: boolean2().optional() }); var ToolExecutionSchema = object({ /** * Indicates the tool's preference for task-augmented execution. * - "required": Clients MUST invoke the tool as a task * - "optional": Clients MAY invoke the tool as a task or normal request * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task * * If not present, defaults to "forbidden". */ taskSupport: _enum2(["required", "optional", "forbidden"]).optional() }); var ToolSchema = object({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A human-readable description of the tool. */ description: string2().optional(), /** * A JSON Schema 2020-12 object defining the expected parameters for the tool. * Must have type: 'object' at the root level per MCP spec. */ inputSchema: object({ type: literal("object"), properties: record(string2(), AssertObjectSchema).optional(), required: array(string2()).optional() }).catchall(unknown()), /** * An optional JSON Schema 2020-12 object defining the structure of the tool's output * returned in the structuredContent field of a CallToolResult. * Must have type: 'object' at the root level per MCP spec. */ outputSchema: object({ type: literal("object"), properties: record(string2(), AssertObjectSchema).optional(), required: array(string2()).optional() }).catchall(unknown()).optional(), /** * Optional additional tool information. */ annotations: ToolAnnotationsSchema.optional(), /** * Execution-related properties for this tool. */ execution: ToolExecutionSchema.optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); var CallToolResultSchema = ResultSchema.extend({ /** * A list of content objects that represent the result of the tool call. * * If the Tool does not define an outputSchema, this field MUST be present in the result. * For backwards compatibility, this field is always present, but it may be empty. */ content: array(ContentBlockSchema).default([]), /** * An object containing structured tool output. * * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. */ structuredContent: record(string2(), unknown()).optional(), /** * Whether the tool call ended in an error. * * If not set, this is assumed to be false (the call was successful). * * Any errors that originate from the tool SHOULD be reported inside the result * object, with `isError` set to true, _not_ as an MCP protocol-level error * response. Otherwise, the LLM would not be able to see that an error occurred * and self-correct. * * However, any errors in _finding_ the tool, an error indicating that the * server does not support tool calls, or any other exceptional conditions, * should be reported as an MCP error response. */ isError: boolean2().optional() }); var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The name of the tool to call. */ name: string2(), /** * Arguments to pass to the tool. */ arguments: record(string2(), unknown()).optional() }); var CallToolRequestSchema = RequestSchema.extend({ method: literal("tools/call"), params: CallToolRequestParamsSchema }); var ToolListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/tools/list_changed"), params: NotificationsParamsSchema.optional() }); var ListChangedOptionsBaseSchema = object({ /** * If true, the list will be refreshed automatically when a list changed notification is received. * The callback will be called with the updated list. * * If false, the callback will be called with null items, allowing manual refresh. * * @default true */ autoRefresh: boolean2().default(true), /** * Debounce time in milliseconds for list changed notification processing. * * Multiple notifications received within this timeframe will only trigger one refresh. * Set to 0 to disable debouncing. * * @default 300 */ debounceMs: number2().int().nonnegative().default(300) }); var LoggingLevelSchema = _enum2(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. */ level: LoggingLevelSchema }); var SetLevelRequestSchema = RequestSchema.extend({ method: literal("logging/setLevel"), params: SetLevelRequestParamsSchema }); var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The severity of this log message. */ level: LoggingLevelSchema, /** * An optional name of the logger issuing this message. */ logger: string2().optional(), /** * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. */ data: unknown() }); var LoggingMessageNotificationSchema = NotificationSchema.extend({ method: literal("notifications/message"), params: LoggingMessageNotificationParamsSchema }); var ModelHintSchema = object({ /** * A hint for a model name. */ name: string2().optional() }); var ModelPreferencesSchema = object({ /** * Optional hints to use for model selection. */ hints: array(ModelHintSchema).optional(), /** * How much to prioritize cost when selecting a model. */ costPriority: number2().min(0).max(1).optional(), /** * How much to prioritize sampling speed (latency) when selecting a model. */ speedPriority: number2().min(0).max(1).optional(), /** * How much to prioritize intelligence and capabilities when selecting a model. */ intelligencePriority: number2().min(0).max(1).optional() }); var ToolChoiceSchema = object({ /** * Controls when tools are used: * - "auto": Model decides whether to use tools (default) * - "required": Model MUST use at least one tool before completing * - "none": Model MUST NOT use any tools */ mode: _enum2(["auto", "required", "none"]).optional() }); var ToolResultContentSchema = object({ type: literal("tool_result"), toolUseId: string2().describe("The unique identifier for the corresponding tool call."), content: array(ContentBlockSchema).default([]), structuredContent: object({}).loose().optional(), isError: boolean2().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, ToolResultContentSchema ]); var SamplingMessageSchema = object({ role: RoleSchema, content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ messages: array(SamplingMessageSchema), /** * The server's preferences for which model to select. The client MAY modify or omit this request. */ modelPreferences: ModelPreferencesSchema.optional(), /** * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. */ systemPrompt: string2().optional(), /** * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. * The client MAY ignore this request. * * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. */ includeContext: _enum2(["none", "thisServer", "allServers"]).optional(), temperature: number2().optional(), /** * The requested maximum number of tokens to sample (to prevent runaway completions). * * The client MAY choose to sample fewer tokens than the requested maximum. */ maxTokens: number2().int(), stopSequences: array(string2()).optional(), /** * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. */ metadata: AssertObjectSchema.optional(), /** * Tools that the model may use during generation. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. */ tools: array(ToolSchema).optional(), /** * Controls how the model uses tools. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. * Default is `{ mode: "auto" }`. */ toolChoice: ToolChoiceSchema.optional() }); var CreateMessageRequestSchema = RequestSchema.extend({ method: literal("sampling/createMessage"), params: CreateMessageRequestParamsSchema }); var CreateMessageResultSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: string2(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string2())), role: RoleSchema, /** * Response content. Single content block (text, image, or audio). */ content: SamplingContentSchema }); var CreateMessageResultWithToolsSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ model: string2(), /** * The reason why sampling stopped, if known. * * Standard values: * - "endTurn": Natural end of the assistant's turn * - "stopSequence": A stop sequence was encountered * - "maxTokens": Maximum token limit was reached * - "toolUse": The model wants to use one or more tools * * This field is an open string to allow for provider-specific stop reasons. */ stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), role: RoleSchema, /** * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". */ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) }); var BooleanSchemaSchema = object({ type: literal("boolean"), title: string2().optional(), description: string2().optional(), default: boolean2().optional() }); var StringSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), minLength: number2().optional(), maxLength: number2().optional(), format: _enum2(["email", "uri", "date", "date-time"]).optional(), default: string2().optional() }); var NumberSchemaSchema = object({ type: _enum2(["number", "integer"]), title: string2().optional(), description: string2().optional(), minimum: number2().optional(), maximum: number2().optional(), default: number2().optional() }); var UntitledSingleSelectEnumSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), enum: array(string2()), default: string2().optional() }); var TitledSingleSelectEnumSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), oneOf: array(object({ const: string2(), title: string2() })), default: string2().optional() }); var LegacyTitledEnumSchemaSchema = object({ type: literal("string"), title: string2().optional(), description: string2().optional(), enum: array(string2()), enumNames: array(string2()).optional(), default: string2().optional() }); var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); var UntitledMultiSelectEnumSchemaSchema = object({ type: literal("array"), title: string2().optional(), description: string2().optional(), minItems: number2().optional(), maxItems: number2().optional(), items: object({ type: literal("string"), enum: array(string2()) }), default: array(string2()).optional() }); var TitledMultiSelectEnumSchemaSchema = object({ type: literal("array"), title: string2().optional(), description: string2().optional(), minItems: number2().optional(), maxItems: number2().optional(), items: object({ anyOf: array(object({ const: string2(), title: string2() })) }), default: array(string2()).optional() }); var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. * * Optional for backward compatibility. Clients MUST treat missing mode as "form". */ mode: literal("form").optional(), /** * The message to present to the user describing what information is being requested. */ message: string2(), /** * A restricted subset of JSON Schema. * Only top-level properties are allowed, without nesting. */ requestedSchema: object({ type: literal("object"), properties: record(string2(), PrimitiveSchemaDefinitionSchema), required: array(string2()).optional() }) }); var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The elicitation mode. */ mode: literal("url"), /** * The message to present to the user explaining why the interaction is needed. */ message: string2(), /** * The ID of the elicitation, which must be unique within the context of the server. * The client MUST treat this ID as an opaque value. */ elicitationId: string2(), /** * The URL that the user should navigate to. */ url: string2().url() }); var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); var ElicitRequestSchema = RequestSchema.extend({ method: literal("elicitation/create"), params: ElicitRequestParamsSchema }); var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The ID of the elicitation that completed. */ elicitationId: string2() }); var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ method: literal("notifications/elicitation/complete"), params: ElicitationCompleteNotificationParamsSchema }); var ElicitResultSchema = ResultSchema.extend({ /** * The user action in response to the elicitation. * - "accept": User submitted the form/confirmed the action * - "decline": User explicitly decline the action * - "cancel": User dismissed without making an explicit choice */ action: _enum2(["accept", "decline", "cancel"]), /** * The submitted form data, only present when action is "accept". * Contains values matching the requested schema. * Per MCP spec, content is "typically omitted" for decline/cancel actions. * We normalize null to undefined for leniency while maintaining type compatibility. */ content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) }); var ResourceTemplateReferenceSchema = object({ type: literal("ref/resource"), /** * The URI or URI template of the resource. */ uri: string2() }); var PromptReferenceSchema = object({ type: literal("ref/prompt"), /** * The name of the prompt or prompt template */ name: string2() }); var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), /** * The argument's information */ argument: object({ /** * The name of the argument */ name: string2(), /** * The value of the argument to use for completion matching. */ value: string2() }), context: object({ /** * Previously-resolved variables in a URI template or prompt. */ arguments: record(string2(), string2()).optional() }).optional() }); var CompleteRequestSchema = RequestSchema.extend({ method: literal("completion/complete"), params: CompleteRequestParamsSchema }); var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ /** * An array of completion values. Must not exceed 100 items. */ values: array(string2()).max(100), /** * The total number of completion options available. This can exceed the number of values actually sent in the response. */ total: optional(number2().int()), /** * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. */ hasMore: optional(boolean2()) }) }); var RootSchema = object({ /** * The URI identifying the root. This *must* start with file:// for now. */ uri: string2().startsWith("file://"), /** * An optional name for the root. */ name: string2().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: record(string2(), unknown()).optional() }); var ListRootsRequestSchema = RequestSchema.extend({ method: literal("roots/list"), params: BaseRequestParamsSchema.optional() }); var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); var RootsListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/roots/list_changed"), params: NotificationsParamsSchema.optional() }); var ClientRequestSchema = union([ PingRequestSchema, InitializeRequestSchema, CompleteRequestSchema, SetLevelRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, CallToolRequestSchema, ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); var ClientNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, InitializedNotificationSchema, RootsListChangedNotificationSchema, TaskStatusNotificationSchema ]); var ClientResultSchema = union([ EmptyResultSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, ListRootsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); var ServerRequestSchema = union([ PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, CancelTaskRequestSchema ]); var ServerNotificationSchema = union([ CancelledNotificationSchema, ProgressNotificationSchema, LoggingMessageNotificationSchema, ResourceUpdatedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, TaskStatusNotificationSchema, ElicitationCompleteNotificationSchema ]); var ServerResultSchema = union([ EmptyResultSchema, InitializeResultSchema, CompleteResultSchema, GetPromptResultSchema, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ReadResourceResultSchema, CallToolResultSchema, ListToolsResultSchema, GetTaskResultSchema, ListTasksResultSchema, CreateTaskResultSchema ]); var McpError = class _McpError extends Error { constructor(code, message, data) { super(`MCP error ${code}: ${message}`); this.code = code; this.data = data; this.name = "McpError"; } /** * Factory method to create the appropriate error type based on the error code and data */ static fromError(code, message, data) { if (code === ErrorCode.UrlElicitationRequired && data) { const errorData = data; if (errorData.elicitations) { return new UrlElicitationRequiredError(errorData.elicitations, message); } } return new _McpError(code, message, data); } }; var UrlElicitationRequiredError = class extends McpError { constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { super(ErrorCode.UrlElicitationRequired, message, { elicitations }); } get elicitations() { return this.data?.elicitations ?? []; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js function isTerminal(status) { return status === "completed" || status === "failed" || status === "cancelled"; } // node_modules/zod-to-json-schema/dist/esm/Options.js var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); var defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", target: "jsonSchema7", strictUnions: false, definitions: {}, errorMessages: false, markdownDescription: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref", openAiAnyTypeName: "OpenAiAnyType" }; var getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; // node_modules/zod-to-json-schema/dist/esm/Refs.js var getRefs = (options) => { const _options = getDefaultOptions(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return { ..._options, flags: { hasReferencedOpenAiAnyType: false }, currentPath, propertyPath: void 0, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ])) }; }; // node_modules/zod-to-json-schema/dist/esm/errorMessages.js function addErrorMessage(res, key, errorMessage, refs) { if (!refs?.errorMessages) return; if (errorMessage) { res.errorMessage = { ...res.errorMessage, [key]: errorMessage }; } } function setResponseValueAndErrors(res, key, value, errorMessage, refs) { res[key] = value; addErrorMessage(res, key, errorMessage, refs); } // node_modules/zod-to-json-schema/dist/esm/getRelativePath.js var getRelativePath = (pathA, pathB) => { let i = 0; for (; i < pathA.length && i < pathB.length; i++) { if (pathA[i] !== pathB[i]) break; } return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); }; // node_modules/zod-to-json-schema/dist/esm/parsers/any.js function parseAnyDef(refs) { if (refs.target !== "openAi") { return {}; } const anyDefinitionPath = [ ...refs.basePath, refs.definitionPath, refs.openAiAnyTypeName ]; refs.flags.hasReferencedOpenAiAnyType = true; return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; } // node_modules/zod-to-json-schema/dist/esm/parsers/array.js function parseArrayDef(def, refs) { const res = { type: "array" }; if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind2.ZodAny) { res.items = parseDef(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); } if (def.minLength) { setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); } if (def.maxLength) { setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); } if (def.exactLength) { setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js function parseBigintDef(def, refs) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check2 of def.checks) { switch (check2.kind) { case "min": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); break; } } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js function parseBooleanDef() { return { type: "boolean" }; } // node_modules/zod-to-json-schema/dist/esm/parsers/branded.js function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/catch.js var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; // node_modules/zod-to-json-schema/dist/esm/parsers/date.js function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy ?? refs.dateStrategy; if (Array.isArray(strategy)) { return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) }; } switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser(def, refs); } } var integerDateParser = (def, refs) => { const res = { type: "integer", format: "unix-time" }; if (refs.target === "openApi3") { return res; } for (const check2 of def.checks) { switch (check2.kind) { case "min": setResponseValueAndErrors( res, "minimum", check2.value, // This is in milliseconds check2.message, refs ); break; case "max": setResponseValueAndErrors( res, "maximum", check2.value, // This is in milliseconds check2.message, refs ); break; } } return res; }; // node_modules/zod-to-json-schema/dist/esm/parsers/default.js function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } // node_modules/zod-to-json-schema/dist/esm/parsers/effects.js function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/enum.js function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values) }; } // node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js var isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef(def, refs) { const allOf = [ parseDef(def.left._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }), parseDef(def.right._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "1"] }) ].filter((x) => !!x); let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) { mergedAllOf.push(...schema.allOf); if (schema.unevaluatedProperties === void 0) { unevaluatedProperties = void 0; } } else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } else { unevaluatedProperties = void 0; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf, ...unevaluatedProperties } : void 0; } // node_modules/zod-to-json-schema/dist/esm/parsers/literal.js function parseLiteralDef(def, refs) { const parsedType2 = typeof def.value; if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } if (refs.target === "openApi3") { return { type: parsedType2 === "bigint" ? "integer" : parsedType2, enum: [def.value] }; } return { type: parsedType2 === "bigint" ? "integer" : parsedType2, const: def.value }; } // node_modules/zod-to-json-schema/dist/esm/parsers/string.js var emojiRegex2 = void 0; var zodPatterns = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (emojiRegex2 === void 0) { emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); } return emojiRegex2; }, /** * Unused */ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, /** * Unused */ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, /** * Unused */ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; function parseStringDef(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check2 of def.checks) { switch (check2.kind) { case "min": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); break; case "max": setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check2.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check2.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check2.message, refs); break; } break; case "url": addFormat(res, "uri", check2.message, refs); break; case "uuid": addFormat(res, "uuid", check2.message, refs); break; case "regex": addPattern(res, check2.regex, check2.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check2.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check2.message, refs); break; case "startsWith": addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs); break; case "endsWith": addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs); break; case "datetime": addFormat(res, "date-time", check2.message, refs); break; case "date": addFormat(res, "date", check2.message, refs); break; case "time": addFormat(res, "time", check2.message, refs); break; case "duration": addFormat(res, "duration", check2.message, refs); break; case "length": setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); break; case "includes": { addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs); break; } case "ip": { if (check2.version !== "v6") { addFormat(res, "ipv4", check2.message, refs); } if (check2.version !== "v4") { addFormat(res, "ipv6", check2.message, refs); } break; } case "base64url": addPattern(res, zodPatterns.base64url, check2.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check2.message, refs); break; case "cidr": { if (check2.version !== "v6") { addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs); } if (check2.version !== "v4") { addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs); } break; } case "emoji": addPattern(res, zodPatterns.emoji(), check2.message, refs); break; case "ulid": { addPattern(res, zodPatterns.ulid, check2.message, refs); break; } case "base64": { switch (refs.base64Strategy) { case "format:binary": { addFormat(res, "binary", check2.message, refs); break; } case "contentEncoding:base64": { setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs); break; } case "pattern:zod": { addPattern(res, zodPatterns.base64, check2.message, refs); break; } } break; } case "nanoid": { addPattern(res, zodPatterns.nanoid, check2.message, refs); } case "toLowerCase": case "toUpperCase": case "trim": break; default: /* @__PURE__ */ ((_) => { })(check2); } } } return res; } function escapeLiteralCheckValue(literal2, refs) { return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2; } var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); function escapeNonAlphaNumeric(source) { let result = ""; for (let i = 0; i < source.length; i++) { if (!ALPHA_NUMERIC.has(source[i])) { result += "\\"; } result += source[i]; } return result; } function addFormat(schema, value, message, refs) { if (schema.format || schema.anyOf?.some((x) => x.format)) { if (!schema.anyOf) { schema.anyOf = []; } if (schema.format) { schema.anyOf.push({ format: schema.format, ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } }); delete schema.format; if (schema.errorMessage) { delete schema.errorMessage.format; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.anyOf.push({ format: value, ...message && refs.errorMessages && { errorMessage: { format: message } } }); } else { setResponseValueAndErrors(schema, "format", value, message, refs); } } function addPattern(schema, regex, message, refs) { if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { if (!schema.allOf) { schema.allOf = []; } if (schema.pattern) { schema.allOf.push({ pattern: schema.pattern, ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } }); delete schema.pattern; if (schema.errorMessage) { delete schema.errorMessage.pattern; if (Object.keys(schema.errorMessage).length === 0) { delete schema.errorMessage; } } } schema.allOf.push({ pattern: stringifyRegExpWithFlags(regex, refs), ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); } else { setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); } } function stringifyRegExpWithFlags(regex, refs) { if (!refs.applyRegexFlags || !regex.flags) { return regex.source; } const flags = { i: regex.flags.includes("i"), m: regex.flags.includes("m"), s: regex.flags.includes("s") // `.` matches newlines }; const source = flags.i ? regex.source.toLowerCase() : regex.source; let pattern = ""; let isEscaped = false; let inCharGroup = false; let inCharRange = false; for (let i = 0; i < source.length; i++) { if (isEscaped) { pattern += source[i]; isEscaped = false; continue; } if (flags.i) { if (inCharGroup) { if (source[i].match(/[a-z]/)) { if (inCharRange) { pattern += source[i]; pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); inCharRange = false; } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { pattern += source[i]; inCharRange = true; } else { pattern += `${source[i]}${source[i].toUpperCase()}`; } continue; } } else if (source[i].match(/[a-z]/)) { pattern += `[${source[i]}${source[i].toUpperCase()}]`; continue; } } if (flags.m) { if (source[i] === "^") { pattern += `(^|(?<=[\r ]))`; continue; } else if (source[i] === "$") { pattern += `($|(?=[\r ]))`; continue; } } if (flags.s && source[i] === ".") { pattern += inCharGroup ? `${source[i]}\r ` : `[${source[i]}\r ]`; continue; } pattern += source[i]; if (source[i] === "\\") { isEscaped = true; } else if (inCharGroup && source[i] === "]") { inCharGroup = false; } else if (!inCharGroup && source[i] === "[") { inCharGroup = true; } } try { new RegExp(pattern); } catch { console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); return regex.source; } return pattern; } // node_modules/zod-to-json-schema/dist/esm/parsers/record.js function parseRecordDef(def, refs) { if (refs.target === "openAi") { console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); } if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) { return { type: "object", required: def.keyType._def.values, properties: def.keyType._def.values.reduce((acc, key) => ({ ...acc, [key]: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "properties", key] }) ?? parseAnyDef(refs) }), {}), additionalProperties: refs.rejectedAdditionalProperties }; } const schema = { type: "object", additionalProperties: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? refs.allowedAdditionalProperties }; if (refs.target === "openApi3") { return schema; } if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) { const { type, ...keyType } = parseStringDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) { return { ...schema, propertyNames: { enum: def.keyType._def.values } }; } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) { const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); return { ...schema, propertyNames: keyType }; } return schema; } // node_modules/zod-to-json-schema/dist/esm/parsers/map.js function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); } const keys = parseDef(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"] }) || parseAnyDef(refs); const values = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"] }) || parseAnyDef(refs); return { type: "array", maxItems: 125, items: { type: "array", items: [keys, values], minItems: 2, maxItems: 2 } }; } // node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js function parseNativeEnumDef(def) { const object3 = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object3[object3[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object3[key]); const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } // node_modules/zod-to-json-schema/dist/esm/parsers/never.js function parseNeverDef(refs) { return refs.target === "openAi" ? void 0 : { not: parseAnyDef({ ...refs, currentPath: [...refs.currentPath, "not"] }) }; } // node_modules/zod-to-json-schema/dist/esm/parsers/null.js function parseNullDef(refs) { return refs.target === "openApi3" ? { enum: ["null"], nullable: true } : { type: "null" }; } // node_modules/zod-to-json-schema/dist/esm/parsers/union.js var primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef(def, refs) { if (refs.target === "openApi3") return asAnyOf(def, refs); const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { const types = options.reduce((types2, x) => { const type = primitiveMappings[x._def.typeName]; return type && !types2.includes(type) ? [...types2, type] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { const types = options.reduce((acc, x) => { const type = typeof x._def.value; switch (type) { case "string": case "number": case "boolean": return [...acc, type]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, []); if (types.length === options.length) { const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce((acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, []) }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce((acc, x) => [ ...acc, ...x._def.values.filter((x2) => !acc.includes(x2)) ], []) }; } return asAnyOf(def, refs); } var asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i}`] })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); return anyOf.length ? { anyOf } : void 0; }; // node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js function parseNullableDef(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { if (refs.target === "openApi3") { return { type: primitiveMappings[def.innerType._def.typeName], nullable: true }; } return { type: [ primitiveMappings[def.innerType._def.typeName], "null" ] }; } if (refs.target === "openApi3") { const base2 = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath] }); if (base2 && "$ref" in base2) return { allOf: [base2], nullable: true }; return base2 && { ...base2, nullable: true }; } const base = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } // node_modules/zod-to-json-schema/dist/esm/parsers/number.js function parseNumberDef(def, refs) { const res = { type: "number" }; if (!def.checks) return res; for (const check2 of def.checks) { switch (check2.kind) { case "int": res.type = "integer"; addErrorMessage(res, "type", check2.message, refs); break; case "min": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMinimum = true; } setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check2.inclusive) { setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } else { setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); } } else { if (!check2.inclusive) { res.exclusiveMaximum = true; } setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); } break; case "multipleOf": setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); break; } } return res; } // node_modules/zod-to-json-schema/dist/esm/parsers/object.js function parseObjectDef(def, refs) { const forceOptionalIntoNullable = refs.target === "openAi"; const result = { type: "object", properties: {} }; const required2 = []; const shape = def.shape(); for (const propName in shape) { let propDef = shape[propName]; if (propDef === void 0 || propDef._def === void 0) { continue; } let propOptional = safeIsOptional(propDef); if (propOptional && forceOptionalIntoNullable) { if (propDef._def.typeName === "ZodOptional") { propDef = propDef._def.innerType; } if (!propDef.isNullable()) { propDef = propDef.nullable(); } propOptional = false; } const parsedDef = parseDef(propDef._def, { ...refs, currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] }); if (parsedDef === void 0) { continue; } result.properties[propName] = parsedDef; if (!propOptional) { required2.push(propName); } } if (required2.length) { result.required = required2; } const additionalProperties = decideAdditionalProperties(def, refs); if (additionalProperties !== void 0) { result.additionalProperties = additionalProperties; } return result; } function decideAdditionalProperties(def, refs) { if (def.catchall._def.typeName !== "ZodNever") { return parseDef(def.catchall._def, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }); } switch (def.unknownKeys) { case "passthrough": return refs.allowedAdditionalProperties; case "strict": return refs.rejectedAdditionalProperties; case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } } function safeIsOptional(schema) { try { return schema.isOptional(); } catch { return true; } } // node_modules/zod-to-json-schema/dist/esm/parsers/optional.js var parseOptionalDef = (def, refs) => { if (refs.currentPath.toString() === refs.propertyPath?.toString()) { return parseDef(def.innerType._def, refs); } const innerSchema = parseDef(def.innerType._def, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return innerSchema ? { anyOf: [ { not: parseAnyDef(refs) }, innerSchema ] } : parseAnyDef(refs); }; // node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js var parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return parseDef(def.in._def, refs); } else if (refs.pipeStrategy === "output") { return parseDef(def.out._def, refs); } const a = parseDef(def.in._def, { ...refs, currentPath: [...refs.currentPath, "allOf", "0"] }); const b = parseDef(def.out._def, { ...refs, currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); return { allOf: [a, b].filter((x) => x !== void 0) }; }; // node_modules/zod-to-json-schema/dist/esm/parsers/promise.js function parsePromiseDef(def, refs) { return parseDef(def.type._def, refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/set.js function parseSetDef(def, refs) { const items = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); const schema = { type: "array", uniqueItems: true, items }; if (def.minSize) { setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); } if (def.maxSize) { setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); } return schema; } // node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js function parseTupleDef(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), additionalItems: parseDef(def.rest._def, { ...refs, currentPath: [...refs.currentPath, "additionalItems"] }) }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items.map((x, i) => parseDef(x._def, { ...refs, currentPath: [...refs.currentPath, "items", `${i}`] })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) }; } } // node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js function parseUndefinedDef(refs) { return { not: parseAnyDef(refs) }; } // node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js function parseUnknownDef(refs) { return parseAnyDef(refs); } // node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js var parseReadonlyDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; // node_modules/zod-to-json-schema/dist/esm/selectParser.js var selectParser = (def, typeName, refs) => { switch (typeName) { case ZodFirstPartyTypeKind2.ZodString: return parseStringDef(def, refs); case ZodFirstPartyTypeKind2.ZodNumber: return parseNumberDef(def, refs); case ZodFirstPartyTypeKind2.ZodObject: return parseObjectDef(def, refs); case ZodFirstPartyTypeKind2.ZodBigInt: return parseBigintDef(def, refs); case ZodFirstPartyTypeKind2.ZodBoolean: return parseBooleanDef(); case ZodFirstPartyTypeKind2.ZodDate: return parseDateDef(def, refs); case ZodFirstPartyTypeKind2.ZodUndefined: return parseUndefinedDef(refs); case ZodFirstPartyTypeKind2.ZodNull: return parseNullDef(refs); case ZodFirstPartyTypeKind2.ZodArray: return parseArrayDef(def, refs); case ZodFirstPartyTypeKind2.ZodUnion: case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion: return parseUnionDef(def, refs); case ZodFirstPartyTypeKind2.ZodIntersection: return parseIntersectionDef(def, refs); case ZodFirstPartyTypeKind2.ZodTuple: return parseTupleDef(def, refs); case ZodFirstPartyTypeKind2.ZodRecord: return parseRecordDef(def, refs); case ZodFirstPartyTypeKind2.ZodLiteral: return parseLiteralDef(def, refs); case ZodFirstPartyTypeKind2.ZodEnum: return parseEnumDef(def); case ZodFirstPartyTypeKind2.ZodNativeEnum: return parseNativeEnumDef(def); case ZodFirstPartyTypeKind2.ZodNullable: return parseNullableDef(def, refs); case ZodFirstPartyTypeKind2.ZodOptional: return parseOptionalDef(def, refs); case ZodFirstPartyTypeKind2.ZodMap: return parseMapDef(def, refs); case ZodFirstPartyTypeKind2.ZodSet: return parseSetDef(def, refs); case ZodFirstPartyTypeKind2.ZodLazy: return () => def.getter()._def; case ZodFirstPartyTypeKind2.ZodPromise: return parsePromiseDef(def, refs); case ZodFirstPartyTypeKind2.ZodNaN: case ZodFirstPartyTypeKind2.ZodNever: return parseNeverDef(refs); case ZodFirstPartyTypeKind2.ZodEffects: return parseEffectsDef(def, refs); case ZodFirstPartyTypeKind2.ZodAny: return parseAnyDef(refs); case ZodFirstPartyTypeKind2.ZodUnknown: return parseUnknownDef(refs); case ZodFirstPartyTypeKind2.ZodDefault: return parseDefaultDef(def, refs); case ZodFirstPartyTypeKind2.ZodBranded: return parseBrandedDef(def, refs); case ZodFirstPartyTypeKind2.ZodReadonly: return parseReadonlyDef(def, refs); case ZodFirstPartyTypeKind2.ZodCatch: return parseCatchDef(def, refs); case ZodFirstPartyTypeKind2.ZodPipeline: return parsePipelineDef(def, refs); case ZodFirstPartyTypeKind2.ZodFunction: case ZodFirstPartyTypeKind2.ZodVoid: case ZodFirstPartyTypeKind2.ZodSymbol: return void 0; default: return /* @__PURE__ */ ((_) => void 0)(typeName); } }; // node_modules/zod-to-json-schema/dist/esm/parseDef.js function parseDef(def, refs, forceResolution = false) { const seenItem = refs.seen.get(def); if (refs.override) { const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); if (overrideResult !== ignoreOverride) { return overrideResult; } } if (seenItem && !forceResolution) { const seenSchema = get$ref(seenItem, refs); if (seenSchema !== void 0) { return seenSchema; } } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; if (jsonSchema) { addMeta(def, refs, jsonSchema); } if (refs.postProcess) { const postProcessResult = refs.postProcess(jsonSchema, def, refs); newItem.jsonSchema = jsonSchema; return postProcessResult; } newItem.jsonSchema = jsonSchema; return jsonSchema; } var get$ref = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.join("/") }; case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; case "none": case "seen": { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); return parseAnyDef(refs); } return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; } } }; var addMeta = (def, refs, jsonSchema) => { if (def.description) { jsonSchema.description = def.description; if (refs.markdownDescription) { jsonSchema.markdownDescription = def.description; } } return jsonSchema; }; // node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js var zodToJsonSchema = (schema, options) => { const refs = getRefs(options); let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ ...acc, [name2]: parseDef(schema2._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name2] }, true) ?? parseAnyDef(refs) }), {}) : void 0; const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; const main = parseDef(schema._def, name === void 0 ? refs : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name] }, false) ?? parseAnyDef(refs); const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; if (title !== void 0) { main.title = title; } if (refs.flags.hasReferencedOpenAiAnyType) { if (!definitions) { definitions = {}; } if (!definitions[refs.openAiAnyTypeName]) { definitions[refs.openAiAnyTypeName] = { // Skipping "object" as no properties can be defined and additionalProperties must be "false" type: ["string", "number", "integer", "boolean", "array", "null"], items: { $ref: refs.$refStrategy === "relative" ? "1" : [ ...refs.basePath, refs.definitionPath, refs.openAiAnyTypeName ].join("/") } }; } } const combined = name === void 0 ? definitions ? { ...main, [refs.definitionPath]: definitions } : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name ].join("/"), [refs.definitionPath]: { ...definitions, [name]: main } }; if (refs.target === "jsonSchema7") { combined.$schema = "http://json-schema.org/draft-07/schema#"; } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; } if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); } return combined; }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js function getMethodLiteral(schema) { const shape = getObjectShape(schema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error("Schema is missing a method literal"); } const value = getLiteralValue(methodSchema); if (typeof value !== "string") { throw new Error("Schema method literal must be a string"); } return value; } function parseWithCompat(schema, data) { const result = safeParse3(schema, data); if (!result.success) { throw result.error; } return result.data; } // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; var Protocol = class { constructor(_options) { this._options = _options; this._requestMessageId = 0; this._requestHandlers = /* @__PURE__ */ new Map(); this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); this._notificationHandlers = /* @__PURE__ */ new Map(); this._responseHandlers = /* @__PURE__ */ new Map(); this._progressHandlers = /* @__PURE__ */ new Map(); this._timeoutInfo = /* @__PURE__ */ new Map(); this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); this._taskProgressTokens = /* @__PURE__ */ new Map(); this._requestResolvers = /* @__PURE__ */ new Map(); this.setNotificationHandler(CancelledNotificationSchema, (notification) => { this._oncancel(notification); }); this.setNotificationHandler(ProgressNotificationSchema, (notification) => { this._onprogress(notification); }); this.setRequestHandler( PingRequestSchema, // Automatic pong by default. (_request) => ({}) ); this._taskStore = _options?.taskStore; this._taskMessageQueue = _options?.taskMessageQueue; if (this._taskStore) { this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); } return { ...task }; }); this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { const handleTaskResult = async () => { const taskId = request.params.taskId; if (this._taskMessageQueue) { let queuedMessage; while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { if (queuedMessage.type === "response" || queuedMessage.type === "error") { const message = queuedMessage.message; const requestId = message.id; const resolver = this._requestResolvers.get(requestId); if (resolver) { this._requestResolvers.delete(requestId); if (queuedMessage.type === "response") { resolver(message); } else { const errorMessage = message; const error48 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); resolver(error48); } } else { const messageType = queuedMessage.type === "response" ? "Response" : "Error"; this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); } continue; } await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); } } const task = await this._taskStore.getTask(taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); } if (!isTerminal(task.status)) { await this._waitForTaskUpdate(taskId, extra.signal); return await handleTaskResult(); } if (isTerminal(task.status)) { const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); this._clearTaskQueue(taskId); return { ...result, _meta: { ...result._meta, [RELATED_TASK_META_KEY]: { taskId } } }; } return await handleTaskResult(); }; return await handleTaskResult(); }); this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { try { const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); return { tasks, nextCursor, _meta: {} }; } catch (error48) { throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error48 instanceof Error ? error48.message : String(error48)}`); } }); this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { try { const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); } if (isTerminal(task.status)) { throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); } await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); this._clearTaskQueue(request.params.taskId); const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); if (!cancelledTask) { throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); } return { _meta: {}, ...cancelledTask }; } catch (error48) { if (error48 instanceof McpError) { throw error48; } throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error48 instanceof Error ? error48.message : String(error48)}`); } }); } } async _oncancel(notification) { if (!notification.params.requestId) { return; } const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); controller?.abort(notification.params.reason); } _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { this._timeoutInfo.set(messageId, { timeoutId: setTimeout(onTimeout, timeout), startTime: Date.now(), timeout, maxTotalTimeout, resetTimeoutOnProgress, onTimeout }); } _resetTimeout(messageId) { const info = this._timeoutInfo.get(messageId); if (!info) return false; const totalElapsed = Date.now() - info.startTime; if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { this._timeoutInfo.delete(messageId); throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { maxTotalTimeout: info.maxTotalTimeout, totalElapsed }); } clearTimeout(info.timeoutId); info.timeoutId = setTimeout(info.onTimeout, info.timeout); return true; } _cleanupTimeout(messageId) { const info = this._timeoutInfo.get(messageId); if (info) { clearTimeout(info.timeoutId); this._timeoutInfo.delete(messageId); } } /** * Attaches to the given transport, starts it, and starts listening for messages. * * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. */ async connect(transport) { if (this._transport) { throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection."); } this._transport = transport; const _onclose = this.transport?.onclose; this._transport.onclose = () => { _onclose?.(); this._onclose(); }; const _onerror = this.transport?.onerror; this._transport.onerror = (error48) => { _onerror?.(error48); this._onerror(error48); }; const _onmessage = this._transport?.onmessage; this._transport.onmessage = (message, extra) => { _onmessage?.(message, extra); if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { this._onresponse(message); } else if (isJSONRPCRequest(message)) { this._onrequest(message, extra); } else if (isJSONRPCNotification(message)) { this._onnotification(message); } else { this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); } }; await this._transport.start(); } _onclose() { const responseHandlers = this._responseHandlers; this._responseHandlers = /* @__PURE__ */ new Map(); this._progressHandlers.clear(); this._taskProgressTokens.clear(); this._pendingDebouncedNotifications.clear(); for (const info of this._timeoutInfo.values()) { clearTimeout(info.timeoutId); } this._timeoutInfo.clear(); for (const controller of this._requestHandlerAbortControllers.values()) { controller.abort(); } this._requestHandlerAbortControllers.clear(); const error48 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); this._transport = void 0; this.onclose?.(); for (const handler of responseHandlers.values()) { handler(error48); } } _onerror(error48) { this.onerror?.(error48); } _onnotification(notification) { const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; if (handler === void 0) { return; } Promise.resolve().then(() => handler(notification)).catch((error48) => this._onerror(new Error(`Uncaught error in notification handler: ${error48}`))); } _onrequest(request, extra) { const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; const capturedTransport = this._transport; const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; if (handler === void 0) { const errorResponse = { jsonrpc: "2.0", id: request.id, error: { code: ErrorCode.MethodNotFound, message: "Method not found" } }; if (relatedTaskId && this._taskMessageQueue) { this._enqueueTaskMessage(relatedTaskId, { type: "error", message: errorResponse, timestamp: Date.now() }, capturedTransport?.sessionId).catch((error48) => this._onerror(new Error(`Failed to enqueue error response: ${error48}`))); } else { capturedTransport?.send(errorResponse).catch((error48) => this._onerror(new Error(`Failed to send an error response: ${error48}`))); } return; } const abortController = new AbortController(); this._requestHandlerAbortControllers.set(request.id, abortController); const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0; const fullExtra = { signal: abortController.signal, sessionId: capturedTransport?.sessionId, _meta: request.params?._meta, sendNotification: async (notification) => { if (abortController.signal.aborted) return; const notificationOptions = { relatedRequestId: request.id }; if (relatedTaskId) { notificationOptions.relatedTask = { taskId: relatedTaskId }; } await this.notification(notification, notificationOptions); }, sendRequest: async (r, resultSchema, options) => { if (abortController.signal.aborted) { throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); } const requestOptions = { ...options, relatedRequestId: request.id }; if (relatedTaskId && !requestOptions.relatedTask) { requestOptions.relatedTask = { taskId: relatedTaskId }; } const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; if (effectiveTaskId && taskStore) { await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); } return await this.request(r, resultSchema, requestOptions); }, authInfo: extra?.authInfo, requestId: request.id, requestInfo: extra?.requestInfo, taskId: relatedTaskId, taskStore, taskRequestedTtl: taskCreationParams?.ttl, closeSSEStream: extra?.closeSSEStream, closeStandaloneSSEStream: extra?.closeStandaloneSSEStream }; Promise.resolve().then(() => { if (taskCreationParams) { this.assertTaskHandlerCapability(request.method); } }).then(() => handler(request, fullExtra)).then(async (result) => { if (abortController.signal.aborted) { return; } const response = { result, jsonrpc: "2.0", id: request.id }; if (relatedTaskId && this._taskMessageQueue) { await this._enqueueTaskMessage(relatedTaskId, { type: "response", message: response, timestamp: Date.now() }, capturedTransport?.sessionId); } else { await capturedTransport?.send(response); } }, async (error48) => { if (abortController.signal.aborted) { return; } const errorResponse = { jsonrpc: "2.0", id: request.id, error: { code: Number.isSafeInteger(error48["code"]) ? error48["code"] : ErrorCode.InternalError, message: error48.message ?? "Internal error", ...error48["data"] !== void 0 && { data: error48["data"] } } }; if (relatedTaskId && this._taskMessageQueue) { await this._enqueueTaskMessage(relatedTaskId, { type: "error", message: errorResponse, timestamp: Date.now() }, capturedTransport?.sessionId); } else { await capturedTransport?.send(errorResponse); } }).catch((error48) => this._onerror(new Error(`Failed to send response: ${error48}`))).finally(() => { if (this._requestHandlerAbortControllers.get(request.id) === abortController) { this._requestHandlerAbortControllers.delete(request.id); } }); } _onprogress(notification) { const { progressToken, ...params } = notification.params; const messageId = Number(progressToken); const handler = this._progressHandlers.get(messageId); if (!handler) { this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); return; } const responseHandler = this._responseHandlers.get(messageId); const timeoutInfo = this._timeoutInfo.get(messageId); if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { try { this._resetTimeout(messageId); } catch (error48) { this._responseHandlers.delete(messageId); this._progressHandlers.delete(messageId); this._cleanupTimeout(messageId); responseHandler(error48); return; } } handler(params); } _onresponse(response) { const messageId = Number(response.id); const resolver = this._requestResolvers.get(messageId); if (resolver) { this._requestResolvers.delete(messageId); if (isJSONRPCResultResponse(response)) { resolver(response); } else { const error48 = new McpError(response.error.code, response.error.message, response.error.data); resolver(error48); } return; } const handler = this._responseHandlers.get(messageId); if (handler === void 0) { this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); return; } this._responseHandlers.delete(messageId); this._cleanupTimeout(messageId); let isTaskResponse = false; if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { const result = response.result; if (result.task && typeof result.task === "object") { const task = result.task; if (typeof task.taskId === "string") { isTaskResponse = true; this._taskProgressTokens.set(task.taskId, messageId); } } } if (!isTaskResponse) { this._progressHandlers.delete(messageId); } if (isJSONRPCResultResponse(response)) { handler(response); } else { const error48 = McpError.fromError(response.error.code, response.error.message, response.error.data); handler(error48); } } get transport() { return this._transport; } /** * Closes the connection. */ async close() { await this._transport?.close(); } /** * Sends a request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * @example * ```typescript * const stream = protocol.requestStream(request, resultSchema, options); * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('Final result:', message.result); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @experimental Use `client.experimental.tasks.requestStream()` to access this method. */ async *requestStream(request, resultSchema, options) { const { task } = options ?? {}; if (!task) { try { const result = await this.request(request, resultSchema, options); yield { type: "result", result }; } catch (error48) { yield { type: "error", error: error48 instanceof McpError ? error48 : new McpError(ErrorCode.InternalError, String(error48)) }; } return; } let taskId; try { const createResult = await this.request(request, CreateTaskResultSchema, options); if (createResult.task) { taskId = createResult.task.taskId; yield { type: "taskCreated", task: createResult.task }; } else { throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); } while (true) { const task2 = await this.getTask({ taskId }, options); yield { type: "taskStatus", task: task2 }; if (isTerminal(task2.status)) { if (task2.status === "completed") { const result = await this.getTaskResult({ taskId }, resultSchema, options); yield { type: "result", result }; } else if (task2.status === "failed") { yield { type: "error", error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) }; } else if (task2.status === "cancelled") { yield { type: "error", error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) }; } return; } if (task2.status === "input_required") { const result = await this.getTaskResult({ taskId }, resultSchema, options); yield { type: "result", result }; return; } const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3; await new Promise((resolve) => setTimeout(resolve, pollInterval)); options?.signal?.throwIfAborted(); } } catch (error48) { yield { type: "error", error: error48 instanceof McpError ? error48 : new McpError(ErrorCode.InternalError, String(error48)) }; } } /** * Sends a request and waits for a response. * * Do not use this method to emit notifications! Use notification() instead. */ request(request, resultSchema, options) { const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; return new Promise((resolve, reject) => { const earlyReject = (error48) => { reject(error48); }; if (!this._transport) { earlyReject(new Error("Not connected")); return; } if (this._options?.enforceStrictCapabilities === true) { try { this.assertCapabilityForMethod(request.method); if (task) { this.assertTaskCapability(request.method); } } catch (e) { earlyReject(e); return; } } options?.signal?.throwIfAborted(); const messageId = this._requestMessageId++; const jsonrpcRequest = { ...request, jsonrpc: "2.0", id: messageId }; if (options?.onprogress) { this._progressHandlers.set(messageId, options.onprogress); jsonrpcRequest.params = { ...request.params, _meta: { ...request.params?._meta || {}, progressToken: messageId } }; } if (task) { jsonrpcRequest.params = { ...jsonrpcRequest.params, task }; } if (relatedTask) { jsonrpcRequest.params = { ...jsonrpcRequest.params, _meta: { ...jsonrpcRequest.params?._meta || {}, [RELATED_TASK_META_KEY]: relatedTask } }; } const cancel = (reason) => { this._responseHandlers.delete(messageId); this._progressHandlers.delete(messageId); this._cleanupTimeout(messageId); this._transport?.send({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: messageId, reason: String(reason) } }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error49) => this._onerror(new Error(`Failed to send cancellation: ${error49}`))); const error48 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); reject(error48); }; this._responseHandlers.set(messageId, (response) => { if (options?.signal?.aborted) { return; } if (response instanceof Error) { return reject(response); } try { const parseResult = safeParse3(resultSchema, response.result); if (!parseResult.success) { reject(parseResult.error); } else { resolve(parseResult.data); } } catch (error48) { reject(error48); } }); options?.signal?.addEventListener("abort", () => { cancel(options?.signal?.reason); }); const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); const relatedTaskId = relatedTask?.taskId; if (relatedTaskId) { const responseResolver = (response) => { const handler = this._responseHandlers.get(messageId); if (handler) { handler(response); } else { this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); } }; this._requestResolvers.set(messageId, responseResolver); this._enqueueTaskMessage(relatedTaskId, { type: "request", message: jsonrpcRequest, timestamp: Date.now() }).catch((error48) => { this._cleanupTimeout(messageId); reject(error48); }); } else { this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error48) => { this._cleanupTimeout(messageId); reject(error48); }); } }); } /** * Gets the current status of a task. * * @experimental Use `client.experimental.tasks.getTask()` to access this method. */ async getTask(params, options) { return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options); } /** * Retrieves the result of a completed task. * * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. */ async getTaskResult(params, resultSchema, options) { return this.request({ method: "tasks/result", params }, resultSchema, options); } /** * Lists tasks, optionally starting from a pagination cursor. * * @experimental Use `client.experimental.tasks.listTasks()` to access this method. */ async listTasks(params, options) { return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options); } /** * Cancels a specific task. * * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. */ async cancelTask(params, options) { return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options); } /** * Emits a notification, which is a one-way message that does not expect a response. */ async notification(notification, options) { if (!this._transport) { throw new Error("Not connected"); } this.assertNotificationCapability(notification.method); const relatedTaskId = options?.relatedTask?.taskId; if (relatedTaskId) { const jsonrpcNotification2 = { ...notification, jsonrpc: "2.0", params: { ...notification.params, _meta: { ...notification.params?._meta || {}, [RELATED_TASK_META_KEY]: options.relatedTask } } }; await this._enqueueTaskMessage(relatedTaskId, { type: "notification", message: jsonrpcNotification2, timestamp: Date.now() }); return; } const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; if (canDebounce) { if (this._pendingDebouncedNotifications.has(notification.method)) { return; } this._pendingDebouncedNotifications.add(notification.method); Promise.resolve().then(() => { this._pendingDebouncedNotifications.delete(notification.method); if (!this._transport) { return; } let jsonrpcNotification2 = { ...notification, jsonrpc: "2.0" }; if (options?.relatedTask) { jsonrpcNotification2 = { ...jsonrpcNotification2, params: { ...jsonrpcNotification2.params, _meta: { ...jsonrpcNotification2.params?._meta || {}, [RELATED_TASK_META_KEY]: options.relatedTask } } }; } this._transport?.send(jsonrpcNotification2, options).catch((error48) => this._onerror(error48)); }); return; } let jsonrpcNotification = { ...notification, jsonrpc: "2.0" }; if (options?.relatedTask) { jsonrpcNotification = { ...jsonrpcNotification, params: { ...jsonrpcNotification.params, _meta: { ...jsonrpcNotification.params?._meta || {}, [RELATED_TASK_META_KEY]: options.relatedTask } } }; } await this._transport.send(jsonrpcNotification, options); } /** * Registers a handler to invoke when this protocol object receives a request with the given method. * * Note that this will replace any previous request handler for the same method. */ setRequestHandler(requestSchema, handler) { const method = getMethodLiteral(requestSchema); this.assertRequestHandlerCapability(method); this._requestHandlers.set(method, (request, extra) => { const parsed = parseWithCompat(requestSchema, request); return Promise.resolve(handler(parsed, extra)); }); } /** * Removes the request handler for the given method. */ removeRequestHandler(method) { this._requestHandlers.delete(method); } /** * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. */ assertCanSetRequestHandler(method) { if (this._requestHandlers.has(method)) { throw new Error(`A request handler for ${method} already exists, which would be overridden`); } } /** * Registers a handler to invoke when this protocol object receives a notification with the given method. * * Note that this will replace any previous notification handler for the same method. */ setNotificationHandler(notificationSchema, handler) { const method = getMethodLiteral(notificationSchema); this._notificationHandlers.set(method, (notification) => { const parsed = parseWithCompat(notificationSchema, notification); return Promise.resolve(handler(parsed)); }); } /** * Removes the notification handler for the given method. */ removeNotificationHandler(method) { this._notificationHandlers.delete(method); } /** * Cleans up the progress handler associated with a task. * This should be called when a task reaches a terminal status. */ _cleanupTaskProgressHandler(taskId) { const progressToken = this._taskProgressTokens.get(taskId); if (progressToken !== void 0) { this._progressHandlers.delete(progressToken); this._taskProgressTokens.delete(taskId); } } /** * Enqueues a task-related message for side-channel delivery via tasks/result. * @param taskId The task ID to associate the message with * @param message The message to enqueue * @param sessionId Optional session ID for binding the operation to a specific session * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) * * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer * simply propagates the error. */ async _enqueueTaskMessage(taskId, message, sessionId) { if (!this._taskStore || !this._taskMessageQueue) { throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); } const maxQueueSize = this._options?.maxTaskQueueSize; await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); } /** * Clears the message queue for a task and rejects any pending request resolvers. * @param taskId The task ID whose queue should be cleared * @param sessionId Optional session ID for binding the operation to a specific session */ async _clearTaskQueue(taskId, sessionId) { if (this._taskMessageQueue) { const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); for (const message of messages) { if (message.type === "request" && isJSONRPCRequest(message.message)) { const requestId = message.message.id; const resolver = this._requestResolvers.get(requestId); if (resolver) { resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); this._requestResolvers.delete(requestId); } else { this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); } } } } } /** * Waits for a task update (new messages or status change) with abort signal support. * Uses polling to check for updates at the task's configured poll interval. * @param taskId The task ID to wait for * @param signal Abort signal to cancel the wait * @returns Promise that resolves when an update occurs or rejects if aborted */ async _waitForTaskUpdate(taskId, signal) { let interval = this._options?.defaultTaskPollInterval ?? 1e3; try { const task = await this._taskStore?.getTask(taskId); if (task?.pollInterval) { interval = task.pollInterval; } } catch { } return new Promise((resolve, reject) => { if (signal.aborted) { reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); return; } const timeoutId = setTimeout(resolve, interval); signal.addEventListener("abort", () => { clearTimeout(timeoutId); reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); }, { once: true }); }); } requestTaskStore(request, sessionId) { const taskStore = this._taskStore; if (!taskStore) { throw new Error("No task store configured"); } return { createTask: async (taskParams) => { if (!request) { throw new Error("No request provided"); } return await taskStore.createTask(taskParams, request.id, { method: request.method, params: request.params }, sessionId); }, getTask: async (taskId) => { const task = await taskStore.getTask(taskId, sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); } return task; }, storeTaskResult: async (taskId, status, result) => { await taskStore.storeTaskResult(taskId, status, result, sessionId); const task = await taskStore.getTask(taskId, sessionId); if (task) { const notification = TaskStatusNotificationSchema.parse({ method: "notifications/tasks/status", params: task }); await this.notification(notification); if (isTerminal(task.status)) { this._cleanupTaskProgressHandler(taskId); } } }, getTaskResult: (taskId) => { return taskStore.getTaskResult(taskId, sessionId); }, updateTaskStatus: async (taskId, status, statusMessage) => { const task = await taskStore.getTask(taskId, sessionId); if (!task) { throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); } if (isTerminal(task.status)) { throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); } await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); const updatedTask = await taskStore.getTask(taskId, sessionId); if (updatedTask) { const notification = TaskStatusNotificationSchema.parse({ method: "notifications/tasks/status", params: updatedTask }); await this.notification(notification); if (isTerminal(updatedTask.status)) { this._cleanupTaskProgressHandler(taskId); } } }, listTasks: (cursor) => { return taskStore.listTasks(cursor, sessionId); } }; } }; function isPlainObject2(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function mergeCapabilities(base, additional) { const result = { ...base }; for (const key in additional) { const k = key; const addValue = additional[k]; if (addValue === void 0) continue; const baseValue = result[k]; if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { result[k] = { ...baseValue, ...addValue }; } else { result[k] = addValue; } } return result; } // node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js var import_ajv = __toESM(require_ajv(), 1); var import_ajv_formats = __toESM(require_dist5(), 1); function createDefaultAjvInstance() { const ajv = new import_ajv.default({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); const addFormats = import_ajv_formats.default; addFormats(ajv); return ajv; } var AjvJsonSchemaValidator = class { /** * Create an AJV validator * * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. * * @example * ```typescript * // Use default configuration (recommended for most cases) * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; * const validator = new AjvJsonSchemaValidator(); * * // Or provide custom AJV instance for advanced configuration * import { Ajv } from 'ajv'; * import addFormats from 'ajv-formats'; * * const ajv = new Ajv({ validateFormats: true }); * addFormats(ajv); * const validator = new AjvJsonSchemaValidator(ajv); * ``` */ constructor(ajv) { this._ajv = ajv ?? createDefaultAjvInstance(); } /** * Create a validator for the given JSON Schema * * The validator is compiled once and can be reused multiple times. * If the schema has an $id, it will be cached by AJV automatically. * * @param schema - Standard JSON Schema object * @returns A validator function that validates input data */ getValidator(schema) { const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema); return (input) => { const valid = ajvValidator(input); if (valid) { return { valid: true, data: input, errorMessage: void 0 }; } else { return { valid: false, data: void 0, errorMessage: this._ajv.errorsText(ajvValidator.errors) }; } }; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js var ExperimentalClientTasks = class { constructor(_client) { this._client = _client; } /** * Calls a tool and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * This method provides streaming access to tool execution, allowing you to * observe intermediate task status updates for long-running tool calls. * Automatically validates structured output if the tool has an outputSchema. * * @example * ```typescript * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Tool execution started:', message.task.taskId); * break; * case 'taskStatus': * console.log('Tool status:', message.task.status); * break; * case 'result': * console.log('Tool result:', message.result); * break; * case 'error': * console.error('Tool error:', message.error); * break; * } * } * ``` * * @param params - Tool call parameters (name and arguments) * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ async *callToolStream(params, resultSchema = CallToolResultSchema, options) { const clientInternal = this._client; const optionsWithTask = { ...options, // We check if the tool is known to be a task during auto-configuration, but assume // the caller knows what they're doing if they pass this explicitly task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0) }; const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask); const validator = clientInternal.getToolOutputValidator(params.name); for await (const message of stream) { if (message.type === "result" && validator) { const result = message.result; if (!result.structuredContent && !result.isError) { yield { type: "error", error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`) }; return; } if (result.structuredContent) { try { const validationResult = validator(result.structuredContent); if (!validationResult.valid) { yield { type: "error", error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`) }; return; } } catch (error48) { if (error48 instanceof McpError) { yield { type: "error", error: error48 }; return; } yield { type: "error", error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error48 instanceof Error ? error48.message : String(error48)}`) }; return; } } } yield message; } } /** * Gets the current status of a task. * * @param taskId - The task identifier * @param options - Optional request options * @returns The task status * * @experimental */ async getTask(taskId, options) { return this._client.getTask({ taskId }, options); } /** * Retrieves the result of a completed task. * * @param taskId - The task identifier * @param resultSchema - Zod schema for validating the result * @param options - Optional request options * @returns The task result * * @experimental */ async getTaskResult(taskId, resultSchema, options) { return this._client.getTaskResult({ taskId }, resultSchema, options); } /** * Lists tasks with optional pagination. * * @param cursor - Optional pagination cursor * @param options - Optional request options * @returns List of tasks with optional next cursor * * @experimental */ async listTasks(cursor, options) { return this._client.listTasks(cursor ? { cursor } : void 0, options); } /** * Cancels a running task. * * @param taskId - The task identifier * @param options - Optional request options * * @experimental */ async cancelTask(taskId, options) { return this._client.cancelTask({ taskId }, options); } /** * Sends a request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * This method provides streaming access to request processing, allowing you to * observe intermediate task status updates for task-augmented requests. * * @param request - The request to send * @param resultSchema - Zod schema for validating the result * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ requestStream(request, resultSchema, options) { return this._client.requestStream(request, resultSchema, options); } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js function assertToolsCallTaskCapability(requests, method, entityName) { if (!requests) { throw new Error(`${entityName} does not support task creation (required for ${method})`); } switch (method) { case "tools/call": if (!requests.tools?.call) { throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); } break; default: break; } } function assertClientRequestTaskCapability(requests, method, entityName) { if (!requests) { throw new Error(`${entityName} does not support task creation (required for ${method})`); } switch (method) { case "sampling/createMessage": if (!requests.sampling?.createMessage) { throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); } break; case "elicitation/create": if (!requests.elicitation?.create) { throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); } break; default: break; } } // node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js function applyElicitationDefaults(schema, data) { if (!schema || data === null || typeof data !== "object") return; if (schema.type === "object" && schema.properties && typeof schema.properties === "object") { const obj = data; const props = schema.properties; for (const key of Object.keys(props)) { const propSchema = props[key]; if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) { obj[key] = propSchema.default; } if (obj[key] !== void 0) { applyElicitationDefaults(propSchema, obj[key]); } } } if (Array.isArray(schema.anyOf)) { for (const sub of schema.anyOf) { if (typeof sub !== "boolean") { applyElicitationDefaults(sub, data); } } } if (Array.isArray(schema.oneOf)) { for (const sub of schema.oneOf) { if (typeof sub !== "boolean") { applyElicitationDefaults(sub, data); } } } } function getSupportedElicitationModes(capabilities) { if (!capabilities) { return { supportsFormMode: false, supportsUrlMode: false }; } const hasFormCapability = capabilities.form !== void 0; const hasUrlCapability = capabilities.url !== void 0; const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability; const supportsUrlMode = hasUrlCapability; return { supportsFormMode, supportsUrlMode }; } var Client = class extends Protocol { /** * Initializes this client with the given name and version information. */ constructor(_clientInfo, options) { super(options); this._clientInfo = _clientInfo; this._cachedToolOutputValidators = /* @__PURE__ */ new Map(); this._cachedKnownTaskTools = /* @__PURE__ */ new Set(); this._cachedRequiredTaskTools = /* @__PURE__ */ new Set(); this._listChangedDebounceTimers = /* @__PURE__ */ new Map(); this._capabilities = options?.capabilities ?? {}; this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); if (options?.listChanged) { this._pendingListChangedConfig = options.listChanged; } } /** * Set up handlers for list changed notifications based on config and server capabilities. * This should only be called after initialization when server capabilities are known. * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. * @internal */ _setupListChangedHandlers(config2) { if (config2.tools && this._serverCapabilities?.tools?.listChanged) { this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config2.tools, async () => { const result = await this.listTools(); return result.tools; }); } if (config2.prompts && this._serverCapabilities?.prompts?.listChanged) { this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config2.prompts, async () => { const result = await this.listPrompts(); return result.prompts; }); } if (config2.resources && this._serverCapabilities?.resources?.listChanged) { this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config2.resources, async () => { const result = await this.listResources(); return result.resources; }); } } /** * Access experimental features. * * WARNING: These APIs are experimental and may change without notice. * * @experimental */ get experimental() { if (!this._experimental) { this._experimental = { tasks: new ExperimentalClientTasks(this) }; } return this._experimental; } /** * Registers new capabilities. This can only be called before connecting to a transport. * * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). */ registerCapabilities(capabilities) { if (this.transport) { throw new Error("Cannot register capabilities after connecting to transport"); } this._capabilities = mergeCapabilities(this._capabilities, capabilities); } /** * Override request handler registration to enforce client-side validation for elicitation. */ setRequestHandler(requestSchema, handler) { const shape = getObjectShape(requestSchema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error("Schema is missing a method literal"); } let methodValue; if (isZ4Schema(methodSchema)) { const v4Schema = methodSchema; const v4Def = v4Schema._zod?.def; methodValue = v4Def?.value ?? v4Schema.value; } else { const v3Schema = methodSchema; const legacyDef = v3Schema._def; methodValue = legacyDef?.value ?? v3Schema.value; } if (typeof methodValue !== "string") { throw new Error("Schema method literal must be a string"); } const method = methodValue; if (method === "elicitation/create") { const wrappedHandler = async (request, extra) => { const validatedRequest = safeParse3(ElicitRequestSchema, request); if (!validatedRequest.success) { const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); } const { params } = validatedRequest.data; params.mode = params.mode ?? "form"; const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); if (params.mode === "form" && !supportsFormMode) { throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests"); } if (params.mode === "url" && !supportsUrlMode) { throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests"); } const result = await Promise.resolve(handler(request, extra)); if (params.task) { const taskValidationResult = safeParse3(CreateTaskResultSchema, result); if (!taskValidationResult.success) { const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); } return taskValidationResult.data; } const validationResult = safeParse3(ElicitResultSchema, result); if (!validationResult.success) { const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); } const validatedResult = validationResult.data; const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0; if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) { if (this._capabilities.elicitation?.form?.applyDefaults) { try { applyElicitationDefaults(requestedSchema, validatedResult.content); } catch { } } } return validatedResult; }; return super.setRequestHandler(requestSchema, wrappedHandler); } if (method === "sampling/createMessage") { const wrappedHandler = async (request, extra) => { const validatedRequest = safeParse3(CreateMessageRequestSchema, request); if (!validatedRequest.success) { const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`); } const { params } = validatedRequest.data; const result = await Promise.resolve(handler(request, extra)); if (params.task) { const taskValidationResult = safeParse3(CreateTaskResultSchema, result); if (!taskValidationResult.success) { const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); } return taskValidationResult.data; } const hasTools = params.tools || params.toolChoice; const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema; const validationResult = safeParse3(resultSchema, result); if (!validationResult.success) { const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`); } return validationResult.data; }; return super.setRequestHandler(requestSchema, wrappedHandler); } return super.setRequestHandler(requestSchema, handler); } assertCapability(capability, method) { if (!this._serverCapabilities?.[capability]) { throw new Error(`Server does not support ${capability} (required for ${method})`); } } async connect(transport, options) { await super.connect(transport); if (transport.sessionId !== void 0) { return; } try { const result = await this.request({ method: "initialize", params: { protocolVersion: LATEST_PROTOCOL_VERSION, capabilities: this._capabilities, clientInfo: this._clientInfo } }, InitializeResultSchema, options); if (result === void 0) { throw new Error(`Server sent invalid initialize result: ${result}`); } if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); } this._serverCapabilities = result.capabilities; this._serverVersion = result.serverInfo; if (transport.setProtocolVersion) { transport.setProtocolVersion(result.protocolVersion); } this._instructions = result.instructions; await this.notification({ method: "notifications/initialized" }); if (this._pendingListChangedConfig) { this._setupListChangedHandlers(this._pendingListChangedConfig); this._pendingListChangedConfig = void 0; } } catch (error48) { void this.close(); throw error48; } } /** * After initialization has completed, this will be populated with the server's reported capabilities. */ getServerCapabilities() { return this._serverCapabilities; } /** * After initialization has completed, this will be populated with information about the server's name and version. */ getServerVersion() { return this._serverVersion; } /** * After initialization has completed, this may be populated with information about the server's instructions. */ getInstructions() { return this._instructions; } assertCapabilityForMethod(method) { switch (method) { case "logging/setLevel": if (!this._serverCapabilities?.logging) { throw new Error(`Server does not support logging (required for ${method})`); } break; case "prompts/get": case "prompts/list": if (!this._serverCapabilities?.prompts) { throw new Error(`Server does not support prompts (required for ${method})`); } break; case "resources/list": case "resources/templates/list": case "resources/read": case "resources/subscribe": case "resources/unsubscribe": if (!this._serverCapabilities?.resources) { throw new Error(`Server does not support resources (required for ${method})`); } if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) { throw new Error(`Server does not support resource subscriptions (required for ${method})`); } break; case "tools/call": case "tools/list": if (!this._serverCapabilities?.tools) { throw new Error(`Server does not support tools (required for ${method})`); } break; case "completion/complete": if (!this._serverCapabilities?.completions) { throw new Error(`Server does not support completions (required for ${method})`); } break; case "initialize": break; case "ping": break; } } assertNotificationCapability(method) { switch (method) { case "notifications/roots/list_changed": if (!this._capabilities.roots?.listChanged) { throw new Error(`Client does not support roots list changed notifications (required for ${method})`); } break; case "notifications/initialized": break; case "notifications/cancelled": break; case "notifications/progress": break; } } assertRequestHandlerCapability(method) { if (!this._capabilities) { return; } switch (method) { case "sampling/createMessage": if (!this._capabilities.sampling) { throw new Error(`Client does not support sampling capability (required for ${method})`); } break; case "elicitation/create": if (!this._capabilities.elicitation) { throw new Error(`Client does not support elicitation capability (required for ${method})`); } break; case "roots/list": if (!this._capabilities.roots) { throw new Error(`Client does not support roots capability (required for ${method})`); } break; case "tasks/get": case "tasks/list": case "tasks/result": case "tasks/cancel": if (!this._capabilities.tasks) { throw new Error(`Client does not support tasks capability (required for ${method})`); } break; case "ping": break; } } assertTaskCapability(method) { assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server"); } assertTaskHandlerCapability(method) { if (!this._capabilities) { return; } assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client"); } async ping(options) { return this.request({ method: "ping" }, EmptyResultSchema, options); } async complete(params, options) { return this.request({ method: "completion/complete", params }, CompleteResultSchema, options); } async setLoggingLevel(level, options) { return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options); } async getPrompt(params, options) { return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options); } async listPrompts(params, options) { return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options); } async listResources(params, options) { return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options); } async listResourceTemplates(params, options) { return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options); } async readResource(params, options) { return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options); } async subscribeResource(params, options) { return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options); } async unsubscribeResource(params, options) { return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options); } /** * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. * * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. */ async callTool(params, resultSchema = CallToolResultSchema, options) { if (this.isToolTaskRequired(params.name)) { throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`); } const result = await this.request({ method: "tools/call", params }, resultSchema, options); const validator = this.getToolOutputValidator(params.name); if (validator) { if (!result.structuredContent && !result.isError) { throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); } if (result.structuredContent) { try { const validationResult = validator(result.structuredContent); if (!validationResult.valid) { throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); } } catch (error48) { if (error48 instanceof McpError) { throw error48; } throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error48 instanceof Error ? error48.message : String(error48)}`); } } } return result; } isToolTask(toolName) { if (!this._serverCapabilities?.tasks?.requests?.tools?.call) { return false; } return this._cachedKnownTaskTools.has(toolName); } /** * Check if a tool requires task-based execution. * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. */ isToolTaskRequired(toolName) { return this._cachedRequiredTaskTools.has(toolName); } /** * Cache validators for tool output schemas. * Called after listTools() to pre-compile validators for better performance. */ cacheToolMetadata(tools) { this._cachedToolOutputValidators.clear(); this._cachedKnownTaskTools.clear(); this._cachedRequiredTaskTools.clear(); for (const tool of tools) { if (tool.outputSchema) { const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); this._cachedToolOutputValidators.set(tool.name, toolValidator); } const taskSupport = tool.execution?.taskSupport; if (taskSupport === "required" || taskSupport === "optional") { this._cachedKnownTaskTools.add(tool.name); } if (taskSupport === "required") { this._cachedRequiredTaskTools.add(tool.name); } } } /** * Get cached validator for a tool */ getToolOutputValidator(toolName) { return this._cachedToolOutputValidators.get(toolName); } async listTools(params, options) { const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options); this.cacheToolMetadata(result.tools); return result; } /** * Set up a single list changed handler. * @internal */ _setupListChangedHandler(listType, notificationSchema, options, fetcher) { const parseResult = ListChangedOptionsBaseSchema.safeParse(options); if (!parseResult.success) { throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); } if (typeof options.onChanged !== "function") { throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`); } const { autoRefresh, debounceMs } = parseResult.data; const { onChanged } = options; const refresh = async () => { if (!autoRefresh) { onChanged(null, null); return; } try { const items = await fetcher(); onChanged(null, items); } catch (e) { const error48 = e instanceof Error ? e : new Error(String(e)); onChanged(error48, null); } }; const handler = () => { if (debounceMs) { const existingTimer = this._listChangedDebounceTimers.get(listType); if (existingTimer) { clearTimeout(existingTimer); } const timer = setTimeout(refresh, debounceMs); this._listChangedDebounceTimers.set(listType, timer); } else { refresh(); } }; this.setNotificationHandler(notificationSchema, handler); } async sendRootsListChanged() { return this.notification({ method: "notifications/roots/list_changed" }); } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js var ExperimentalServerTasks = class { constructor(_server) { this._server = _server; } /** * Sends a request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * This method provides streaming access to request processing, allowing you to * observe intermediate task status updates for task-augmented requests. * * @param request - The request to send * @param resultSchema - Zod schema for validating the result * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ requestStream(request, resultSchema, options) { return this._server.requestStream(request, resultSchema, options); } /** * Sends a sampling request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages * before the final result. * * @example * ```typescript * const stream = server.experimental.tasks.createMessageStream({ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], * maxTokens: 100 * }, { * onprogress: (progress) => { * // Handle streaming tokens via progress notifications * console.log('Progress:', progress.message); * } * }); * * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('Final result:', message.result); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @param params - The sampling request parameters * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ createMessageStream(params, options) { const clientCapabilities = this._server.getClientCapabilities(); if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { throw new Error("Client does not support sampling tools capability."); } if (params.messages.length > 0) { const lastMessage = params.messages[params.messages.length - 1]; const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; const hasToolResults = lastContent.some((c) => c.type === "tool_result"); const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); if (hasToolResults) { if (lastContent.some((c) => c.type !== "tool_result")) { throw new Error("The last message must contain only tool_result content if any is present"); } if (!hasPreviousToolUse) { throw new Error("tool_result blocks are not matching any tool_use from the previous message"); } } if (hasPreviousToolUse) { const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); } } } return this.requestStream({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); } /** * Sends an elicitation request and returns an AsyncGenerator that yields response messages. * The generator is guaranteed to end with either a 'result' or 'error' message. * * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated' * and 'taskStatus' messages before the final result. * * @example * ```typescript * const stream = server.experimental.tasks.elicitInputStream({ * mode: 'url', * message: 'Please authenticate', * elicitationId: 'auth-123', * url: 'https://example.com/auth' * }, { * task: { ttl: 300000 } // Task-augmented for long-running auth flow * }); * * for await (const message of stream) { * switch (message.type) { * case 'taskCreated': * console.log('Task created:', message.task.taskId); * break; * case 'taskStatus': * console.log('Task status:', message.task.status); * break; * case 'result': * console.log('User action:', message.result.action); * break; * case 'error': * console.error('Error:', message.error); * break; * } * } * ``` * * @param params - The elicitation request parameters * @param options - Optional request options (timeout, signal, task creation params, etc.) * @returns AsyncGenerator that yields ResponseMessage objects * * @experimental */ elicitInputStream(params, options) { const clientCapabilities = this._server.getClientCapabilities(); const mode = params.mode ?? "form"; switch (mode) { case "url": { if (!clientCapabilities?.elicitation?.url) { throw new Error("Client does not support url elicitation."); } break; } case "form": { if (!clientCapabilities?.elicitation?.form) { throw new Error("Client does not support form elicitation."); } break; } } const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params; return this.requestStream({ method: "elicitation/create", params: normalizedParams }, ElicitResultSchema, options); } /** * Gets the current status of a task. * * @param taskId - The task identifier * @param options - Optional request options * @returns The task status * * @experimental */ async getTask(taskId, options) { return this._server.getTask({ taskId }, options); } /** * Retrieves the result of a completed task. * * @param taskId - The task identifier * @param resultSchema - Zod schema for validating the result * @param options - Optional request options * @returns The task result * * @experimental */ async getTaskResult(taskId, resultSchema, options) { return this._server.getTaskResult({ taskId }, resultSchema, options); } /** * Lists tasks with optional pagination. * * @param cursor - Optional pagination cursor * @param options - Optional request options * @returns List of tasks with optional next cursor * * @experimental */ async listTasks(cursor, options) { return this._server.listTasks(cursor ? { cursor } : void 0, options); } /** * Cancels a running task. * * @param taskId - The task identifier * @param options - Optional request options * * @experimental */ async cancelTask(taskId, options) { return this._server.cancelTask({ taskId }, options); } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js var Server = class extends Protocol { /** * Initializes this server with the given name and version information. */ constructor(_serverInfo, options) { super(options); this._serverInfo = _serverInfo; this._loggingLevels = /* @__PURE__ */ new Map(); this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); this.isMessageIgnored = (level, sessionId) => { const currentLevel = this._loggingLevels.get(sessionId); return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; }; this._capabilities = options?.capabilities ?? {}; this._instructions = options?.instructions; this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request)); this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); if (this._capabilities.logging) { this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0; const { level } = request.params; const parseResult = LoggingLevelSchema.safeParse(level); if (parseResult.success) { this._loggingLevels.set(transportSessionId, parseResult.data); } return {}; }); } } /** * Access experimental features. * * WARNING: These APIs are experimental and may change without notice. * * @experimental */ get experimental() { if (!this._experimental) { this._experimental = { tasks: new ExperimentalServerTasks(this) }; } return this._experimental; } /** * Registers new capabilities. This can only be called before connecting to a transport. * * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). */ registerCapabilities(capabilities) { if (this.transport) { throw new Error("Cannot register capabilities after connecting to transport"); } this._capabilities = mergeCapabilities(this._capabilities, capabilities); } /** * Override request handler registration to enforce server-side validation for tools/call. */ setRequestHandler(requestSchema, handler) { const shape = getObjectShape(requestSchema); const methodSchema = shape?.method; if (!methodSchema) { throw new Error("Schema is missing a method literal"); } let methodValue; if (isZ4Schema(methodSchema)) { const v4Schema = methodSchema; const v4Def = v4Schema._zod?.def; methodValue = v4Def?.value ?? v4Schema.value; } else { const v3Schema = methodSchema; const legacyDef = v3Schema._def; methodValue = legacyDef?.value ?? v3Schema.value; } if (typeof methodValue !== "string") { throw new Error("Schema method literal must be a string"); } const method = methodValue; if (method === "tools/call") { const wrappedHandler = async (request, extra) => { const validatedRequest = safeParse3(CallToolRequestSchema, request); if (!validatedRequest.success) { const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); } const { params } = validatedRequest.data; const result = await Promise.resolve(handler(request, extra)); if (params.task) { const taskValidationResult = safeParse3(CreateTaskResultSchema, result); if (!taskValidationResult.success) { const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); } return taskValidationResult.data; } const validationResult = safeParse3(CallToolResultSchema, result); if (!validationResult.success) { const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); } return validationResult.data; }; return super.setRequestHandler(requestSchema, wrappedHandler); } return super.setRequestHandler(requestSchema, handler); } assertCapabilityForMethod(method) { switch (method) { case "sampling/createMessage": if (!this._clientCapabilities?.sampling) { throw new Error(`Client does not support sampling (required for ${method})`); } break; case "elicitation/create": if (!this._clientCapabilities?.elicitation) { throw new Error(`Client does not support elicitation (required for ${method})`); } break; case "roots/list": if (!this._clientCapabilities?.roots) { throw new Error(`Client does not support listing roots (required for ${method})`); } break; case "ping": break; } } assertNotificationCapability(method) { switch (method) { case "notifications/message": if (!this._capabilities.logging) { throw new Error(`Server does not support logging (required for ${method})`); } break; case "notifications/resources/updated": case "notifications/resources/list_changed": if (!this._capabilities.resources) { throw new Error(`Server does not support notifying about resources (required for ${method})`); } break; case "notifications/tools/list_changed": if (!this._capabilities.tools) { throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); } break; case "notifications/prompts/list_changed": if (!this._capabilities.prompts) { throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); } break; case "notifications/elicitation/complete": if (!this._clientCapabilities?.elicitation?.url) { throw new Error(`Client does not support URL elicitation (required for ${method})`); } break; case "notifications/cancelled": break; case "notifications/progress": break; } } assertRequestHandlerCapability(method) { if (!this._capabilities) { return; } switch (method) { case "completion/complete": if (!this._capabilities.completions) { throw new Error(`Server does not support completions (required for ${method})`); } break; case "logging/setLevel": if (!this._capabilities.logging) { throw new Error(`Server does not support logging (required for ${method})`); } break; case "prompts/get": case "prompts/list": if (!this._capabilities.prompts) { throw new Error(`Server does not support prompts (required for ${method})`); } break; case "resources/list": case "resources/templates/list": case "resources/read": if (!this._capabilities.resources) { throw new Error(`Server does not support resources (required for ${method})`); } break; case "tools/call": case "tools/list": if (!this._capabilities.tools) { throw new Error(`Server does not support tools (required for ${method})`); } break; case "tasks/get": case "tasks/list": case "tasks/result": case "tasks/cancel": if (!this._capabilities.tasks) { throw new Error(`Server does not support tasks capability (required for ${method})`); } break; case "ping": case "initialize": break; } } assertTaskCapability(method) { assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client"); } assertTaskHandlerCapability(method) { if (!this._capabilities) { return; } assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server"); } async _oninitialize(request) { const requestedVersion = request.params.protocolVersion; this._clientCapabilities = request.params.capabilities; this._clientVersion = request.params.clientInfo; const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; return { protocolVersion, capabilities: this.getCapabilities(), serverInfo: this._serverInfo, ...this._instructions && { instructions: this._instructions } }; } /** * After initialization has completed, this will be populated with the client's reported capabilities. */ getClientCapabilities() { return this._clientCapabilities; } /** * After initialization has completed, this will be populated with information about the client's name and version. */ getClientVersion() { return this._clientVersion; } getCapabilities() { return this._capabilities; } async ping() { return this.request({ method: "ping" }, EmptyResultSchema); } // Implementation async createMessage(params, options) { if (params.tools || params.toolChoice) { if (!this._clientCapabilities?.sampling?.tools) { throw new Error("Client does not support sampling tools capability."); } } if (params.messages.length > 0) { const lastMessage = params.messages[params.messages.length - 1]; const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; const hasToolResults = lastContent.some((c) => c.type === "tool_result"); const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); if (hasToolResults) { if (lastContent.some((c) => c.type !== "tool_result")) { throw new Error("The last message must contain only tool_result content if any is present"); } if (!hasPreviousToolUse) { throw new Error("tool_result blocks are not matching any tool_use from the previous message"); } } if (hasPreviousToolUse) { const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); } } } if (params.tools) { return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options); } return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); } /** * Creates an elicitation request for the given parameters. * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. * @param params The parameters for the elicitation request. * @param options Optional request options. * @returns The result of the elicitation request. */ async elicitInput(params, options) { const mode = params.mode ?? "form"; switch (mode) { case "url": { if (!this._clientCapabilities?.elicitation?.url) { throw new Error("Client does not support url elicitation."); } const urlParams = params; return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options); } case "form": { if (!this._clientCapabilities?.elicitation?.form) { throw new Error("Client does not support form elicitation."); } const formParams = params.mode === "form" ? params : { ...params, mode: "form" }; const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options); if (result.action === "accept" && result.content && formParams.requestedSchema) { try { const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); const validationResult = validator(result.content); if (!validationResult.valid) { throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); } } catch (error48) { if (error48 instanceof McpError) { throw error48; } throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error48 instanceof Error ? error48.message : String(error48)}`); } } return result; } } } /** * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` * notification for the specified elicitation ID. * * @param elicitationId The ID of the elicitation to mark as complete. * @param options Optional notification options. Useful when the completion notification should be related to a prior request. * @returns A function that emits the completion notification when awaited. */ createElicitationCompletionNotifier(elicitationId, options) { if (!this._clientCapabilities?.elicitation?.url) { throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)"); } return () => this.notification({ method: "notifications/elicitation/complete", params: { elicitationId } }, options); } async listRoots(params, options) { return this.request({ method: "roots/list", params }, ListRootsResultSchema, options); } /** * Sends a logging message to the client, if connected. * Note: You only need to send the parameters object, not the entire JSON RPC message * @see LoggingMessageNotification * @param params * @param sessionId optional for stateless and backward compatibility */ async sendLoggingMessage(params, sessionId) { if (this._capabilities.logging) { if (!this.isMessageIgnored(params.level, sessionId)) { return this.notification({ method: "notifications/message", params }); } } } async sendResourceUpdated(params) { return this.notification({ method: "notifications/resources/updated", params }); } async sendResourceListChanged() { return this.notification({ method: "notifications/resources/list_changed" }); } async sendToolListChanged() { return this.notification({ method: "notifications/tools/list_changed" }); } async sendPromptListChanged() { return this.notification({ method: "notifications/prompts/list_changed" }); } }; // node_modules/eventsource-parser/dist/index.js var ParseError = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; function noop(_arg) { } function createParser(callbacks) { if (typeof callbacks == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; function feed(newChunk) { const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines2(`${incompleteLine}${chunk}`); for (const line of complete) parseLine(line); incompleteLine = incomplete, isFirstChunk = false; } function parseLine(line) { if (line === "") { dispatchEvent(); return; } if (line.startsWith(":")) { onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); return; } const fieldSeparatorIndex = line.indexOf(":"); if (fieldSeparatorIndex !== -1) { const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); processField(field, value, line); return; } processField(line, "", line); } function processField(field, value, line) { switch (field) { case "event": eventType = value; break; case "data": data = `${data}${value} `; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line } ) ); break; } } function dispatchEvent() { data.length > 0 && onEvent({ id, event: eventType || void 0, // If the data buffer's last character is a U+000A LINE FEED (LF) character, // then remove the last character from the data buffer. data: data.endsWith(` `) ? data.slice(0, -1) : data }), id = void 0, data = "", eventType = ""; } function reset(options = {}) { incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = ""; } return { feed, reset }; } function splitLines2(chunk) { const lines = []; let incompleteLine = "", searchIndex = 0; for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) { incompleteLine = chunk.slice(searchIndex); break; } else { const line = chunk.slice(searchIndex, lineEnd); lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === ` ` && searchIndex++; } } return [lines, incompleteLine]; } // node_modules/eventsource/dist/index.js var ErrorEvent = class extends Event { /** * Constructs a new `ErrorEvent` instance. This is typically not called directly, * but rather emitted by the `EventSource` object when an error occurs. * * @param type - The type of the event (should be "error") * @param errorEventInitDict - Optional properties to include in the error event */ constructor(type, errorEventInitDict) { var _a2, _b; super(type), this.code = (_a2 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a2 : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0; } /** * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance, * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, * we explicitly include the properties in the `inspect` method. * * This is automatically called by Node.js when you `console.log` an instance of this class. * * @param _depth - The current depth * @param options - The options passed to `util.inspect` * @param inspect - The inspect function to use (prevents having to import it from `util`) * @returns A string representation of the error */ [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) { return inspect(inspectableError(this), options); } /** * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance, * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, * we explicitly include the properties in the `inspect` method. * * This is automatically called by Deno when you `console.log` an instance of this class. * * @param inspect - The inspect function to use (prevents having to import it from `util`) * @param options - The options passed to `Deno.inspect` * @returns A string representation of the error */ [Symbol.for("Deno.customInspect")](inspect, options) { return inspect(inspectableError(this), options); } }; function syntaxError(message) { const DomException = globalThis.DOMException; return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message); } function flattenError2(err) { return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError2).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError2(err.cause)}` : err.message : `${err}`; } function inspectableError(err) { return { type: err.type, message: err.message, code: err.code, defaultPrevented: err.defaultPrevented, cancelable: err.cancelable, timeStamp: err.timeStamp }; } var __typeError = (msg) => { throw TypeError(msg); }; var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); var _readyState; var _url2; var _redirectUrl; var _withCredentials; var _fetch; var _reconnectInterval; var _reconnectTimer; var _lastEventId; var _controller; var _parser; var _onError; var _onMessage; var _onOpen; var _EventSource_instances; var connect_fn; var _onFetchResponse; var _onFetchError; var getRequestOptions_fn; var _onEvent; var _onRetryChange; var failConnection_fn; var scheduleReconnect_fn; var _reconnect; var EventSource = class extends EventTarget { constructor(url2, eventSourceInitDict) { var _a2, _b; super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url2), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => { var _a22; __privateGet(this, _parser).reset(); const { body, redirected, status, headers } = response; if (status === 204) { __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close(); return; } if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) { __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status); return; } if (!(headers.get("content-type") || "").startsWith("text/event-stream")) { __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status); return; } if (__privateGet(this, _readyState) === this.CLOSED) return; __privateSet(this, _readyState, this.OPEN); const openEvent = new Event("open"); if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) { __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close(); return; } const decoder = new TextDecoder(), reader = body.getReader(); let open2 = true; do { const { done, value } = await reader.read(); value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open2 = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this)); } while (open2); }), __privateAdd(this, _onFetchError, (err) => { __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err)); }), __privateAdd(this, _onEvent, (event) => { typeof event.id == "string" && __privateSet(this, _lastEventId, event.id); const messageEvent = new MessageEvent(event.event || "message", { data: event.data, origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url2).origin, lastEventId: event.id || "" }); __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent); }), __privateAdd(this, _onRetryChange, (value) => { __privateSet(this, _reconnectInterval, value); }), __privateAdd(this, _reconnect, () => { __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this); }); try { if (url2 instanceof URL) __privateSet(this, _url2, url2); else if (typeof url2 == "string") __privateSet(this, _url2, new URL(url2, getBaseURL())); else throw new Error("Invalid URL"); } catch { throw syntaxError("An invalid or illegal string was specified"); } __privateSet(this, _parser, createParser({ onEvent: __privateGet(this, _onEvent), onRetry: __privateGet(this, _onRetryChange) })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a2 : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this); } /** * Returns the state of this EventSource object's connection. It can have the values described below. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) * * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface, * defined in the TypeScript `dom` library. * * @public */ get readyState() { return __privateGet(this, _readyState); } /** * Returns the URL providing the event stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) * * @public */ get url() { return __privateGet(this, _url2).href; } /** * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) */ get withCredentials() { return __privateGet(this, _withCredentials); } /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ get onerror() { return __privateGet(this, _onError); } set onerror(value) { __privateSet(this, _onError, value); } /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ get onmessage() { return __privateGet(this, _onMessage); } set onmessage(value) { __privateSet(this, _onMessage, value); } /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ get onopen() { return __privateGet(this, _onOpen); } set onopen(value) { __privateSet(this, _onOpen, value); } addEventListener(type, listener, options) { const listen = listener; super.addEventListener(type, listen, options); } removeEventListener(type, listener, options) { const listen = listener; super.removeEventListener(type, listen, options); } /** * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) * * @public */ close() { __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0)); } }; _readyState = /* @__PURE__ */ new WeakMap(), _url2 = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /** * Connect to the given URL and start receiving events * * @internal */ connect_fn = function() { __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url2), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError)); }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /** * Get request options for the `fetch()` request * * @returns The request options * @internal */ getRequestOptions_fn = function() { var _a2; const init = { // [spec] Let `corsAttributeState` be `Anonymous`… // [spec] …will have their mode set to "cors"… mode: "cors", redirect: "follow", headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 }, cache: "no-store", signal: (_a2 = __privateGet(this, _controller)) == null ? void 0 : _a2.signal }; return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init; }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /** * Handles the process referred to in the EventSource specification as "failing a connection". * * @param error - The error causing the connection to fail * @param code - The HTTP status code, if available * @internal */ failConnection_fn = function(message, code) { var _a2; __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED); const errorEvent = new ErrorEvent("error", { code, message }); (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent); }, /** * Schedules a reconnection attempt against the EventSource endpoint. * * @param message - The error causing the connection to fail * @param code - The HTTP status code, if available * @internal */ scheduleReconnect_fn = function(message, code) { var _a2; if (__privateGet(this, _readyState) === this.CLOSED) return; __privateSet(this, _readyState, this.CONNECTING); const errorEvent = new ErrorEvent("error", { code, message }); (_a2 = __privateGet(this, _onError)) == null || _a2.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval))); }, _reconnect = /* @__PURE__ */ new WeakMap(), /** * ReadyState representing an EventSource currently trying to connect * * @public */ EventSource.CONNECTING = 0, /** * ReadyState representing an EventSource connection that is open (eg connected) * * @public */ EventSource.OPEN = 1, /** * ReadyState representing an EventSource connection that is closed (eg disconnected) * * @public */ EventSource.CLOSED = 2; function getBaseURL() { const doc = "document" in globalThis ? globalThis.document : void 0; return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0; } // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js function normalizeHeaders(headers) { if (!headers) return {}; if (headers instanceof Headers) { return Object.fromEntries(headers.entries()); } if (Array.isArray(headers)) { return Object.fromEntries(headers); } return { ...headers }; } function createFetchWithInit(baseFetch = fetch, baseInit) { if (!baseInit) { return baseFetch; } return async (url2, init) => { const mergedInit = { ...baseInit, ...init, // Headers need special handling - merge instead of replace headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers }; return baseFetch(url2, mergedInit); }; } // node_modules/pkce-challenge/dist/index.node.js var crypto2; crypto2 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL globalThis.crypto ?? // Node.js >18 import("node:crypto").then((m) => m.webcrypto); async function getRandomValues(size) { return (await crypto2).getRandomValues(new Uint8Array(size)); } async function random(size) { const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; let result = ""; const randomUints = await getRandomValues(size); for (let i = 0; i < size; i++) { const randomIndex = randomUints[i] % mask.length; result += mask[randomIndex]; } return result; } async function generateVerifier(length) { return await random(length); } async function generateChallenge(code_verifier) { const buffer = await (await crypto2).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, ""); } async function pkceChallenge(length) { if (!length) length = 43; if (length < 43 || length > 128) { throw `Expected a length between 43 and 128. Received ${length}.`; } const verifier = await generateVerifier(length); const challenge = await generateChallenge(verifier); return { code_verifier: verifier, code_challenge: challenge }; } // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js var SafeUrlSchema = url().superRefine((val, ctx) => { if (!URL.canParse(val)) { ctx.addIssue({ code: ZodIssueCode.custom, message: "URL must be parseable", fatal: true }); return NEVER; } }).refine((url2) => { const u = new URL(url2); return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); var OAuthProtectedResourceMetadataSchema = looseObject({ resource: string2().url(), authorization_servers: array(SafeUrlSchema).optional(), jwks_uri: string2().url().optional(), scopes_supported: array(string2()).optional(), bearer_methods_supported: array(string2()).optional(), resource_signing_alg_values_supported: array(string2()).optional(), resource_name: string2().optional(), resource_documentation: string2().optional(), resource_policy_uri: string2().url().optional(), resource_tos_uri: string2().url().optional(), tls_client_certificate_bound_access_tokens: boolean2().optional(), authorization_details_types_supported: array(string2()).optional(), dpop_signing_alg_values_supported: array(string2()).optional(), dpop_bound_access_tokens_required: boolean2().optional() }); var OAuthMetadataSchema = looseObject({ issuer: string2(), authorization_endpoint: SafeUrlSchema, token_endpoint: SafeUrlSchema, registration_endpoint: SafeUrlSchema.optional(), scopes_supported: array(string2()).optional(), response_types_supported: array(string2()), response_modes_supported: array(string2()).optional(), grant_types_supported: array(string2()).optional(), token_endpoint_auth_methods_supported: array(string2()).optional(), token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), service_documentation: SafeUrlSchema.optional(), revocation_endpoint: SafeUrlSchema.optional(), revocation_endpoint_auth_methods_supported: array(string2()).optional(), revocation_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), introspection_endpoint: string2().optional(), introspection_endpoint_auth_methods_supported: array(string2()).optional(), introspection_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), code_challenge_methods_supported: array(string2()).optional(), client_id_metadata_document_supported: boolean2().optional() }); var OpenIdProviderMetadataSchema = looseObject({ issuer: string2(), authorization_endpoint: SafeUrlSchema, token_endpoint: SafeUrlSchema, userinfo_endpoint: SafeUrlSchema.optional(), jwks_uri: SafeUrlSchema, registration_endpoint: SafeUrlSchema.optional(), scopes_supported: array(string2()).optional(), response_types_supported: array(string2()), response_modes_supported: array(string2()).optional(), grant_types_supported: array(string2()).optional(), acr_values_supported: array(string2()).optional(), subject_types_supported: array(string2()), id_token_signing_alg_values_supported: array(string2()), id_token_encryption_alg_values_supported: array(string2()).optional(), id_token_encryption_enc_values_supported: array(string2()).optional(), userinfo_signing_alg_values_supported: array(string2()).optional(), userinfo_encryption_alg_values_supported: array(string2()).optional(), userinfo_encryption_enc_values_supported: array(string2()).optional(), request_object_signing_alg_values_supported: array(string2()).optional(), request_object_encryption_alg_values_supported: array(string2()).optional(), request_object_encryption_enc_values_supported: array(string2()).optional(), token_endpoint_auth_methods_supported: array(string2()).optional(), token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), display_values_supported: array(string2()).optional(), claim_types_supported: array(string2()).optional(), claims_supported: array(string2()).optional(), service_documentation: string2().optional(), claims_locales_supported: array(string2()).optional(), ui_locales_supported: array(string2()).optional(), claims_parameter_supported: boolean2().optional(), request_parameter_supported: boolean2().optional(), request_uri_parameter_supported: boolean2().optional(), require_request_uri_registration: boolean2().optional(), op_policy_uri: SafeUrlSchema.optional(), op_tos_uri: SafeUrlSchema.optional(), client_id_metadata_document_supported: boolean2().optional() }); var OpenIdProviderDiscoveryMetadataSchema = object({ ...OpenIdProviderMetadataSchema.shape, ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape }); var OAuthTokensSchema = object({ access_token: string2(), id_token: string2().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect token_type: string2(), expires_in: coerce_exports.number().optional(), scope: string2().optional(), refresh_token: string2().optional() }).strip(); var OAuthErrorResponseSchema = object({ error: string2(), error_description: string2().optional(), error_uri: string2().optional() }); var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); var OAuthClientMetadataSchema = object({ redirect_uris: array(SafeUrlSchema), token_endpoint_auth_method: string2().optional(), grant_types: array(string2()).optional(), response_types: array(string2()).optional(), client_name: string2().optional(), client_uri: SafeUrlSchema.optional(), logo_uri: OptionalSafeUrlSchema, scope: string2().optional(), contacts: array(string2()).optional(), tos_uri: OptionalSafeUrlSchema, policy_uri: string2().optional(), jwks_uri: SafeUrlSchema.optional(), jwks: any().optional(), software_id: string2().optional(), software_version: string2().optional(), software_statement: string2().optional() }).strip(); var OAuthClientInformationSchema = object({ client_id: string2(), client_secret: string2().optional(), client_id_issued_at: number2().optional(), client_secret_expires_at: number2().optional() }).strip(); var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); var OAuthClientRegistrationErrorSchema = object({ error: string2(), error_description: string2().optional() }).strip(); var OAuthTokenRevocationRequestSchema = object({ token: string2(), token_type_hint: string2().optional() }).strip(); // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js function resourceUrlFromServerUrl(url2) { const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href); resourceURL.hash = ""; return resourceURL; } function checkResourceAllowed({ requestedResource, configuredResource }) { const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); if (requested.origin !== configured.origin) { return false; } if (requested.pathname.length < configured.pathname.length) { return false; } const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; return requestedPath.startsWith(configuredPath); } // node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js var OAuthError = class extends Error { constructor(message, errorUri) { super(message); this.errorUri = errorUri; this.name = this.constructor.name; } /** * Converts the error to a standard OAuth error response object */ toResponseObject() { const response = { error: this.errorCode, error_description: this.message }; if (this.errorUri) { response.error_uri = this.errorUri; } return response; } get errorCode() { return this.constructor.errorCode; } }; var InvalidRequestError = class extends OAuthError { }; InvalidRequestError.errorCode = "invalid_request"; var InvalidClientError = class extends OAuthError { }; InvalidClientError.errorCode = "invalid_client"; var InvalidGrantError = class extends OAuthError { }; InvalidGrantError.errorCode = "invalid_grant"; var UnauthorizedClientError = class extends OAuthError { }; UnauthorizedClientError.errorCode = "unauthorized_client"; var UnsupportedGrantTypeError = class extends OAuthError { }; UnsupportedGrantTypeError.errorCode = "unsupported_grant_type"; var InvalidScopeError = class extends OAuthError { }; InvalidScopeError.errorCode = "invalid_scope"; var AccessDeniedError = class extends OAuthError { }; AccessDeniedError.errorCode = "access_denied"; var ServerError = class extends OAuthError { }; ServerError.errorCode = "server_error"; var TemporarilyUnavailableError = class extends OAuthError { }; TemporarilyUnavailableError.errorCode = "temporarily_unavailable"; var UnsupportedResponseTypeError = class extends OAuthError { }; UnsupportedResponseTypeError.errorCode = "unsupported_response_type"; var UnsupportedTokenTypeError = class extends OAuthError { }; UnsupportedTokenTypeError.errorCode = "unsupported_token_type"; var InvalidTokenError = class extends OAuthError { }; InvalidTokenError.errorCode = "invalid_token"; var MethodNotAllowedError = class extends OAuthError { }; MethodNotAllowedError.errorCode = "method_not_allowed"; var TooManyRequestsError = class extends OAuthError { }; TooManyRequestsError.errorCode = "too_many_requests"; var InvalidClientMetadataError = class extends OAuthError { }; InvalidClientMetadataError.errorCode = "invalid_client_metadata"; var InsufficientScopeError = class extends OAuthError { }; InsufficientScopeError.errorCode = "insufficient_scope"; var InvalidTargetError = class extends OAuthError { }; InvalidTargetError.errorCode = "invalid_target"; var OAUTH_ERRORS = { [InvalidRequestError.errorCode]: InvalidRequestError, [InvalidClientError.errorCode]: InvalidClientError, [InvalidGrantError.errorCode]: InvalidGrantError, [UnauthorizedClientError.errorCode]: UnauthorizedClientError, [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, [InvalidScopeError.errorCode]: InvalidScopeError, [AccessDeniedError.errorCode]: AccessDeniedError, [ServerError.errorCode]: ServerError, [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, [InvalidTokenError.errorCode]: InvalidTokenError, [MethodNotAllowedError.errorCode]: MethodNotAllowedError, [TooManyRequestsError.errorCode]: TooManyRequestsError, [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, [InsufficientScopeError.errorCode]: InsufficientScopeError, [InvalidTargetError.errorCode]: InvalidTargetError }; // node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js var UnauthorizedError = class extends Error { constructor(message) { super(message ?? "Unauthorized"); } }; function isClientAuthMethod(method) { return ["client_secret_basic", "client_secret_post", "none"].includes(method); } var AUTHORIZATION_CODE_RESPONSE_TYPE = "code"; var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256"; function selectClientAuthMethod(clientInformation, supportedMethods) { const hasClientSecret = clientInformation.client_secret !== void 0; if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) { return clientInformation.token_endpoint_auth_method; } if (supportedMethods.length === 0) { return hasClientSecret ? "client_secret_basic" : "none"; } if (hasClientSecret && supportedMethods.includes("client_secret_basic")) { return "client_secret_basic"; } if (hasClientSecret && supportedMethods.includes("client_secret_post")) { return "client_secret_post"; } if (supportedMethods.includes("none")) { return "none"; } return hasClientSecret ? "client_secret_post" : "none"; } function applyClientAuthentication(method, clientInformation, headers, params) { const { client_id, client_secret } = clientInformation; switch (method) { case "client_secret_basic": applyBasicAuth(client_id, client_secret, headers); return; case "client_secret_post": applyPostAuth(client_id, client_secret, params); return; case "none": applyPublicAuth(client_id, params); return; default: throw new Error(`Unsupported client authentication method: ${method}`); } } function applyBasicAuth(clientId, clientSecret, headers) { if (!clientSecret) { throw new Error("client_secret_basic authentication requires a client_secret"); } const credentials = btoa(`${clientId}:${clientSecret}`); headers.set("Authorization", `Basic ${credentials}`); } function applyPostAuth(clientId, clientSecret, params) { params.set("client_id", clientId); if (clientSecret) { params.set("client_secret", clientSecret); } } function applyPublicAuth(clientId, params) { params.set("client_id", clientId); } async function parseErrorResponse(input) { const statusCode = input instanceof Response ? input.status : void 0; const body = input instanceof Response ? await input.text() : input; try { const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); const { error: error48, error_description, error_uri } = result; const errorClass = OAUTH_ERRORS[error48] || ServerError; return new errorClass(error_description || "", error_uri); } catch (error48) { const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error48}. Raw body: ${body}`; return new ServerError(errorMessage); } } async function auth(provider, options) { try { return await authInternal(provider, options); } catch (error48) { if (error48 instanceof InvalidClientError || error48 instanceof UnauthorizedClientError) { await provider.invalidateCredentials?.("all"); return await authInternal(provider, options); } else if (error48 instanceof InvalidGrantError) { await provider.invalidateCredentials?.("tokens"); return await authInternal(provider, options); } throw error48; } } async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { const cachedState = await provider.discoveryState?.(); let resourceMetadata; let authorizationServerUrl; let metadata; let effectiveResourceMetadataUrl = resourceMetadataUrl; if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) { effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl); } if (cachedState?.authorizationServerUrl) { authorizationServerUrl = cachedState.authorizationServerUrl; resourceMetadata = cachedState.resourceMetadata; metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn }); if (!resourceMetadata) { try { resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn); } catch { } } if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) { await provider.saveDiscoveryState?.({ authorizationServerUrl: String(authorizationServerUrl), resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), resourceMetadata, authorizationServerMetadata: metadata }); } } else { const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn }); authorizationServerUrl = serverInfo.authorizationServerUrl; metadata = serverInfo.authorizationServerMetadata; resourceMetadata = serverInfo.resourceMetadata; await provider.saveDiscoveryState?.({ authorizationServerUrl: String(authorizationServerUrl), resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), resourceMetadata, authorizationServerMetadata: metadata }); } const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope; let clientInformation = await Promise.resolve(provider.clientInformation()); if (!clientInformation) { if (authorizationCode !== void 0) { throw new Error("Existing OAuth client information is required when exchanging an authorization code"); } const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true; const clientMetadataUrl = provider.clientMetadataUrl; if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); } const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; if (shouldUseUrlBasedClientId) { clientInformation = { client_id: clientMetadataUrl }; await provider.saveClientInformation?.(clientInformation); } else { if (!provider.saveClientInformation) { throw new Error("OAuth client information must be saveable for dynamic registration"); } const fullInformation = await registerClient(authorizationServerUrl, { metadata, clientMetadata: provider.clientMetadata, scope: resolvedScope, fetchFn }); await provider.saveClientInformation(fullInformation); clientInformation = fullInformation; } } const nonInteractiveFlow = !provider.redirectUrl; if (authorizationCode !== void 0 || nonInteractiveFlow) { const tokens2 = await fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn }); await provider.saveTokens(tokens2); return "AUTHORIZED"; } const tokens = await provider.tokens(); if (tokens?.refresh_token) { try { const newTokens = await refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken: tokens.refresh_token, resource, addClientAuthentication: provider.addClientAuthentication, fetchFn }); await provider.saveTokens(newTokens); return "AUTHORIZED"; } catch (error48) { if (!(error48 instanceof OAuthError) || error48 instanceof ServerError) { } else { throw error48; } } } const state = provider.state ? await provider.state() : void 0; const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { metadata, clientInformation, state, redirectUrl: provider.redirectUrl, scope: resolvedScope, resource }); await provider.saveCodeVerifier(codeVerifier); await provider.redirectToAuthorization(authorizationUrl); return "REDIRECT"; } function isHttpsUrl(value) { if (!value) return false; try { const url2 = new URL(value); return url2.protocol === "https:" && url2.pathname !== "/"; } catch { return false; } } async function selectResourceURL(serverUrl, provider, resourceMetadata) { const defaultResource = resourceUrlFromServerUrl(serverUrl); if (provider.validateResourceURL) { return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); } if (!resourceMetadata) { return void 0; } if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); } return new URL(resourceMetadata.resource); } function extractWWWAuthenticateParams(res) { const authenticateHeader = res.headers.get("WWW-Authenticate"); if (!authenticateHeader) { return {}; } const [type, scheme] = authenticateHeader.split(" "); if (type.toLowerCase() !== "bearer" || !scheme) { return {}; } const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0; let resourceMetadataUrl; if (resourceMetadataMatch) { try { resourceMetadataUrl = new URL(resourceMetadataMatch); } catch { } } const scope = extractFieldFromWwwAuth(res, "scope") || void 0; const error48 = extractFieldFromWwwAuth(res, "error") || void 0; return { resourceMetadataUrl, scope, error: error48 }; } function extractFieldFromWwwAuth(response, fieldName) { const wwwAuthHeader = response.headers.get("WWW-Authenticate"); if (!wwwAuthHeader) { return null; } const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); const match = wwwAuthHeader.match(pattern); if (match) { return match[1] || match[2]; } return null; } async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, { protocolVersion: opts?.protocolVersion, metadataUrl: opts?.resourceMetadataUrl }); if (!response || response.status === 404) { await response?.body?.cancel(); throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); } if (!response.ok) { await response.body?.cancel(); throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); } return OAuthProtectedResourceMetadataSchema.parse(await response.json()); } async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) { try { return await fetchFn(url2, { headers }); } catch (error48) { if (error48 instanceof TypeError) { if (headers) { return fetchWithCorsRetry(url2, void 0, fetchFn); } else { return void 0; } } throw error48; } } function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) { if (pathname.endsWith("/")) { pathname = pathname.slice(0, -1); } return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; } async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) { const headers = { "MCP-Protocol-Version": protocolVersion }; return await fetchWithCorsRetry(url2, headers, fetchFn); } function shouldAttemptFallback(response, pathname) { return !response || response.status >= 400 && response.status < 500 && pathname !== "/"; } async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { const issuer = new URL(serverUrl); const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION; let url2; if (opts?.metadataUrl) { url2 = new URL(opts.metadataUrl); } else { const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); url2.search = issuer.search; } let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn); if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) { const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); } return response; } function buildDiscoveryUrls(authorizationServerUrl) { const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl; const hasPath = url2.pathname !== "/"; const urlsToTry = []; if (!hasPath) { urlsToTry.push({ url: new URL("/.well-known/oauth-authorization-server", url2.origin), type: "oauth" }); urlsToTry.push({ url: new URL(`/.well-known/openid-configuration`, url2.origin), type: "oidc" }); return urlsToTry; } let pathname = url2.pathname; if (pathname.endsWith("/")) { pathname = pathname.slice(0, -1); } urlsToTry.push({ url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin), type: "oauth" }); urlsToTry.push({ url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin), type: "oidc" }); urlsToTry.push({ url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin), type: "oidc" }); return urlsToTry; } async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) { const headers = { "MCP-Protocol-Version": protocolVersion, Accept: "application/json" }; const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); for (const { url: endpointUrl, type } of urlsToTry) { const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); if (!response) { continue; } if (!response.ok) { await response.body?.cancel(); if (response.status >= 400 && response.status < 500) { continue; } throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`); } if (type === "oauth") { return OAuthMetadataSchema.parse(await response.json()); } else { return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); } } return void 0; } async function discoverOAuthServerInfo(serverUrl, opts) { let resourceMetadata; let authorizationServerUrl; try { resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn); if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { authorizationServerUrl = resourceMetadata.authorization_servers[0]; } } catch { } if (!authorizationServerUrl) { authorizationServerUrl = String(new URL("/", serverUrl)); } const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn }); return { authorizationServerUrl, authorizationServerMetadata, resourceMetadata }; } async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { let authorizationUrl; if (metadata) { authorizationUrl = new URL(metadata.authorization_endpoint); if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); } if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); } } else { authorizationUrl = new URL("/authorize", authorizationServerUrl); } const challenge = await pkceChallenge(); const codeVerifier = challenge.code_verifier; const codeChallenge = challenge.code_challenge; authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE); authorizationUrl.searchParams.set("client_id", clientInformation.client_id); authorizationUrl.searchParams.set("code_challenge", codeChallenge); authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD); authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl)); if (state) { authorizationUrl.searchParams.set("state", state); } if (scope) { authorizationUrl.searchParams.set("scope", scope); } if (scope?.includes("offline_access")) { authorizationUrl.searchParams.append("prompt", "consent"); } if (resource) { authorizationUrl.searchParams.set("resource", resource.href); } return { authorizationUrl, codeVerifier }; } function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { return new URLSearchParams({ grant_type: "authorization_code", code: authorizationCode, code_verifier: codeVerifier, redirect_uri: String(redirectUri) }); } async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl); const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }); if (resource) { tokenRequestParams.set("resource", resource.href); } if (addClientAuthentication) { await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); } else if (clientInformation) { const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []; const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams); } const response = await (fetchFn ?? fetch)(tokenUrl, { method: "POST", headers, body: tokenRequestParams }); if (!response.ok) { throw await parseErrorResponse(response); } return OAuthTokensSchema.parse(await response.json()); } async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { const tokenRequestParams = new URLSearchParams({ grant_type: "refresh_token", refresh_token: refreshToken }); const tokens = await executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }); return { refresh_token: refreshToken, ...tokens }; } async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) { const scope = provider.clientMetadata.scope; let tokenRequestParams; if (provider.prepareTokenRequest) { tokenRequestParams = await provider.prepareTokenRequest(scope); } if (!tokenRequestParams) { if (!authorizationCode) { throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required"); } if (!provider.redirectUrl) { throw new Error("redirectUrl is required for authorization_code flow"); } const codeVerifier = await provider.codeVerifier(); tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl); } const clientInformation = await provider.clientInformation(); return executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation: clientInformation ?? void 0, addClientAuthentication: provider.addClientAuthentication, resource, fetchFn }); } async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) { let registrationUrl; if (metadata) { if (!metadata.registration_endpoint) { throw new Error("Incompatible auth server: does not support dynamic client registration"); } registrationUrl = new URL(metadata.registration_endpoint); } else { registrationUrl = new URL("/register", authorizationServerUrl); } const response = await (fetchFn ?? fetch)(registrationUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...clientMetadata, ...scope !== void 0 ? { scope } : {} }) }); if (!response.ok) { throw await parseErrorResponse(response); } return OAuthClientInformationFullSchema.parse(await response.json()); } // node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js var SseError = class extends Error { constructor(code, message, event) { super(`SSE error: ${message}`); this.code = code; this.event = event; } }; var SSEClientTransport = class { constructor(url2, opts) { this._url = url2; this._resourceMetadataUrl = void 0; this._scope = void 0; this._eventSourceInit = opts?.eventSourceInit; this._requestInit = opts?.requestInit; this._authProvider = opts?.authProvider; this._fetch = opts?.fetch; this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); } async _authThenStart() { if (!this._authProvider) { throw new UnauthorizedError("No auth provider"); } let result; try { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, scope: this._scope, fetchFn: this._fetchWithInit }); } catch (error48) { this.onerror?.(error48); throw error48; } if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } return await this._startOrAuth(); } async _commonHeaders() { const headers = {}; if (this._authProvider) { const tokens = await this._authProvider.tokens(); if (tokens) { headers["Authorization"] = `Bearer ${tokens.access_token}`; } } if (this._protocolVersion) { headers["mcp-protocol-version"] = this._protocolVersion; } const extraHeaders = normalizeHeaders(this._requestInit?.headers); return new Headers({ ...headers, ...extraHeaders }); } _startOrAuth() { const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch; return new Promise((resolve, reject) => { this._eventSource = new EventSource(this._url.href, { ...this._eventSourceInit, fetch: async (url2, init) => { const headers = await this._commonHeaders(); headers.set("Accept", "text/event-stream"); const response = await fetchImpl(url2, { ...init, headers }); if (response.status === 401 && response.headers.has("www-authenticate")) { const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); this._resourceMetadataUrl = resourceMetadataUrl; this._scope = scope; } return response; } }); this._abortController = new AbortController(); this._eventSource.onerror = (event) => { if (event.code === 401 && this._authProvider) { this._authThenStart().then(resolve, reject); return; } const error48 = new SseError(event.code, event.message, event); reject(error48); this.onerror?.(error48); }; this._eventSource.onopen = () => { }; this._eventSource.addEventListener("endpoint", (event) => { const messageEvent = event; try { this._endpoint = new URL(messageEvent.data, this._url); if (this._endpoint.origin !== this._url.origin) { throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); } } catch (error48) { reject(error48); this.onerror?.(error48); void this.close(); return; } resolve(); }); this._eventSource.onmessage = (event) => { const messageEvent = event; let message; try { message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); } catch (error48) { this.onerror?.(error48); return; } this.onmessage?.(message); }; }); } async start() { if (this._eventSource) { throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically."); } return await this._startOrAuth(); } /** * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. */ async finishAuth(authorizationCode) { if (!this._authProvider) { throw new UnauthorizedError("No auth provider"); } const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, scope: this._scope, fetchFn: this._fetchWithInit }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); } } async close() { this._abortController?.abort(); this._eventSource?.close(); this.onclose?.(); } async send(message) { if (!this._endpoint) { throw new Error("Not connected"); } try { const headers = await this._commonHeaders(); headers.set("content-type", "application/json"); const init = { ...this._requestInit, method: "POST", headers, body: JSON.stringify(message), signal: this._abortController?.signal }; const response = await (this._fetch ?? fetch)(this._endpoint, init); if (!response.ok) { const text = await response.text().catch(() => null); if (response.status === 401 && this._authProvider) { const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); this._resourceMetadataUrl = resourceMetadataUrl; this._scope = scope; const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, scope: this._scope, fetchFn: this._fetchWithInit }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } return this.send(message); } throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); } await response.body?.cancel(); } catch (error48) { this.onerror?.(error48); throw error48; } } setProtocolVersion(version2) { this._protocolVersion = version2; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js var import_node_crypto = require("node:crypto"); var import_node_tls = require("node:tls"); // utils/build/raw-body.ts var import_bytes = __toESM(require_bytes()); function getRawBody(req, { limit, encoding }) { const limitNumber = import_bytes.default.parse(limit); return new Promise((resolve, reject) => { let received = 0; const chunks = []; req.on("data", (chunk) => { received += chunk.length; if (received > limitNumber) return reject(new Error(`Message size exceeds limit of ${limit} bytes`)); chunks.push(chunk); }); req.on("end", () => { try { resolve(Buffer.concat(chunks).toString(encoding)); } catch (error48) { reject(error48); } }); req.on("error", (error48) => { reject(error48); }); }); } // node_modules/@modelcontextprotocol/sdk/dist/esm/server/sse.js var import_content_type = __toESM(require_content_type(), 1); var import_node_url = require("node:url"); var MAXIMUM_MESSAGE_SIZE = "4mb"; var SSEServerTransport = class { /** * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. */ constructor(_endpoint, res, options) { this._endpoint = _endpoint; this.res = res; this._sessionId = (0, import_node_crypto.randomUUID)(); this._options = options || { enableDnsRebindingProtection: false }; } /** * Validates request headers for DNS rebinding protection. * @returns Error message if validation fails, undefined if validation passes. */ validateRequestHeaders(req) { if (!this._options.enableDnsRebindingProtection) { return void 0; } if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { const hostHeader = req.headers.host; if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { return `Invalid Host header: ${hostHeader}`; } } if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { const originHeader = req.headers.origin; if (originHeader && !this._options.allowedOrigins.includes(originHeader)) { return `Invalid Origin header: ${originHeader}`; } } return void 0; } /** * Handles the initial SSE connection request. * * This should be called when a GET request is made to establish the SSE stream. */ async start() { if (this._sseResponse) { throw new Error("SSEServerTransport already started! If using Server class, note that connect() calls start() automatically."); } this.res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" }); const dummyBase = "http://localhost"; const endpointUrl = new import_node_url.URL(this._endpoint, dummyBase); endpointUrl.searchParams.set("sessionId", this._sessionId); const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; this.res.write(`event: endpoint data: ${relativeUrlWithSession} `); this._sseResponse = this.res; this.res.on("close", () => { this._sseResponse = void 0; this.onclose?.(); }); } /** * Handles incoming POST messages. * * This should be called when a POST request is made to send a message to the server. */ async handlePostMessage(req, res, parsedBody) { if (!this._sseResponse) { const message = "SSE connection not established"; res.writeHead(500).end(message); throw new Error(message); } const validationError = this.validateRequestHeaders(req); if (validationError) { res.writeHead(403).end(validationError); this.onerror?.(new Error(validationError)); return; } const authInfo = req.auth; const host = req.headers.host; const protocol = req.socket instanceof import_node_tls.TLSSocket ? "https" : "http"; const fullUrl = host && req.url ? new import_node_url.URL(req.url, `${protocol}://${host}`) : void 0; const requestInfo = { headers: req.headers, url: fullUrl }; let body; try { const ct = import_content_type.default.parse(req.headers["content-type"] ?? ""); if (ct.type !== "application/json") { throw new Error(`Unsupported content-type: ${ct.type}`); } body = parsedBody ?? await getRawBody(req, { limit: MAXIMUM_MESSAGE_SIZE, encoding: ct.parameters.charset ?? "utf-8" }); } catch (error48) { res.writeHead(400).end(String(error48)); this.onerror?.(error48); return; } try { await this.handleMessage(typeof body === "string" ? JSON.parse(body) : body, { requestInfo, authInfo }); } catch { res.writeHead(400).end(`Invalid message: ${body}`); return; } res.writeHead(202).end("Accepted"); } /** * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. */ async handleMessage(message, extra) { let parsedMessage; try { parsedMessage = JSONRPCMessageSchema.parse(message); } catch (error48) { this.onerror?.(error48); throw error48; } this.onmessage?.(parsedMessage, extra); } async close() { this._sseResponse?.end(); this._sseResponse = void 0; this.onclose?.(); } async send(message) { if (!this._sseResponse) { throw new Error("Not connected"); } this._sseResponse.write(`event: message data: ${JSON.stringify(message)} `); } /** * Returns the session ID for this transport. * * This can be used to route incoming POST requests. */ get sessionId() { return this._sessionId; } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js var import_cross_spawn = __toESM(require_cross_spawn(), 1); var import_node_process = __toESM(require("node:process"), 1); var import_node_stream = require("node:stream"); // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js var ReadBuffer = class { append(chunk) { this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; } readMessage() { if (!this._buffer) { return null; } const index = this._buffer.indexOf("\n"); if (index === -1) { return null; } const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); this._buffer = this._buffer.subarray(index + 1); return deserializeMessage(line); } clear() { this._buffer = void 0; } }; function deserializeMessage(line) { return JSONRPCMessageSchema.parse(JSON.parse(line)); } function serializeMessage(message) { return JSON.stringify(message) + "\n"; } // node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js var DEFAULT_INHERITED_ENV_VARS = import_node_process.default.platform === "win32" ? [ "APPDATA", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "PATH", "PROCESSOR_ARCHITECTURE", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "USERNAME", "USERPROFILE", "PROGRAMFILES" ] : ( /* list inspired by the default env inheritance of sudo */ ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"] ); function getDefaultEnvironment() { const env = {}; for (const key of DEFAULT_INHERITED_ENV_VARS) { const value = import_node_process.default.env[key]; if (value === void 0) { continue; } if (value.startsWith("()")) { continue; } env[key] = value; } return env; } var StdioClientTransport = class { constructor(server) { this._readBuffer = new ReadBuffer(); this._stderrStream = null; this._serverParams = server; if (server.stderr === "pipe" || server.stderr === "overlapped") { this._stderrStream = new import_node_stream.PassThrough(); } } /** * Starts the server process and prepares to communicate with it. */ async start() { if (this._process) { throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically."); } return new Promise((resolve, reject) => { this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], { // merge default env with server env because mcp server needs some env vars env: { ...getDefaultEnvironment(), ...this._serverParams.env }, stdio: ["pipe", "pipe", this._serverParams.stderr ?? "inherit"], shell: false, windowsHide: import_node_process.default.platform === "win32", cwd: this._serverParams.cwd }); this._process.on("error", (error48) => { reject(error48); this.onerror?.(error48); }); this._process.on("spawn", () => { resolve(); }); this._process.on("close", (_code) => { this._process = void 0; this.onclose?.(); }); this._process.stdin?.on("error", (error48) => { this.onerror?.(error48); }); this._process.stdout?.on("data", (chunk) => { this._readBuffer.append(chunk); this.processReadBuffer(); }); this._process.stdout?.on("error", (error48) => { this.onerror?.(error48); }); if (this._stderrStream && this._process.stderr) { this._process.stderr.pipe(this._stderrStream); } }); } /** * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". * * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to * attach listeners before the start method is invoked. This prevents loss of any early * error output emitted by the child process. */ get stderr() { if (this._stderrStream) { return this._stderrStream; } return this._process?.stderr ?? null; } /** * The child process pid spawned by this transport. * * This is only available after the transport has been started. */ get pid() { return this._process?.pid ?? null; } processReadBuffer() { while (true) { try { const message = this._readBuffer.readMessage(); if (message === null) { break; } this.onmessage?.(message); } catch (error48) { this.onerror?.(error48); } } } async close() { if (this._process) { const processToClose = this._process; this._process = void 0; const closePromise = new Promise((resolve) => { processToClose.once("close", () => { resolve(); }); }); try { processToClose.stdin?.end(); } catch { } await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]); if (processToClose.exitCode === null) { try { processToClose.kill("SIGTERM"); } catch { } await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]); } if (processToClose.exitCode === null) { try { processToClose.kill("SIGKILL"); } catch { } } } this._readBuffer.clear(); } send(message) { return new Promise((resolve) => { if (!this._process?.stdin) { throw new Error("Not connected"); } const json2 = serializeMessage(message); if (this._process.stdin.write(json2)) { resolve(); } else { this._process.stdin.once("drain", resolve); } }); } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js var import_node_process2 = __toESM(require("node:process"), 1); var StdioServerTransport = class { constructor(_stdin = import_node_process2.default.stdin, _stdout = import_node_process2.default.stdout) { this._stdin = _stdin; this._stdout = _stdout; this._readBuffer = new ReadBuffer(); this._started = false; this._ondata = (chunk) => { this._readBuffer.append(chunk); this.processReadBuffer(); }; this._onerror = (error48) => { this.onerror?.(error48); }; } /** * Starts listening for messages on stdin. */ async start() { if (this._started) { throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); } this._started = true; this._stdin.on("data", this._ondata); this._stdin.on("error", this._onerror); } processReadBuffer() { while (true) { try { const message = this._readBuffer.readMessage(); if (message === null) { break; } this.onmessage?.(message); } catch (error48) { this.onerror?.(error48); } } } async close() { this._stdin.off("data", this._ondata); this._stdin.off("error", this._onerror); const remainingDataListeners = this._stdin.listenerCount("data"); if (remainingDataListeners === 0) { this._stdin.pause(); } this._readBuffer.clear(); this.onclose?.(); } send(message) { return new Promise((resolve) => { const json2 = serializeMessage(message); if (this._stdout.write(json2)) { resolve(); } else { this._stdout.once("drain", resolve); } }); } }; // node_modules/@hono/node-server/dist/index.mjs var import_http2 = require("http2"); var import_http22 = require("http2"); var import_stream2 = require("stream"); var import_crypto = __toESM(require("crypto"), 1); var RequestError = class extends Error { constructor(message, options) { super(message, options); this.name = "RequestError"; } }; var toRequestError = (e) => { if (e instanceof RequestError) { return e; } return new RequestError(e.message, { cause: e }); }; var GlobalRequest = global.Request; var Request = class extends GlobalRequest { constructor(input, options) { if (typeof input === "object" && getRequestCache in input) { input = input[getRequestCache](); } if (typeof options?.body?.getReader !== "undefined") { ; options.duplex ??= "half"; } super(input, options); } }; var newHeadersFromIncoming = (incoming) => { const headerRecord = []; const rawHeaders = incoming.rawHeaders; for (let i = 0; i < rawHeaders.length; i += 2) { const { [i]: key, [i + 1]: value } = rawHeaders; if (key.charCodeAt(0) !== /*:*/ 58) { headerRecord.push([key, value]); } } return new Headers(headerRecord); }; var wrapBodyStream = Symbol("wrapBodyStream"); var newRequestFromIncoming = (method, url2, headers, incoming, abortController) => { const init = { method, headers, signal: abortController.signal }; if (method === "TRACE") { init.method = "GET"; const req = new Request(url2, init); Object.defineProperty(req, "method", { get() { return "TRACE"; } }); return req; } if (!(method === "GET" || method === "HEAD")) { if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { init.body = new ReadableStream({ start(controller) { controller.enqueue(incoming.rawBody); controller.close(); } }); } else if (incoming[wrapBodyStream]) { let reader; init.body = new ReadableStream({ async pull(controller) { try { reader ||= import_stream2.Readable.toWeb(incoming).getReader(); const { done, value } = await reader.read(); if (done) { controller.close(); } else { controller.enqueue(value); } } catch (error48) { controller.error(error48); } } }); } else { init.body = import_stream2.Readable.toWeb(incoming); } } return new Request(url2, init); }; var getRequestCache = Symbol("getRequestCache"); var requestCache = Symbol("requestCache"); var incomingKey = Symbol("incomingKey"); var urlKey = Symbol("urlKey"); var headersKey = Symbol("headersKey"); var abortControllerKey = Symbol("abortControllerKey"); var getAbortController = Symbol("getAbortController"); var requestPrototype = { get method() { return this[incomingKey].method || "GET"; }, get url() { return this[urlKey]; }, get headers() { return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]); }, [getAbortController]() { this[getRequestCache](); return this[abortControllerKey]; }, [getRequestCache]() { this[abortControllerKey] ||= new AbortController(); return this[requestCache] ||= newRequestFromIncoming( this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey] ); } }; [ "body", "bodyUsed", "cache", "credentials", "destination", "integrity", "mode", "redirect", "referrer", "referrerPolicy", "signal", "keepalive" ].forEach((k) => { Object.defineProperty(requestPrototype, k, { get() { return this[getRequestCache]()[k]; } }); }); ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { Object.defineProperty(requestPrototype, k, { value: function() { return this[getRequestCache]()[k](); } }); }); Object.setPrototypeOf(requestPrototype, Request.prototype); var newRequest = (incoming, defaultHostname) => { const req = Object.create(requestPrototype); req[incomingKey] = incoming; const incomingUrl = incoming.url || ""; if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL. (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { if (incoming instanceof import_http22.Http2ServerRequest) { throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); } try { const url22 = new URL(incomingUrl); req[urlKey] = url22.href; } catch (e) { throw new RequestError("Invalid absolute URL", { cause: e }); } return req; } const host = (incoming instanceof import_http22.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; if (!host) { throw new RequestError("Missing host header"); } let scheme; if (incoming instanceof import_http22.Http2ServerRequest) { scheme = incoming.scheme; if (!(scheme === "http" || scheme === "https")) { throw new RequestError("Unsupported scheme"); } } else { scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; } const url2 = new URL(`${scheme}://${host}${incomingUrl}`); if (url2.hostname.length !== host.length && url2.hostname !== host.replace(/:\d+$/, "")) { throw new RequestError("Invalid host header"); } req[urlKey] = url2.href; return req; }; var responseCache = Symbol("responseCache"); var getResponseCache = Symbol("getResponseCache"); var cacheKey = Symbol("cache"); var GlobalResponse = global.Response; var Response2 = class _Response { #body; #init; [getResponseCache]() { delete this[cacheKey]; return this[responseCache] ||= new GlobalResponse(this.#body, this.#init); } constructor(body, init) { let headers; this.#body = body; if (init instanceof _Response) { const cachedGlobalResponse = init[responseCache]; if (cachedGlobalResponse) { this.#init = cachedGlobalResponse; this[getResponseCache](); return; } else { this.#init = init.#init; headers = new Headers(init.#init.headers); } } else { this.#init = init; } if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { ; this[cacheKey] = [init?.status || 200, body, headers || init?.headers]; } } get headers() { const cache = this[cacheKey]; if (cache) { if (!(cache[2] instanceof Headers)) { cache[2] = new Headers( cache[2] || { "content-type": "text/plain; charset=UTF-8" } ); } return cache[2]; } return this[getResponseCache]().headers; } get status() { return this[cacheKey]?.[0] ?? this[getResponseCache]().status; } get ok() { const status = this.status; return status >= 200 && status < 300; } }; ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => { Object.defineProperty(Response2.prototype, k, { get() { return this[getResponseCache]()[k]; } }); }); ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => { Object.defineProperty(Response2.prototype, k, { value: function() { return this[getResponseCache]()[k](); } }); }); Object.setPrototypeOf(Response2, GlobalResponse); Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); async function readWithoutBlocking(readPromise) { return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]); } function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { const cancel = (error48) => { reader.cancel(error48).catch(() => { }); }; writable.on("close", cancel); writable.on("error", cancel); (currentReadPromise ?? reader.read()).then(flow, handleStreamError); return reader.closed.finally(() => { writable.off("close", cancel); writable.off("error", cancel); }); function handleStreamError(error48) { if (error48) { writable.destroy(error48); } } function onDrain() { reader.read().then(flow, handleStreamError); } function flow({ done, value }) { try { if (done) { writable.end(); } else if (!writable.write(value)) { writable.once("drain", onDrain); } else { return reader.read().then(flow, handleStreamError); } } catch (e) { handleStreamError(e); } } } function writeFromReadableStream(stream, writable) { if (stream.locked) { throw new TypeError("ReadableStream is locked."); } else if (writable.destroyed) { return; } return writeFromReadableStreamDefaultReader(stream.getReader(), writable); } var buildOutgoingHttpHeaders = (headers) => { const res = {}; if (!(headers instanceof Headers)) { headers = new Headers(headers ?? void 0); } const cookies = []; for (const [k, v] of headers) { if (k === "set-cookie") { cookies.push(v); } else { res[k] = v; } } if (cookies.length > 0) { res["set-cookie"] = cookies; } res["content-type"] ??= "text/plain; charset=UTF-8"; return res; }; var X_ALREADY_SENT = "x-hono-already-sent"; if (typeof global.crypto === "undefined") { global.crypto = import_crypto.default; } var outgoingEnded = Symbol("outgoingEnded"); var handleRequestError = () => new Response(null, { status: 400 }); var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 }); var handleResponseError = (e, outgoing) => { const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { console.info("The user aborted a request."); } else { console.error(e); if (!outgoing.headersSent) { outgoing.writeHead(500, { "Content-Type": "text/plain" }); } outgoing.end(`Error: ${err.message}`); outgoing.destroy(err); } }; var flushHeaders = (outgoing) => { if ("flushHeaders" in outgoing && outgoing.writable) { outgoing.flushHeaders(); } }; var responseViaCache = async (res, outgoing) => { let [status, body, header] = res[cacheKey]; let hasContentLength = false; if (!header) { header = { "content-type": "text/plain; charset=UTF-8" }; } else if (header instanceof Headers) { hasContentLength = header.has("content-length"); header = buildOutgoingHttpHeaders(header); } else if (Array.isArray(header)) { const headerObj = new Headers(header); hasContentLength = headerObj.has("content-length"); header = buildOutgoingHttpHeaders(headerObj); } else { for (const key in header) { if (key.length === 14 && key.toLowerCase() === "content-length") { hasContentLength = true; break; } } } if (!hasContentLength) { if (typeof body === "string") { header["Content-Length"] = Buffer.byteLength(body); } else if (body instanceof Uint8Array) { header["Content-Length"] = body.byteLength; } else if (body instanceof Blob) { header["Content-Length"] = body.size; } } outgoing.writeHead(status, header); if (typeof body === "string" || body instanceof Uint8Array) { outgoing.end(body); } else if (body instanceof Blob) { outgoing.end(new Uint8Array(await body.arrayBuffer())); } else { flushHeaders(outgoing); await writeFromReadableStream(body, outgoing)?.catch( (e) => handleResponseError(e, outgoing) ); } ; outgoing[outgoingEnded]?.(); }; var isPromise = (res) => typeof res.then === "function"; var responseViaResponseObject = async (res, outgoing, options = {}) => { if (isPromise(res)) { if (options.errorHandler) { try { res = await res; } catch (err) { const errRes = await options.errorHandler(err); if (!errRes) { return; } res = errRes; } } else { res = await res.catch(handleFetchError); } } if (cacheKey in res) { return responseViaCache(res, outgoing); } const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); if (res.body) { const reader = res.body.getReader(); const values = []; let done = false; let currentReadPromise = void 0; if (resHeaderRecord["transfer-encoding"] !== "chunked") { let maxReadCount = 2; for (let i = 0; i < maxReadCount; i++) { currentReadPromise ||= reader.read(); const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { console.error(e); done = true; }); if (!chunk) { if (i === 1) { await new Promise((resolve) => setTimeout(resolve)); maxReadCount = 3; continue; } break; } currentReadPromise = void 0; if (chunk.value) { values.push(chunk.value); } if (chunk.done) { done = true; break; } } if (done && !("content-length" in resHeaderRecord)) { resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); } } outgoing.writeHead(res.status, resHeaderRecord); values.forEach((value) => { ; outgoing.write(value); }); if (done) { outgoing.end(); } else { if (values.length === 0) { flushHeaders(outgoing); } await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); } } else if (resHeaderRecord[X_ALREADY_SENT]) { } else { outgoing.writeHead(res.status, resHeaderRecord); outgoing.end(); } ; outgoing[outgoingEnded]?.(); }; var getRequestListener = (fetchCallback, options = {}) => { const autoCleanupIncoming = options.autoCleanupIncoming ?? true; if (options.overrideGlobalObjects !== false && global.Request !== Request) { Object.defineProperty(global, "Request", { value: Request }); Object.defineProperty(global, "Response", { value: Response2 }); } return async (incoming, outgoing) => { let res, req; try { req = newRequest(incoming, options.hostname); let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; if (!incomingEnded) { ; incoming[wrapBodyStream] = true; incoming.on("end", () => { incomingEnded = true; }); if (incoming instanceof import_http2.Http2ServerRequest) { ; outgoing[outgoingEnded] = () => { if (!incomingEnded) { setTimeout(() => { if (!incomingEnded) { setTimeout(() => { incoming.destroy(); outgoing.destroy(); }); } }); } }; } } outgoing.on("close", () => { const abortController = req[abortControllerKey]; if (abortController) { if (incoming.errored) { req[abortControllerKey].abort(incoming.errored.toString()); } else if (!outgoing.writableFinished) { req[abortControllerKey].abort("Client connection prematurely closed."); } } if (!incomingEnded) { setTimeout(() => { if (!incomingEnded) { setTimeout(() => { incoming.destroy(); }); } }); } }); res = fetchCallback(req, { incoming, outgoing }); if (cacheKey in res) { return responseViaCache(res, outgoing); } } catch (e) { if (!res) { if (options.errorHandler) { res = await options.errorHandler(req ? e : toRequestError(e)); if (!res) { return; } } else if (!req) { res = handleRequestError(); } else { res = handleFetchError(e); } } else { return handleResponseError(e, outgoing); } } try { return await responseViaResponseObject(res, outgoing, options); } catch (e) { return handleResponseError(e, outgoing); } }; }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js var WebStandardStreamableHTTPServerTransport = class { constructor(options = {}) { this._started = false; this._hasHandledRequest = false; this._streamMapping = /* @__PURE__ */ new Map(); this._requestToStreamMapping = /* @__PURE__ */ new Map(); this._requestResponseMap = /* @__PURE__ */ new Map(); this._initialized = false; this._enableJsonResponse = false; this._standaloneSseStreamId = "_GET_stream"; this.sessionIdGenerator = options.sessionIdGenerator; this._enableJsonResponse = options.enableJsonResponse ?? false; this._eventStore = options.eventStore; this._onsessioninitialized = options.onsessioninitialized; this._onsessionclosed = options.onsessionclosed; this._allowedHosts = options.allowedHosts; this._allowedOrigins = options.allowedOrigins; this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; this._retryInterval = options.retryInterval; } /** * Starts the transport. This is required by the Transport interface but is a no-op * for the Streamable HTTP transport as connections are managed per-request. */ async start() { if (this._started) { throw new Error("Transport already started"); } this._started = true; } /** * Helper to create a JSON error response */ createJsonErrorResponse(status, code, message, options) { const error48 = { code, message }; if (options?.data !== void 0) { error48.data = options.data; } return new Response(JSON.stringify({ jsonrpc: "2.0", error: error48, id: null }), { status, headers: { "Content-Type": "application/json", ...options?.headers } }); } /** * Validates request headers for DNS rebinding protection. * @returns Error response if validation fails, undefined if validation passes. */ validateRequestHeaders(req) { if (!this._enableDnsRebindingProtection) { return void 0; } if (this._allowedHosts && this._allowedHosts.length > 0) { const hostHeader = req.headers.get("host"); if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { const error48 = `Invalid Host header: ${hostHeader}`; this.onerror?.(new Error(error48)); return this.createJsonErrorResponse(403, -32e3, error48); } } if (this._allowedOrigins && this._allowedOrigins.length > 0) { const originHeader = req.headers.get("origin"); if (originHeader && !this._allowedOrigins.includes(originHeader)) { const error48 = `Invalid Origin header: ${originHeader}`; this.onerror?.(new Error(error48)); return this.createJsonErrorResponse(403, -32e3, error48); } } return void 0; } /** * Handles an incoming HTTP request, whether GET, POST, or DELETE * Returns a Response object (Web Standard) */ async handleRequest(req, options) { if (!this.sessionIdGenerator && this._hasHandledRequest) { throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request."); } this._hasHandledRequest = true; const validationError = this.validateRequestHeaders(req); if (validationError) { return validationError; } switch (req.method) { case "POST": return this.handlePostRequest(req, options); case "GET": return this.handleGetRequest(req); case "DELETE": return this.handleDeleteRequest(req); default: return this.handleUnsupportedRequest(); } } /** * Writes a priming event to establish resumption capability. * Only sends if eventStore is configured (opt-in for resumability) and * the client's protocol version supports empty SSE data (>= 2025-11-25). */ async writePrimingEvent(controller, encoder, streamId, protocolVersion) { if (!this._eventStore) { return; } if (protocolVersion < "2025-11-25") { return; } const primingEventId = await this._eventStore.storeEvent(streamId, {}); let primingEvent = `id: ${primingEventId} data: `; if (this._retryInterval !== void 0) { primingEvent = `id: ${primingEventId} retry: ${this._retryInterval} data: `; } controller.enqueue(encoder.encode(primingEvent)); } /** * Handles GET requests for SSE stream */ async handleGetRequest(req) { const acceptHeader = req.headers.get("accept"); if (!acceptHeader?.includes("text/event-stream")) { this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream")); return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); } const sessionError = this.validateSession(req); if (sessionError) { return sessionError; } const protocolError = this.validateProtocolVersion(req); if (protocolError) { return protocolError; } if (this._eventStore) { const lastEventId = req.headers.get("last-event-id"); if (lastEventId) { return this.replayEvents(lastEventId); } } if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session")); return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); } const encoder = new TextEncoder(); let streamController; const readable = new ReadableStream({ start: (controller) => { streamController = controller; }, cancel: () => { this._streamMapping.delete(this._standaloneSseStreamId); } }); const headers = { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" }; if (this.sessionId !== void 0) { headers["mcp-session-id"] = this.sessionId; } this._streamMapping.set(this._standaloneSseStreamId, { controller: streamController, encoder, cleanup: () => { this._streamMapping.delete(this._standaloneSseStreamId); try { streamController.close(); } catch { } } }); return new Response(readable, { headers }); } /** * Replays events that would have been sent after the specified event ID * Only used when resumability is enabled */ async replayEvents(lastEventId) { if (!this._eventStore) { this.onerror?.(new Error("Event store not configured")); return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); } try { let streamId; if (this._eventStore.getStreamIdForEventId) { streamId = await this._eventStore.getStreamIdForEventId(lastEventId); if (!streamId) { this.onerror?.(new Error("Invalid event ID format")); return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); } if (this._streamMapping.get(streamId) !== void 0) { this.onerror?.(new Error("Conflict: Stream already has an active connection")); return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); } } const headers = { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" }; if (this.sessionId !== void 0) { headers["mcp-session-id"] = this.sessionId; } const encoder = new TextEncoder(); let streamController; const readable = new ReadableStream({ start: (controller) => { streamController = controller; }, cancel: () => { } }); const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { const success2 = this.writeSSEEvent(streamController, encoder, message, eventId); if (!success2) { this.onerror?.(new Error("Failed replay events")); try { streamController.close(); } catch { } } } }); this._streamMapping.set(replayedStreamId, { controller: streamController, encoder, cleanup: () => { this._streamMapping.delete(replayedStreamId); try { streamController.close(); } catch { } } }); return new Response(readable, { headers }); } catch (error48) { this.onerror?.(error48); return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); } } /** * Writes an event to an SSE stream via controller with proper formatting */ writeSSEEvent(controller, encoder, message, eventId) { try { let eventData = `event: message `; if (eventId) { eventData += `id: ${eventId} `; } eventData += `data: ${JSON.stringify(message)} `; controller.enqueue(encoder.encode(eventData)); return true; } catch (error48) { this.onerror?.(error48); return false; } } /** * Handles unsupported requests (PUT, PATCH, etc.) */ handleUnsupportedRequest() { this.onerror?.(new Error("Method not allowed.")); return new Response(JSON.stringify({ jsonrpc: "2.0", error: { code: -32e3, message: "Method not allowed." }, id: null }), { status: 405, headers: { Allow: "GET, POST, DELETE", "Content-Type": "application/json" } }); } /** * Handles POST requests containing JSON-RPC messages */ async handlePostRequest(req, options) { try { const acceptHeader = req.headers.get("accept"); if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); } const ct = req.headers.get("content-type"); if (!ct || !ct.includes("application/json")) { this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")); return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); } const requestInfo = { headers: Object.fromEntries(req.headers.entries()), url: new URL(req.url) }; let rawMessage; if (options?.parsedBody !== void 0) { rawMessage = options.parsedBody; } else { try { rawMessage = await req.json(); } catch { this.onerror?.(new Error("Parse error: Invalid JSON")); return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); } } let messages; try { if (Array.isArray(rawMessage)) { messages = rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)); } else { messages = [JSONRPCMessageSchema.parse(rawMessage)]; } } catch { this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")); return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); } const isInitializationRequest = messages.some(isInitializeRequest); if (isInitializationRequest) { if (this._initialized && this.sessionId !== void 0) { this.onerror?.(new Error("Invalid Request: Server already initialized")); return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); } if (messages.length > 1) { this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")); return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); } this.sessionId = this.sessionIdGenerator?.(); this._initialized = true; if (this.sessionId && this._onsessioninitialized) { await Promise.resolve(this._onsessioninitialized(this.sessionId)); } } if (!isInitializationRequest) { const sessionError = this.validateSession(req); if (sessionError) { return sessionError; } const protocolError = this.validateProtocolVersion(req); if (protocolError) { return protocolError; } } const hasRequests = messages.some(isJSONRPCRequest); if (!hasRequests) { for (const message of messages) { this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); } return new Response(null, { status: 202 }); } const streamId = crypto.randomUUID(); const initRequest = messages.find((m) => isInitializeRequest(m)); const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; if (this._enableJsonResponse) { return new Promise((resolve) => { this._streamMapping.set(streamId, { resolveJson: resolve, cleanup: () => { this._streamMapping.delete(streamId); } }); for (const message of messages) { if (isJSONRPCRequest(message)) { this._requestToStreamMapping.set(message.id, streamId); } } for (const message of messages) { this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); } }); } const encoder = new TextEncoder(); let streamController; const readable = new ReadableStream({ start: (controller) => { streamController = controller; }, cancel: () => { this._streamMapping.delete(streamId); } }); const headers = { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" }; if (this.sessionId !== void 0) { headers["mcp-session-id"] = this.sessionId; } for (const message of messages) { if (isJSONRPCRequest(message)) { this._streamMapping.set(streamId, { controller: streamController, encoder, cleanup: () => { this._streamMapping.delete(streamId); try { streamController.close(); } catch { } } }); this._requestToStreamMapping.set(message.id, streamId); } } await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); for (const message of messages) { let closeSSEStream; let closeStandaloneSSEStream; if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= "2025-11-25") { closeSSEStream = () => { this.closeSSEStream(message.id); }; closeStandaloneSSEStream = () => { this.closeStandaloneSSEStream(); }; } this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream }); } return new Response(readable, { status: 200, headers }); } catch (error48) { this.onerror?.(error48); return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error48) }); } } /** * Handles DELETE requests to terminate sessions */ async handleDeleteRequest(req) { const sessionError = this.validateSession(req); if (sessionError) { return sessionError; } const protocolError = this.validateProtocolVersion(req); if (protocolError) { return protocolError; } await Promise.resolve(this._onsessionclosed?.(this.sessionId)); await this.close(); return new Response(null, { status: 200 }); } /** * Validates session ID for non-initialization requests. * Returns Response error if invalid, undefined otherwise */ validateSession(req) { if (this.sessionIdGenerator === void 0) { return void 0; } if (!this._initialized) { this.onerror?.(new Error("Bad Request: Server not initialized")); return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); } const sessionId = req.headers.get("mcp-session-id"); if (!sessionId) { this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")); return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); } if (sessionId !== this.sessionId) { this.onerror?.(new Error("Session not found")); return this.createJsonErrorResponse(404, -32001, "Session not found"); } return void 0; } /** * Validates the MCP-Protocol-Version header on incoming requests. * * For initialization: Version negotiation handles unknown versions gracefully * (server responds with its supported version). * * For subsequent requests with MCP-Protocol-Version header: * - Accept if in supported list * - 400 if unsupported * * For HTTP requests without the MCP-Protocol-Version header: * - Accept and default to the version negotiated at initialization */ validateProtocolVersion(req) { const protocolVersion = req.headers.get("mcp-protocol-version"); if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`)); return this.createJsonErrorResponse(400, -32e3, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`); } return void 0; } async close() { this._streamMapping.forEach(({ cleanup }) => { cleanup(); }); this._streamMapping.clear(); this._requestResponseMap.clear(); this.onclose?.(); } /** * Close an SSE stream for a specific request, triggering client reconnection. * Use this to implement polling behavior during long-running operations - * client will reconnect after the retry interval specified in the priming event. */ closeSSEStream(requestId) { const streamId = this._requestToStreamMapping.get(requestId); if (!streamId) return; const stream = this._streamMapping.get(streamId); if (stream) { stream.cleanup(); } } /** * Close the standalone GET SSE stream, triggering client reconnection. * Use this to implement polling behavior for server-initiated notifications. */ closeStandaloneSSEStream() { const stream = this._streamMapping.get(this._standaloneSseStreamId); if (stream) { stream.cleanup(); } } async send(message, options) { let requestId = options?.relatedRequestId; if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { requestId = message.id; } if (requestId === void 0) { if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); } let eventId; if (this._eventStore) { eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); } const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); if (standaloneSse === void 0) { return; } if (standaloneSse.controller && standaloneSse.encoder) { this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); } return; } const streamId = this._requestToStreamMapping.get(requestId); if (!streamId) { throw new Error(`No connection established for request ID: ${String(requestId)}`); } const stream = this._streamMapping.get(streamId); if (!this._enableJsonResponse && stream?.controller && stream?.encoder) { let eventId; if (this._eventStore) { eventId = await this._eventStore.storeEvent(streamId, message); } this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); } if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { this._requestResponseMap.set(requestId, message); const relatedIds = Array.from(this._requestToStreamMapping.entries()).filter(([_, sid]) => sid === streamId).map(([id]) => id); const allResponsesReady = relatedIds.every((id) => this._requestResponseMap.has(id)); if (allResponsesReady) { if (!stream) { throw new Error(`No connection established for request ID: ${String(requestId)}`); } if (this._enableJsonResponse && stream.resolveJson) { const headers = { "Content-Type": "application/json" }; if (this.sessionId !== void 0) { headers["mcp-session-id"] = this.sessionId; } const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); if (responses.length === 1) { stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers })); } else { stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers })); } } else { stream.cleanup(); } for (const id of relatedIds) { this._requestResponseMap.delete(id); this._requestToStreamMapping.delete(id); } } } } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js var StreamableHTTPServerTransport = class { constructor(options = {}) { this._requestContext = /* @__PURE__ */ new WeakMap(); this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options); this._requestListener = getRequestListener(async (webRequest) => { const context = this._requestContext.get(webRequest); return this._webStandardTransport.handleRequest(webRequest, { authInfo: context?.authInfo, parsedBody: context?.parsedBody }); }, { overrideGlobalObjects: false }); } /** * Gets the session ID for this transport instance. */ get sessionId() { return this._webStandardTransport.sessionId; } /** * Sets callback for when the transport is closed. */ set onclose(handler) { this._webStandardTransport.onclose = handler; } get onclose() { return this._webStandardTransport.onclose; } /** * Sets callback for transport errors. */ set onerror(handler) { this._webStandardTransport.onerror = handler; } get onerror() { return this._webStandardTransport.onerror; } /** * Sets callback for incoming messages. */ set onmessage(handler) { this._webStandardTransport.onmessage = handler; } get onmessage() { return this._webStandardTransport.onmessage; } /** * Starts the transport. This is required by the Transport interface but is a no-op * for the Streamable HTTP transport as connections are managed per-request. */ async start() { return this._webStandardTransport.start(); } /** * Closes the transport and all active connections. */ async close() { return this._webStandardTransport.close(); } /** * Sends a JSON-RPC message through the transport. */ async send(message, options) { return this._webStandardTransport.send(message, options); } /** * Handles an incoming HTTP request, whether GET or POST. * * This method converts Node.js HTTP objects to Web Standard Request/Response * and delegates to the underlying WebStandardStreamableHTTPServerTransport. * * @param req - Node.js IncomingMessage, optionally with auth property from middleware * @param res - Node.js ServerResponse * @param parsedBody - Optional pre-parsed body from body-parser middleware */ async handleRequest(req, res, parsedBody) { const authInfo = req.auth; const handler = getRequestListener(async (webRequest) => { return this._webStandardTransport.handleRequest(webRequest, { authInfo, parsedBody }); }, { overrideGlobalObjects: false }); await handler(req, res); } /** * Close an SSE stream for a specific request, triggering client reconnection. * Use this to implement polling behavior during long-running operations - * client will reconnect after the retry interval specified in the priming event. */ closeSSEStream(requestId) { this._webStandardTransport.closeSSEStream(requestId); } /** * Close the standalone GET SSE stream, triggering client reconnection. * Use this to implement polling behavior for server-initiated notifications. */ closeStandaloneSSEStream() { this._webStandardTransport.closeStandaloneSSEStream(); } }; // node_modules/eventsource-parser/dist/stream.js var EventSourceParserStream = class extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser({ onEvent: (event) => { controller.enqueue(event); }, onError(error48) { onError === "terminate" ? controller.error(error48) : typeof onError == "function" && onError(error48); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; // node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { initialReconnectionDelay: 1e3, maxReconnectionDelay: 3e4, reconnectionDelayGrowFactor: 1.5, maxRetries: 2 }; var StreamableHTTPError = class extends Error { constructor(code, message) { super(`Streamable HTTP error: ${message}`); this.code = code; } }; var StreamableHTTPClientTransport = class { constructor(url2, opts) { this._hasCompletedAuthFlow = false; this._url = url2; this._resourceMetadataUrl = void 0; this._scope = void 0; this._requestInit = opts?.requestInit; this._authProvider = opts?.authProvider; this._fetch = opts?.fetch; this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); this._sessionId = opts?.sessionId; this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; } async _authThenStart() { if (!this._authProvider) { throw new UnauthorizedError("No auth provider"); } let result; try { result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, scope: this._scope, fetchFn: this._fetchWithInit }); } catch (error48) { this.onerror?.(error48); throw error48; } if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } return await this._startOrAuthSse({ resumptionToken: void 0 }); } async _commonHeaders() { const headers = {}; if (this._authProvider) { const tokens = await this._authProvider.tokens(); if (tokens) { headers["Authorization"] = `Bearer ${tokens.access_token}`; } } if (this._sessionId) { headers["mcp-session-id"] = this._sessionId; } if (this._protocolVersion) { headers["mcp-protocol-version"] = this._protocolVersion; } const extraHeaders = normalizeHeaders(this._requestInit?.headers); return new Headers({ ...headers, ...extraHeaders }); } async _startOrAuthSse(options) { const { resumptionToken } = options; try { const headers = await this._commonHeaders(); headers.set("Accept", "text/event-stream"); if (resumptionToken) { headers.set("last-event-id", resumptionToken); } const response = await (this._fetch ?? fetch)(this._url, { method: "GET", headers, signal: this._abortController?.signal }); if (!response.ok) { await response.body?.cancel(); if (response.status === 401 && this._authProvider) { return await this._authThenStart(); } if (response.status === 405) { return; } throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); } this._handleSseStream(response.body, options, true); } catch (error48) { this.onerror?.(error48); throw error48; } } /** * Calculates the next reconnection delay using backoff algorithm * * @param attempt Current reconnection attempt count for the specific stream * @returns Time to wait in milliseconds before next reconnection attempt */ _getNextReconnectionDelay(attempt) { if (this._serverRetryMs !== void 0) { return this._serverRetryMs; } const initialDelay = this._reconnectionOptions.initialReconnectionDelay; const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; const maxDelay = this._reconnectionOptions.maxReconnectionDelay; return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); } /** * Schedule a reconnection attempt using server-provided retry interval or backoff * * @param lastEventId The ID of the last received event for resumability * @param attemptCount Current reconnection attempt count for this specific stream */ _scheduleReconnection(options, attemptCount = 0) { const maxRetries = this._reconnectionOptions.maxRetries; if (attemptCount >= maxRetries) { this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); return; } const delay = this._getNextReconnectionDelay(attemptCount); this._reconnectionTimeout = setTimeout(() => { this._startOrAuthSse(options).catch((error48) => { this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error48 instanceof Error ? error48.message : String(error48)}`)); this._scheduleReconnection(options, attemptCount + 1); }); }, delay); } _handleSseStream(stream, options, isReconnectable) { if (!stream) { return; } const { onresumptiontoken, replayMessageId } = options; let lastEventId; let hasPrimingEvent = false; let receivedResponse = false; const processStream = async () => { try { const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ onRetry: (retryMs) => { this._serverRetryMs = retryMs; } })).getReader(); while (true) { const { value: event, done } = await reader.read(); if (done) { break; } if (event.id) { lastEventId = event.id; hasPrimingEvent = true; onresumptiontoken?.(event.id); } if (!event.data) { continue; } if (!event.event || event.event === "message") { try { const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); if (isJSONRPCResultResponse(message)) { receivedResponse = true; if (replayMessageId !== void 0) { message.id = replayMessageId; } } this.onmessage?.(message); } catch (error48) { this.onerror?.(error48); } } } const canResume = isReconnectable || hasPrimingEvent; const needsReconnect = canResume && !receivedResponse; if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { this._scheduleReconnection({ resumptionToken: lastEventId, onresumptiontoken, replayMessageId }, 0); } } catch (error48) { this.onerror?.(new Error(`SSE stream disconnected: ${error48}`)); const canResume = isReconnectable || hasPrimingEvent; const needsReconnect = canResume && !receivedResponse; if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { try { this._scheduleReconnection({ resumptionToken: lastEventId, onresumptiontoken, replayMessageId }, 0); } catch (error49) { this.onerror?.(new Error(`Failed to reconnect: ${error49 instanceof Error ? error49.message : String(error49)}`)); } } } }; processStream(); } async start() { if (this._abortController) { throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically."); } this._abortController = new AbortController(); } /** * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. */ async finishAuth(authorizationCode) { if (!this._authProvider) { throw new UnauthorizedError("No auth provider"); } const result = await auth(this._authProvider, { serverUrl: this._url, authorizationCode, resourceMetadataUrl: this._resourceMetadataUrl, scope: this._scope, fetchFn: this._fetchWithInit }); if (result !== "AUTHORIZED") { throw new UnauthorizedError("Failed to authorize"); } } async close() { if (this._reconnectionTimeout) { clearTimeout(this._reconnectionTimeout); this._reconnectionTimeout = void 0; } this._abortController?.abort(); this.onclose?.(); } async send(message, options) { try { const { resumptionToken, onresumptiontoken } = options || {}; if (resumptionToken) { this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err)); return; } const headers = await this._commonHeaders(); headers.set("content-type", "application/json"); headers.set("accept", "application/json, text/event-stream"); const init = { ...this._requestInit, method: "POST", headers, body: JSON.stringify(message), signal: this._abortController?.signal }; const response = await (this._fetch ?? fetch)(this._url, init); const sessionId = response.headers.get("mcp-session-id"); if (sessionId) { this._sessionId = sessionId; } if (!response.ok) { const text = await response.text().catch(() => null); if (response.status === 401 && this._authProvider) { if (this._hasCompletedAuthFlow) { throw new StreamableHTTPError(401, "Server returned 401 after successful authentication"); } const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); this._resourceMetadataUrl = resourceMetadataUrl; this._scope = scope; const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, scope: this._scope, fetchFn: this._fetchWithInit }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } this._hasCompletedAuthFlow = true; return this.send(message); } if (response.status === 403 && this._authProvider) { const { resourceMetadataUrl, scope, error: error48 } = extractWWWAuthenticateParams(response); if (error48 === "insufficient_scope") { const wwwAuthHeader = response.headers.get("WWW-Authenticate"); if (this._lastUpscopingHeader === wwwAuthHeader) { throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping"); } if (scope) { this._scope = scope; } if (resourceMetadataUrl) { this._resourceMetadataUrl = resourceMetadataUrl; } this._lastUpscopingHeader = wwwAuthHeader ?? void 0; const result = await auth(this._authProvider, { serverUrl: this._url, resourceMetadataUrl: this._resourceMetadataUrl, scope: this._scope, fetchFn: this._fetch }); if (result !== "AUTHORIZED") { throw new UnauthorizedError(); } return this.send(message); } } throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`); } this._hasCompletedAuthFlow = false; this._lastUpscopingHeader = void 0; if (response.status === 202) { await response.body?.cancel(); if (isInitializedNotification(message)) { this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err)); } return; } const messages = Array.isArray(message) ? message : [message]; const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0; const contentType2 = response.headers.get("content-type"); if (hasRequests) { if (contentType2?.includes("text/event-stream")) { this._handleSseStream(response.body, { onresumptiontoken }, false); } else if (contentType2?.includes("application/json")) { const data = await response.json(); const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)]; for (const msg of responseMessages) { this.onmessage?.(msg); } } else { await response.body?.cancel(); throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType2}`); } } else { await response.body?.cancel(); } } catch (error48) { this.onerror?.(error48); throw error48; } } get sessionId() { return this._sessionId; } /** * Terminates the current session by sending a DELETE request to the server. * * Clients that no longer need a particular session * (e.g., because the user is leaving the client application) SHOULD send an * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly * terminate the session. * * The server MAY respond with HTTP 405 Method Not Allowed, indicating that * the server does not allow clients to terminate sessions. */ async terminateSession() { if (!this._sessionId) { return; } try { const headers = await this._commonHeaders(); const init = { ...this._requestInit, method: "DELETE", headers, signal: this._abortController?.signal }; const response = await (this._fetch ?? fetch)(this._url, init); await response.body?.cancel(); if (!response.ok && response.status !== 405) { throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); } this._sessionId = void 0; } catch (error48) { this.onerror?.(error48); throw error48; } } setProtocolVersion(version2) { this._protocolVersion = version2; } get protocolVersion() { return this._protocolVersion; } /** * Resume an SSE stream from a previous event ID. * Opens a GET SSE connection with Last-Event-ID header to replay missed events. * * @param lastEventId The event ID to resume from * @param options Optional callback to receive new resumption tokens */ async resumeStream(lastEventId, options) { await this._startOrAuthSse({ resumptionToken: lastEventId, onresumptiontoken: options?.onresumptiontoken }); } }; // packages/playwright-core/src/utilsBundle.ts var colors = import_safe.default; var debug = import_debug.default; var ini = iniLibrary; var diff = libesm_exports; var dotenv = import_dotenv.default; var jpegjs = import_jpeg_js.default; var mime = import_mime.default; var minimatch = import_minimatch.default; var open = import_open.default; var progress = import_progress.default; var ws = wrapper_default; var wsServer = import_websocket_server.default; var wsReceiver = import_receiver.default; var wsSender = import_sender.default; var yaml = import_yaml.default; var json5 = import_json5.default; var sourceMapSupport = import_source_map_support.default; var enquirer = import_enquirer.default; var chokidar = import_chokidar.default; var getEastAsianWidth = get_east_asian_width_exports; var gracefulFs = gracefulFsLibrary; var retry = import_retry.default; var onExit = import_signal_exit.default; var getStream = import_get_stream.default; var httpProxyAgent = import_https_proxy_agent2.default; var socksProxyAgent = import_socks_proxy_agent2.default; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CallToolRequestSchema, Client, HttpsProxyAgent, ListRootsRequestSchema, ListToolsRequestSchema, PNG, PingRequestSchema, ProgramOption, ProgressNotificationSchema, SSEClientTransport, SSEServerTransport, Server, SocksProxyAgent, StdioClientTransport, StdioServerTransport, StreamableHTTPClientTransport, StreamableHTTPServerTransport, chokidar, colors, debug, diff, dotenv, enquirer, getEastAsianWidth, getProxyForUrl, getStream, gracefulFs, httpProxyAgent, ini, jpegjs, json5, mime, minimatch, onExit, open, program, progress, retry, socksProxyAgent, sourceMapSupport, ws, wsReceiver, wsSender, wsServer, yaml, yazl, z, zodToJsonSchema }); /*! Bundled license information: progress/lib/node-progress.js: (*! * node-progress * Copyright(c) 2011 TJ Holowaychuk * MIT Licensed *) normalize-path/index.js: (*! * normalize-path * * Copyright (c) 2014-2018, Jon Schlinkert. * Released under the MIT License. *) is-extglob/index.js: (*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. *) is-glob/index.js: (*! * is-glob * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. *) is-number/index.js: (*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. *) to-regex-range/index.js: (*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. *) fill-range/index.js: (*! * fill-range * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. *) bytes/index.js: (*! * bytes * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015 Jed Watson * MIT Licensed *) content-type/index.js: (*! * content-type * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed *) */